filename
stringlengths 3
67
| data
stringlengths 0
58.3M
| license
stringlengths 0
19.5k
|
---|---|---|
operation_list_list_hash.mli | (** Blocks hashes / IDs. *)
include S.MERKLE_TREE with type elt = Operation_list_hash.t
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
commitment_storage.mli | val init:
Raw_context.t ->
Commitment_repr.t list ->
Raw_context.t tzresult Lwt.t
val get_opt:
Raw_context.t -> Blinded_public_key_hash.t ->
Tez_repr.t option tzresult Lwt.t
val delete:
Raw_context.t -> Blinded_public_key_hash.t ->
Raw_context.t tzresult Lwt.t
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
voting_period_storage.ml | (*
The shell uses the convention that a context at level n is the resulting
context of the application of block n.
Therefore when using an RPC on the last level of a voting period, the context
that is inspected is the resulting one.
However [Amendment.may_start_new_voting_period] is run at the end of voting
period and it has to prepare the context for validating operations of the next
period. This causes the counter-intuitive result that the info returned by RPCs
at last level of a voting period mention data of the next voting period.
For example, when validating the last block of a proposal period at level n
we have:
- Input context:
voting_period = { kind = Proposal;
index = i;
start_position = n - blocks_per_voting_period}
- position = n - start_position = blocks_per_voting_period
- remaining = blocks_per_voting_period - (position + 1) = 0
- Output context:
voting_period = { kind = Exploration;
index = i + 1;
start_position = n + 1}
Now if we calculate position and remaining in the voting period we get
strange results:
- position = n - (n + 1) = -1
- remaining = blocks_per_voting_period
To work around this issue, two RPCs were added
`Voting_period_storage.get_rpc_current_info`, which returns the correct
info also for the last context of a period, and
`Voting_period_storage.get_rpc_succ_info`, which can be used at the last
context of a period to craft operations that will be valid for the first
block of the new period.
This odd behaviour could be fixed if [Amendment.may_start_new_voting_period]
was called when we start validating the first block of a voting period instead
that at the end of the validation of the last block of a voting period.
This should be carefully done because the voting period listing depends on
the rolls and it might break some invariant.
When this is implemented one should:
- edit the function [reset_current] and [inc_current] to use the
current level and not the next one.
- remove the storage for pred_kind
- make Voting_period_repr.t abstract
You can also look at the MR description here:
https://gitlab.com/metastatedev/tezos/-/merge_requests/333
*)
(* Voting periods start at the first block of a cycle. More formally,
the invariant of start_position with respect to cycle_position is:
cycle_position mod blocks_per_cycle ==
position_in_period mod blocks_per_cycle *)
let set_current = Storage.Vote.Current_period.update
let get_current = Storage.Vote.Current_period.get
let init = Storage.Vote.Current_period.init
let init_first_period ctxt ~start_position =
init ctxt @@ Voting_period_repr.root ~start_position >>=? fun ctxt ->
Storage.Vote.Pred_period_kind.init ctxt Voting_period_repr.Proposal
let common ctxt =
get_current ctxt >>=? fun current_period ->
Storage.Vote.Pred_period_kind.update ctxt current_period.kind >|=? fun ctxt ->
let start_position =
(* because we are preparing the voting period for the next block we need to
use the next level. *)
Int32.succ (Level_storage.current ctxt).level_position
in
(ctxt, current_period, start_position)
let reset ctxt =
common ctxt >>=? fun (ctxt, current_period, start_position) ->
Voting_period_repr.raw_reset current_period ~start_position
|> set_current ctxt
let succ ctxt =
common ctxt >>=? fun (ctxt, current_period, start_position) ->
Voting_period_repr.raw_succ current_period ~start_position |> set_current ctxt
let get_current_kind ctxt = get_current ctxt >|=? fun {kind; _} -> kind
let get_current_info ctxt =
get_current ctxt >|=? fun voting_period ->
let blocks_per_voting_period =
Constants_storage.blocks_per_voting_period ctxt
in
let level = Level_storage.current ctxt in
let position = Voting_period_repr.position_since level voting_period in
let remaining =
Voting_period_repr.remaining_blocks
level
voting_period
~blocks_per_voting_period
in
Voting_period_repr.{voting_period; position; remaining}
let get_current_remaining ctxt =
get_current ctxt >|=? fun voting_period ->
let blocks_per_voting_period =
Constants_storage.blocks_per_voting_period ctxt
in
Voting_period_repr.remaining_blocks
(Level_storage.current ctxt)
voting_period
~blocks_per_voting_period
let is_last_block ctxt =
get_current_remaining ctxt >|=? fun remaining ->
Compare.Int32.(remaining = 0l)
let get_rpc_current_info ctxt =
get_current_info ctxt
>>=? fun ({voting_period; position; _} as voting_period_info) ->
if Compare.Int32.(position = Int32.minus_one) then
let level = Level_storage.current ctxt in
let blocks_per_voting_period =
Constants_storage.blocks_per_voting_period ctxt
in
Storage.Vote.Pred_period_kind.get ctxt >|=? fun pred_kind ->
let voting_period : Voting_period_repr.t =
{
index = Int32.pred voting_period.index;
kind = pred_kind;
start_position =
Int32.(sub voting_period.start_position blocks_per_voting_period);
}
in
let position = Voting_period_repr.position_since level voting_period in
let remaining =
Voting_period_repr.remaining_blocks
level
voting_period
~blocks_per_voting_period
in
({voting_period; remaining; position} : Voting_period_repr.info)
else return voting_period_info
let get_rpc_succ_info ctxt =
Level_storage.from_raw_with_offset
ctxt
~offset:1l
(Level_storage.current ctxt).level
>>?= fun level ->
get_current ctxt >|=? fun voting_period ->
let blocks_per_voting_period =
Constants_storage.blocks_per_voting_period ctxt
in
let position = Voting_period_repr.position_since level voting_period in
let remaining =
Voting_period_repr.remaining_blocks
level
voting_period
~blocks_per_voting_period
in
Voting_period_repr.{voting_period; position; remaining}
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2020 Metastate AG <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
mehari_io.ml |
module Stack = Tcpip_stack_socket.V4V6
include Mehari_mirage.Make (Pclock) (Stack) (Time)
| |
vmm_resources.mli | (* (c) 2017 Hannes Mehnert, all rights reserved *)
(** A tree data structure including policies and dynamic usage.
Considering delegation of resources to someone, and further delegation
to others - using a process which is not controlled by the authority -
requires runtime tracking of these delegations and the actual usage:
If Alice may create 2 virtual machines, and she delegates the same
capability further to both Bob and Charlie, the authority must still enforce
that Alice, Bob, and Charlie are able to run 2 virtual machines in total,
rather than 2 each. *)
open Vmm_core
(** The type of the resource tree. *)
type t = private {
policies : Policy.t Vmm_trie.t ;
block_devices : (int * bool) Vmm_trie.t ;
unikernels : Unikernel.t Vmm_trie.t ;
}
(** [empty] is the empty tree. *)
val empty : t
(** [find_vm t name] is either [Some vm] or [None]. *)
val find_vm : t -> Name.t -> Unikernel.t option
(** [find_policy t path] is either [Some policy] or [None]. *)
val find_policy : t -> Name.path -> Policy.t option
(** [find_block t name] is either [Some (size, active)] or [None]. *)
val find_block : t -> Name.t -> (int * bool) option
(** [check_vm t name vm] checks whether [vm] under [name] in [t] would be
allowed under the current policies. *)
val check_vm : t -> Name.t -> Unikernel.config -> (unit, [> `Msg of string ]) result
(** [insert_vm t name vm] inserts [vm] under [name] in [t], and returns the
new [t]. The caller has to ensure (using {!check_vm}) that a VM with the
same name does not yet exist, and the block device is not in use.
@raise Invalid_argument if block device is already in use, or VM already
exists. *)
val insert_vm : t -> Name.t -> Unikernel.t -> t
(** [insert_policy t path policy] inserts [policy] under [path] in [t], and
returns the new [t] or an error. *)
val insert_policy : t -> Name.path -> Policy.t -> (t, [> `Msg of string]) result
(** [check_block t name size] checks whether [size] under [name] in [t] would be
allowed under the current policies. *)
val check_block : t -> Name.t -> int -> (unit, [> `Msg of string ]) result
(** [insert_block t name size] inserts [size] under [name] in [t], and returns
the new [t] or an error. *)
val insert_block : t -> Name.t -> int -> (t, [> `Msg of string]) result
(** [remove_vm t name] removes vm [name] from [t]. *)
val remove_vm : t -> Name.t -> (t, [> `Msg of string ]) result
(** [remove_policy t path] removes policy [path] from [t]. *)
val remove_policy : t -> Name.path -> (t, [> `Msg of string ]) result
(** [remove_block t name] removes block [name] from [t]. *)
val remove_block : t -> Name.t -> (t, [> `Msg of string ]) result
(** [pp] is a pretty printer for [t]. *)
val pp : t Fmt.t
| (* (c) 2017 Hannes Mehnert, all rights reserved *)
|
dune |
; This file was automatically generated, do not edit.
; Edit file manifest/main.ml instead.
(library
(name tezos_benchmark_015_PtLimaPt)
(public_name tezos-benchmark-015-PtLimaPt)
(libraries
tezos-stdlib
tezos-base
tezos-error-monad
tezos-micheline
tezos-micheline-rewriting
tezos-benchmark
tezos-benchmark-type-inference-015-PtLimaPt
tezos-protocol-015-PtLimaPt
tezos-crypto
tezos-protocol-015-PtLimaPt.parameters
hashcons
tezos-015-PtLimaPt-test-helpers
prbnmcn-stats)
(library_flags (:standard -linkall))
(flags
(:standard)
-open Tezos_stdlib
-open Tezos_base
-open Tezos_base.TzPervasives.Error_monad.Legacy_monad_globals
-open Tezos_error_monad
-open Tezos_micheline
-open Tezos_micheline_rewriting
-open Tezos_benchmark
-open Tezos_benchmark_type_inference_015_PtLimaPt
-open Tezos_protocol_015_PtLimaPt
-open Tezos_015_PtLimaPt_test_helpers)
(private_modules kernel rules state_space))
| |
Parse_ruby_tree_sitter.mli |
val parse : Common.filename -> Ast_ruby.program Tree_sitter_run.Parsing_result.t
| |
sigs.mli |
module type FUNCTOR = sig
type +'a t
end
type (+'a, 's) io
type 's scheduler = {
bind : 'a 'b. ('a, 's) io -> ('a -> ('b, 's) io) -> ('b, 's) io;
return : 'a. 'a -> ('a, 's) io;
}
module type SCHEDULER = sig
type +'a s
type t
external inj : 'a s -> ('a, t) io = "%identity"
external prj : ('a, t) io -> 'a s = "%identity"
end
module type MUTEX = sig
type +'a fiber
type t
val create : unit -> t
val lock : t -> unit fiber
val unlock : t -> unit
end
module type CONDITION = sig
type +'a fiber
type mutex
type t
val create : unit -> t
val wait : t -> mutex -> unit fiber
val signal : t -> unit
val broadcast : t -> unit
end
module type IO = sig
type +'a t
module Mutex : MUTEX with type 'a fiber = 'a t
module Condition :
CONDITION with type 'a fiber = 'a t and type mutex = Mutex.t
val bind : 'a t -> ('a -> 'b t) -> 'b t
val return : 'a -> 'a t
val detach : (unit -> 'a) -> 'a t
val parallel_map : f:('a -> 'b t) -> 'a list -> 'b list t
val parallel_iter : f:('a -> unit t) -> 'a list -> unit t
end
module Make (T : FUNCTOR) : SCHEDULER with type 'a s = 'a T.t
module type UID = sig
type t
type ctx
val empty : ctx
val get : ctx -> t
val feed : ctx -> ?off:int -> ?len:int -> Bigstringaf.t -> ctx
val equal : t -> t -> bool
val compare : t -> t -> int
val length : int
val of_raw_string : string -> t
val to_raw_string : t -> string
val pp : t Fmt.t
val null : t
end
type kind = [ `A | `B | `C | `D ]
val _max_depth : int
| |
dune |
(test
(name example)
(preprocess
(pps ppx_deriving_yojson))
(libraries easy_logging_yojson
ppx_deriving_yojson)
)
| |
client_proto_programs.mli | open Protocol
open Alpha_context
open Tezos_micheline
module Program :
Client_aliases.Alias
with type t = Michelson_v1_parser.parsed Micheline_parser.parsing_result
val run_view :
#Protocol_client_context.rpc_context ->
chain:Shell_services.chain ->
block:Shell_services.block ->
contract:Contract.t ->
entrypoint:string ->
input:Michelson_v1_parser.parsed ->
unparsing_mode:Script_ir_translator.unparsing_mode ->
?source:Contract.t ->
?payer:Contract.t ->
?gas:Gas.Arith.integral ->
unit ->
Script.expr tzresult Lwt.t
val run :
#Protocol_client_context.rpc_context ->
chain:Shell_services.chain ->
block:Shell_services.block ->
?amount:Tez.t ->
balance:Tez.t ->
program:Michelson_v1_parser.parsed ->
storage:Michelson_v1_parser.parsed ->
input:Michelson_v1_parser.parsed ->
unparsing_mode:Script_ir_translator.unparsing_mode ->
?source:Contract.t ->
?payer:Contract.t ->
?gas:Gas.Arith.integral ->
?entrypoint:string ->
unit ->
(Script.expr * packed_internal_operation list * Lazy_storage.diffs option)
tzresult
Lwt.t
val trace :
#Protocol_client_context.rpc_context ->
chain:Shell_services.chain ->
block:Shell_services.block ->
?amount:Tez.t ->
balance:Tez.t ->
program:Michelson_v1_parser.parsed ->
storage:Michelson_v1_parser.parsed ->
input:Michelson_v1_parser.parsed ->
unparsing_mode:Script_ir_translator.unparsing_mode ->
?source:Contract.t ->
?payer:Contract.t ->
?gas:Gas.Arith.integral ->
?entrypoint:string ->
unit ->
(Script.expr
* packed_internal_operation list
* Script_interpreter.execution_trace
* Lazy_storage.diffs option)
tzresult
Lwt.t
val print_view_result :
#Client_context.printer -> Script_repr.expr tzresult -> unit tzresult Lwt.t
val print_run_result :
#Client_context.printer ->
show_source:bool ->
parsed:Michelson_v1_parser.parsed ->
(Script_repr.expr
* packed_internal_operation list
* Lazy_storage.diffs option)
tzresult ->
unit tzresult Lwt.t
val print_trace_result :
#Client_context.printer ->
show_source:bool ->
parsed:Michelson_v1_parser.parsed ->
(Script_repr.expr
* packed_internal_operation list
* Script_interpreter.execution_trace
* Lazy_storage.diffs option)
tzresult ->
unit tzresult Lwt.t
val typecheck_data :
#Protocol_client_context.rpc_context ->
chain:Shell_services.chain ->
block:Shell_services.block ->
?gas:Gas.Arith.integral ->
?legacy:bool ->
data:Michelson_v1_parser.parsed ->
ty:Michelson_v1_parser.parsed ->
unit ->
Gas.t tzresult Lwt.t
val typecheck_program :
#Protocol_client_context.rpc_context ->
chain:Shell_services.chain ->
block:Shell_services.block ->
?gas:Gas.Arith.integral ->
?legacy:bool ->
Michelson_v1_parser.parsed ->
(Script_tc_errors.type_map * Gas.t) tzresult Lwt.t
val print_typecheck_result :
emacs:bool ->
show_types:bool ->
print_source_on_error:bool ->
Michelson_v1_parser.parsed ->
(Script_tc_errors.type_map * Gas.t) tzresult ->
#Client_context.printer ->
unit tzresult Lwt.t
val entrypoint_type :
#Protocol_client_context.rpc_context ->
chain:Shell_services.chain ->
block:Shell_services.block ->
Michelson_v1_parser.parsed ->
entrypoint:string ->
Script.expr option tzresult Lwt.t
val print_entrypoint_type :
#Client_context.printer ->
emacs:bool ->
?script_name:string ->
show_source:bool ->
parsed:Michelson_v1_parser.parsed ->
entrypoint:string ->
Script_repr.expr option tzresult ->
unit tzresult Lwt.t
val list_entrypoints :
#Protocol_client_context.rpc_context ->
chain:Shell_services.chain ->
block:Shell_services.block ->
Michelson_v1_parser.parsed ->
(string * Script.expr) list tzresult Lwt.t
val print_entrypoints_list :
#Client_context.printer ->
emacs:bool ->
?script_name:string ->
show_source:bool ->
parsed:Michelson_v1_parser.parsed ->
(string * Script.expr) list tzresult ->
unit tzresult Lwt.t
val list_unreachables :
#Protocol_client_context.rpc_context ->
chain:Shell_services.chain ->
block:Shell_services.block ->
Michelson_v1_parser.parsed ->
Michelson_v1_primitives.prim list list tzresult Lwt.t
val print_unreachables :
#Client_context.printer ->
emacs:bool ->
?script_name:string ->
show_source:bool ->
parsed:Michelson_v1_parser.parsed ->
Michelson_v1_primitives.prim list list tzresult ->
unit tzresult Lwt.t
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* Copyright (c) 2019 Nomadic Labs <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
dynlink_types.ml |
#2 "otherlibs/dynlink/dynlink_types.ml"
(**************************************************************************)
(* *)
(* OCaml *)
(* *)
(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
(* Mark Shinwell and Leo White, Jane Street Europe *)
(* *)
(* Copyright 1996 Institut National de Recherche en Informatique et *)
(* en Automatique. *)
(* Copyright 2017--2018 Jane Street Group LLC *)
(* *)
(* 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. *)
(* *)
(**************************************************************************)
(** Types shared amongst the various parts of the dynlink code. *)
[@@@ocaml.warning "+a-4-30-40-41-42"]
type implem_state =
| Loaded
| Not_initialized
| Check_inited of int
type filename = string
type linking_error =
| Undefined_global of string
| Unavailable_primitive of string
| Uninitialized_global of string
type error =
| Not_a_bytecode_file of string
| Inconsistent_import of string
| Unavailable_unit of string
| Unsafe_file
| Linking_error of string * linking_error
| Corrupted_interface of string
| Cannot_open_dynamic_library of exn
| Library's_module_initializers_failed of exn
| Inconsistent_implementation of string
| Module_already_loaded of string
| Private_library_cannot_implement_interface of string
exception Error of error
let error_message = function
| Not_a_bytecode_file name ->
name ^ " is not an object file"
| Inconsistent_import name ->
"interface mismatch on " ^ name
| Unavailable_unit name ->
"no implementation available for " ^ name
| Unsafe_file ->
"this object file uses unsafe features"
| Linking_error (name, Undefined_global s) ->
"error while linking " ^ name ^ ".\n" ^
"Reference to undefined global `" ^ s ^ "'"
| Linking_error (name, Unavailable_primitive s) ->
"error while linking " ^ name ^ ".\n" ^
"The external function `" ^ s ^ "' is not available"
| Linking_error (name, Uninitialized_global s) ->
"error while linking " ^ name ^ ".\n" ^
"The module `" ^ s ^ "' is not yet initialized"
| Corrupted_interface name ->
"corrupted interface file " ^ name
| Cannot_open_dynamic_library exn ->
"error loading shared library: " ^ (Printexc.to_string exn)
| Inconsistent_implementation name ->
"implementation mismatch on " ^ name
| Library's_module_initializers_failed exn ->
"execution of module initializers in the shared library failed: "
^ (Printexc.to_string exn)
| Module_already_loaded name ->
"The module `" ^ name ^ "' is already loaded \
(either by the main program or a previously-dynlinked library)"
| Private_library_cannot_implement_interface name ->
"The interface `" ^ name ^ "' cannot be implemented by a \
library loaded privately"
let () =
Printexc.register_printer (function
| Error err ->
let msg = match err with
| Not_a_bytecode_file s -> Printf.sprintf "Not_a_bytecode_file %S" s
| Inconsistent_import s -> Printf.sprintf "Inconsistent_import %S" s
| Unavailable_unit s -> Printf.sprintf "Unavailable_unit %S" s
| Unsafe_file -> "Unsafe_file"
| Linking_error (s, Undefined_global s') ->
Printf.sprintf "Linking_error (%S, Dynlink.Undefined_global %S)"
s s'
| Linking_error (s, Unavailable_primitive s') ->
Printf.sprintf "Linking_error (%S, Dynlink.Unavailable_primitive %S)"
s s'
| Linking_error (s, Uninitialized_global s') ->
Printf.sprintf "Linking_error (%S, Dynlink.Uninitialized_global %S)"
s s'
| Corrupted_interface s ->
Printf.sprintf "Corrupted_interface %S" s
| Cannot_open_dynamic_library exn ->
Printf.sprintf "Cannot_open_dll %S" (Printexc.to_string exn)
| Inconsistent_implementation s ->
Printf.sprintf "Inconsistent_implementation %S" s
| Library's_module_initializers_failed exn ->
Printf.sprintf "Library's_module_initializers_failed %S"
(Printexc.to_string exn)
| Module_already_loaded name ->
Printf.sprintf "Module_already_loaded %S" name
| Private_library_cannot_implement_interface name ->
Printf.sprintf "Private_library_cannot_implement_interface %S" name
in
Some (Printf.sprintf "Dynlink.Error (Dynlink.%s)" msg)
| _ -> None)
| |
ssa3.c |
int main(int y) {
int x;
if(y) {
return 0;
x ++;
};
// do something with x
// It almost looks like x is a phi variable here, but it is not
// because one of the predecessors is dead code.
y = x + 1;
return y;
}
| |
foo.ml |
let v = "bar"
| |
client_proto_multisig.mli | open Protocol
open Alpha_context
open Protocol_client_context
(* The script of the recommended version of the multisig contract.
This is the script originated by [originate_multisig]. *)
val multisig_script : Script.expr
(* A description of the possible actions that a multisig contract can run. *)
type multisig_action =
| Transfer of {
amount : Tez.t;
destination : Contract.t;
entrypoint : Entrypoint.t;
parameter_type : Script.expr;
parameter : Script.expr;
}
| Change_delegate of public_key_hash option
| Lambda of Script.expr
| Change_keys of Z.t * public_key list
(* A prepared action is the byte sequence that needs to be signed to run the
action together with some data that can be useful for the user and to call
the multisig contracts once enough signatures are provided. *)
type multisig_prepared_action = {
(* The sequence of bytes to be signed. *)
bytes : Bytes.t;
(* Information reported to the user so that she knows who can sign and how
many signatures are required. *)
threshold : Z.t;
keys : public_key list;
(* Information needed to execute the action ones enough signatures have been
gathered. *)
counter : Z.t;
entrypoint : Entrypoint.t option;
generic : bool;
}
(* The client will refuse to interact with a multisig contract if the hash of
its script is not in this list. *)
val known_multisig_hashes : Script_expr_hash.t list
(* Originate a new multisig contract *)
val originate_multisig :
full ->
chain:Shell_services.chain ->
block:Shell_services.block ->
?confirmations:int ->
?dry_run:bool ->
?branch:int ->
?fee:Tez.t ->
?gas_limit:Gas.Arith.integral ->
?storage_limit:Z.t ->
?verbose_signing:bool ->
delegate:public_key_hash option ->
threshold:Z.t ->
keys:public_key list ->
balance:Tez.t ->
source:public_key_hash ->
src_pk:public_key ->
src_sk:Client_keys.sk_uri ->
fee_parameter:Injection.fee_parameter ->
unit ->
(Kind.origination Kind.manager Injection.result * Contract.t) tzresult Lwt.t
(* Prepare an action, see [multisig_prepared_action]. *)
val prepare_multisig_transaction :
full ->
chain:Shell_services.chain ->
block:Shell_services.block ->
multisig_contract:Contract_hash.t ->
action:multisig_action ->
unit ->
multisig_prepared_action tzresult Lwt.t
(* Call a multisig contract, requesting it to run an action. *)
val call_multisig :
full ->
chain:Shell_services.chain ->
block:Shell_services.block ->
?confirmations:int ->
?dry_run:bool ->
?verbose_signing:bool ->
?branch:int ->
source:public_key_hash ->
src_pk:public_key ->
src_sk:Client_keys.sk_uri ->
multisig_contract:Contract_hash.t ->
action:multisig_action ->
signatures:Tezos_crypto.Signature.t list ->
amount:Tez.t ->
?fee:Tez.t ->
?gas_limit:Gas.Arith.integral ->
?storage_limit:Z.t ->
?counter:Manager_counter.t ->
fee_parameter:Injection.fee_parameter ->
unit ->
(Kind.transaction Kind.manager Injection.result * Contract_hash.t list)
tzresult
Lwt.t
(* Same as [call_multisig] but the action to be performed is reconstructed from
the byte sequence that was signed. *)
val call_multisig_on_bytes :
full ->
chain:Shell_services.chain ->
block:Shell_services.block ->
?confirmations:int ->
?dry_run:bool ->
?verbose_signing:bool ->
?branch:int ->
source:public_key_hash ->
src_pk:public_key ->
src_sk:Client_keys.sk_uri ->
multisig_contract:Contract_hash.t ->
bytes:Bytes.t ->
signatures:Tezos_crypto.Signature.t list ->
amount:Tez.t ->
?fee:Tez.t ->
?gas_limit:Gas.Arith.integral ->
?storage_limit:Z.t ->
?counter:Manager_counter.t ->
fee_parameter:Injection.fee_parameter ->
unit ->
(Kind.transaction Kind.manager Injection.result * Contract_hash.t list)
tzresult
Lwt.t
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2019 Nomadic Labs <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
bytes.mli |
external length : bytes -> int = "%bytes_length"
external get : bytes -> int -> char = "%bytes_safe_get"
external set : bytes -> int -> char -> unit = "%bytes_safe_set"
external create : int -> bytes = "caml_create_bytes"
val make : int -> char -> bytes
val init : int -> (int -> char) -> bytes
val empty : bytes
val copy : bytes -> bytes
val of_string : string -> bytes
val to_string : bytes -> string
val sub : bytes -> int -> int -> bytes
val sub_string : bytes -> int -> int -> string
val extend : bytes -> int -> int -> bytes
val fill : bytes -> int -> int -> char -> unit
val blit : bytes -> int -> bytes -> int -> int -> unit
val blit_string : string -> int -> bytes -> int -> int -> unit
val concat : bytes -> bytes list -> bytes
val cat : bytes -> bytes -> bytes
val iter : (char -> unit) -> bytes -> unit
val iteri : (int -> char -> unit) -> bytes -> unit
val map : (char -> char) -> bytes -> bytes
val mapi : (int -> char -> char) -> bytes -> bytes
val fold_left : ('a -> char -> 'a) -> 'a -> bytes -> 'a
val fold_right : (char -> 'a -> 'a) -> bytes -> 'a -> 'a
val for_all : (char -> bool) -> bytes -> bool
val exists : (char -> bool) -> bytes -> bool
val trim : bytes -> bytes
val escaped : bytes -> bytes
val index : bytes -> char -> int
val index_opt : bytes -> char -> int option
val rindex : bytes -> char -> int
val rindex_opt : bytes -> char -> int option
val index_from : bytes -> int -> char -> int
val index_from_opt : bytes -> int -> char -> int option
val rindex_from : bytes -> int -> char -> int
val rindex_from_opt : bytes -> int -> char -> int option
val contains : bytes -> char -> bool
val contains_from : bytes -> int -> char -> bool
val rcontains_from : bytes -> int -> char -> bool
val uppercase : bytes -> bytes
val lowercase : bytes -> bytes
val capitalize : bytes -> bytes
val uncapitalize : bytes -> bytes
val uppercase_ascii : bytes -> bytes
val lowercase_ascii : bytes -> bytes
val capitalize_ascii : bytes -> bytes
val uncapitalize_ascii : bytes -> bytes
type t = bytes
val compare : t -> t -> int
val equal : t -> t -> bool
val starts_with : prefix:bytes -> bytes -> bool
val ends_with : suffix:bytes -> bytes -> bool
val unsafe_to_string : bytes -> string
val unsafe_of_string : string -> bytes
val split_on_char : char -> bytes -> bytes list
val to_seq : t -> char Seq.t
val to_seqi : t -> (int * char) Seq.t
val of_seq : char Seq.t -> t
val get_uint8 : bytes -> int -> int
val get_int8 : bytes -> int -> int
val get_uint16_ne : bytes -> int -> int
val get_uint16_be : bytes -> int -> int
val get_uint16_le : bytes -> int -> int
val get_int16_ne : bytes -> int -> int
val get_int16_be : bytes -> int -> int
val get_int16_le : bytes -> int -> int
val get_int32_ne : bytes -> int -> int32
val get_int32_be : bytes -> int -> int32
val get_int32_le : bytes -> int -> int32
val get_int64_ne : bytes -> int -> int64
val get_int64_be : bytes -> int -> int64
val get_int64_le : bytes -> int -> int64
val set_uint8 : bytes -> int -> int -> unit
val set_int8 : bytes -> int -> int -> unit
val set_uint16_ne : bytes -> int -> int -> unit
val set_uint16_be : bytes -> int -> int -> unit
val set_uint16_le : bytes -> int -> int -> unit
val set_int16_ne : bytes -> int -> int -> unit
val set_int16_be : bytes -> int -> int -> unit
val set_int16_le : bytes -> int -> int -> unit
val set_int32_ne : bytes -> int -> int32 -> unit
val set_int32_be : bytes -> int -> int32 -> unit
val set_int32_le : bytes -> int -> int32 -> unit
val set_int64_ne : bytes -> int -> int64 -> unit
val set_int64_be : bytes -> int -> int64 -> unit
val set_int64_le : bytes -> int -> int64 -> unit
external unsafe_get : bytes -> int -> char = "%bytes_unsafe_get"
external unsafe_set : bytes -> int -> char -> unit = "%bytes_unsafe_set"
external unsafe_blit :
bytes -> int -> bytes -> int -> int -> unit = "caml_blit_bytes"[@@noalloc ]
external unsafe_blit_string :
string -> int -> bytes -> int -> int -> unit = "caml_blit_string"[@@noalloc
]
external unsafe_fill :
bytes -> int -> int -> char -> unit = "caml_fill_bytes"[@@noalloc ]
| |
config_v1_error.ml | (* this is a wrong config file containing type errors in it *)
let job = 42
| (* this is a wrong config file containing type errors in it *)
let job = 42 |
resolve.mli | (** Library name resolution monad *)
(** The goal of the [Resolve] monad is to delay library related errors until we
actually need the result.
Indeed, in many places in the Dune codebase we eagerly resolve library names
at "rule generation time". This means that if a library was missing, we
could fail right from the start if we are not caferul. What is more, we
would fail even if we didn't need to build the item that depended on this
library. This would not be good.
This is where the [Resolve] monad can help. A [_ Resolve.t] value represent
a computation that resolved some library names and might have failed. The
failure is captured in the [Resolve.t] value. Failures will be propagated
when we "read" a [Resolve.t].
{2 Reading resolve values}
You should use [read] or [args] on [Resolve.t] values inside code that
compute the action of a rule. By doing so, any error will be propagated only
at the point where the rule is actually being executed. For instance:
{[
add_rule
(let open Action_builder.O in
let* libs = Resolve.read requires in
gen_action libs)
]}
or:
{[
Command.run prog
[ Resolve.args
(let open Resolve.O in
let+ libs = Resolve.args requires in
Command.Args.S [ gen_args libs ])
]
]}
{2 Reading resolve values early}
It is sometimes necessary to read a [Resolve.t] value at rule generation
time. For instance, it is necessary to do that for setting the rule for
inline tests. This is because some information needed to setup the rules are
attached to the backend library for the inline test framework.
One way to do that would be to call [read_memo] while setting up the rules:
{[
let open Memo.O in
let* libs = Resolve.get libs in
gen_rules libs
]}
However, as discussed earlier this would cause Dune to fail too early and
too often. There are two ways to deal with this:
1. refactor the code so that only [Resolve.read] and/or [Resolve.args] are
used from inside the code that compute rules actions
2. use [Resolve.peek] and produce the rules using some dummy value in the
error case
1 is generally the cleaner solution but requires more work. 2 is a quick fix
to still generates some rules and fail when rules are actually being
executed. For instance:
{[
let libs =
match Resolve.peek libs with
| Ok x -> x
| Error () -> []
(* or a dummy value *)
in
gen_rules libs
]}
If you use this pattern, you need to make sure that the rules will indeed
fail with the error captured in the [libs] value.
[Action_builder.prefix_rules] provides a hassle free way to do this,
allowing one to "inject" a failure in each rule generated by a piece of
code. In the end the code should looking this this:
{[
match Resolve.peek libs with
| Ok libs -> gen_rules libs
| Error () ->
let fail = Action_builder.ignore (Resolve.read libs) in
Rules.prefix_rules fail ~f:(fun () -> gen_rules libs)
]} *)
open Import
type 'a t
include Monad.S with type 'a t := 'a t
val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
val hash : ('a -> int) -> 'a t -> int
val to_dyn : ('a -> Dyn.t) -> 'a t Dyn.builder
val of_result : ('a, exn) result -> 'a t
type error
val to_result : 'a t -> ('a, error) result
val of_error : error -> 'a t
(** Read a [Resolve.t] value inside the action builder monad. *)
val read : 'a t -> 'a Action_builder.t
(** [args] allows to easily inject a resolve monad computing some command line
arguments into an command line specification. *)
val args : 'a Command.Args.t t -> 'a Command.Args.t
(** Same as [read] but in the memo build monad. Use with caution! *)
val read_memo : 'a t -> 'a Memo.t
(** Read the value immediatly, ignoring actual errors. *)
val peek : 'a t -> ('a, unit) result
(** [is_ok t] is the same as [Result.is_ok (peek t)] *)
val is_ok : 'a t -> bool
(** [is_ok t] is the same as [Result.is_error (peek t)] *)
val is_error : 'a t -> bool
(** When in the resolve monad, you should prefer using this function rather than
raising directly. This allows errors to be delayed until the monad is
actually evaluated. *)
val fail : User_message.t -> _ t
(** Similar to [Memo.push_stack_frame]. *)
val push_stack_frame :
human_readable_description:(unit -> User_message.Style.t Pp.t) -> 'a t -> 'a t
val all : 'a t list -> 'a list t
module List : sig
val map : 'a list -> f:('a -> 'b t) -> 'b list t
val filter_map : 'a list -> f:('a -> 'b option t) -> 'b list t
val concat_map : 'a list -> f:('a -> 'b list t) -> 'b list t
val iter : 'a list -> f:('a -> unit t) -> unit t
val fold_left : 'a list -> f:('acc -> 'a -> 'acc t) -> init:'acc -> 'acc t
end
module Option : sig
val iter : 'a option -> f:('a -> unit t) -> unit t
end
module Memo : sig
type 'a resolve
type 'a t = 'a resolve Memo.t
val all : 'a t list -> 'a list t
include Monad.S with type 'a t := 'a t
val push_stack_frame :
human_readable_description:(unit -> User_message.Style.t Pp.t)
-> (unit -> 'a t)
-> 'a t
val lift_memo : 'a Memo.t -> 'a t
val lift : 'a resolve -> 'a t
val is_ok : 'a t -> bool Memo.t
(** [is_ok t] is the same as [Result.is_error (peek t)] *)
val is_error : 'a t -> bool Memo.t
module List : Monad.List with type 'a t := 'a t
module Option : sig
val iter : 'a option -> f:('a -> unit t) -> unit t
end
(** Same as [read] but in the memo build monad. Use with caution! *)
val read_memo : 'a t -> 'a Memo.t
(** Read a [Resolve.t] value inside the action builder monad. *)
val read : 'a t -> 'a Action_builder.t
(** [args] allows to easily inject a resolve monad computing some command line
arguments into an command line specification. *)
val args : Command.Args.without_targets Command.Args.t t -> 'a Command.Args.t
val fail : User_message.t -> _ t
val of_result : ('a, exn) result -> 'a t
(** Read the value immediatly, ignoring actual errors. *)
val peek : 'a t -> ('a, unit) result Memo.t
end
with type 'a resolve := 'a t
| (** Library name resolution monad *)
|
t-epsilon_arg.c |
#include "acb_modular.h"
#include "flint/arith.h"
static void
acb_modular_epsilon_arg_naive(fmpq_t arg, const psl2z_t g)
{
#define a (&g->a)
#define b (&g->b)
#define c (&g->c)
#define d (&g->d)
if (fmpz_is_zero(c))
{
fmpz_set(fmpq_numref(arg), b);
fmpz_set_ui(fmpq_denref(arg), 12);
fmpq_canonicalise(arg);
}
else
{
fmpq_t t;
fmpq_init(t);
fmpz_add(fmpq_numref(arg), a, d);
fmpz_submul_ui(fmpq_numref(arg), c, 3);
fmpz_mul_ui(fmpq_denref(arg), c, 12);
fmpq_canonicalise(arg);
arith_dedekind_sum(t, d, c);
fmpq_sub(arg, arg, t);
fmpq_clear(t);
}
#undef a
#undef b
#undef c
#undef d
}
int main()
{
slong iter;
flint_rand_t state;
flint_printf("eta_epsilon_arg....");
fflush(stdout);
flint_randinit(state);
for (iter = 0; iter < 10000 * arb_test_multiplier(); iter++)
{
psl2z_t g;
fmpq_t x, y;
acb_t a, b;
psl2z_init(g);
fmpq_init(x);
fmpq_init(y);
acb_init(a);
acb_init(b);
psl2z_randtest(g, state, n_randint(state, 200));
fmpq_randtest(x, state, 100);
fmpq_randtest(y, state, 100);
fmpq_set_si(x, acb_modular_epsilon_arg(g), 12);
acb_modular_epsilon_arg_naive(y, g);
arb_sin_cos_pi_fmpq(acb_imagref(a), acb_realref(a), x, 200);
arb_sin_cos_pi_fmpq(acb_imagref(b), acb_realref(b), x, 200);
if (!acb_overlaps(a, b))
{
flint_printf("FAIL\n");
flint_printf("g = "); psl2z_print(g); flint_printf("\n");
flint_printf("x = "); fmpq_print(x); flint_printf("\n");
flint_printf("y = "); fmpq_print(y); flint_printf("\n");
flint_abort();
}
psl2z_clear(g);
fmpq_clear(x);
fmpq_clear(y);
acb_clear(a);
acb_clear(b);
}
flint_randclear(state);
flint_cleanup();
flint_printf("PASS\n");
return EXIT_SUCCESS;
}
| /*
Copyright (C) 2014 Fredrik Johansson
This file is part of Arb.
Arb is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <http://www.gnu.org/licenses/>.
*/ |
Semgrep_envvars.ml | (*****************************************************************************)
(* Prelude *)
(*****************************************************************************)
(*
Typed access to Semgrep environment variables (e.g., SEMGREP_IN_DOCKER).
Translated from env.py.
There are other Semgrep environment variables which are not mentioned
in this file because their value is accessed by Cmdliner
in Scan_CLI.ml (SEMGREP_BASELINE_COMMIT, SEMGREP_SEND_METRICS,
SEMGREP_TIMEOUT, and SEMGREP_RULES).
*)
(*****************************************************************************)
(* Constants *)
(*****************************************************************************)
let settings_filename = "settings.yml"
(*****************************************************************************)
(* Helpers *)
(*****************************************************************************)
(* LATER: use Fpath.of_string or something at some point *)
let path_of_string s = s
let ( / ) a b = Filename.concat a b
(* this causes parse failure in codemap/efuns so commented for now *)
(*
let%test_unit "Semgrep_envvars.(/)" =
[%test_eq: Base.string] ("a/b/" / "c/d" / "foo.c") "a/b/c/d/foo.c"
*)
let env_opt var = Sys.getenv_opt var
let env_or conv var default =
match Sys.getenv_opt var with
| None -> conv default
| Some x -> conv x
let in_env var = env_opt var <> None
(*****************************************************************************)
(* Types and constants *)
(*****************************************************************************)
(* TODO: could we use deriving to automate the generation of
* env below? [@default = ...] or use ATD?
*)
type t = {
semgrep_url : Uri.t;
fail_open_url : Uri.t;
app_token : string option;
version_check_url : Uri.t;
version_check_timeout : int;
(* LATER: use FPath.t *)
version_check_cache_path : Common.filename;
git_command_timeout : int;
src_directory : Common.filename;
user_data_folder : Common.filename;
user_log_file : Common.filename;
user_settings_file : Common.filename;
in_docker : bool;
in_gh_action : bool;
(* deprecated *)
in_agent : bool;
min_fetch_depth : int;
shouldafound_base_url : Uri.t;
shouldafound_no_email : bool;
}
(* less: make it Lazy? *)
let env : t =
let user_data_folder =
let parent_dir =
match Sys.getenv_opt "XDG_CONFIG_HOME" with
| Some x when Sys.is_directory x -> x
| _else_ -> Sys.getenv "HOME"
in
parent_dir / ".semgrep"
in
{
(* TOPORT: also SEMGREP_APP_URL *)
semgrep_url = env_or Uri.of_string "SEMGREP_URL" "https://semgrep.dev";
fail_open_url =
env_or Uri.of_string "SEMGREP_FAIL_OPEN_URL"
"https://fail-open.prod.semgrep.dev/failure";
shouldafound_base_url =
env_or Uri.of_string "SEMGREP_SHOULDAFOUND_BASE_URL"
"https://shouldafound.semgrep.dev";
app_token = env_opt "SEMGREP_APP_TOKEN";
version_check_url =
env_or Uri.of_string "SEMGREP_VERSION_CHECK_URL"
"https://semgrep.dev/api/check-version";
version_check_timeout =
env_or int_of_string "SEMGREP_VERSION_CHECK_TIMEOUT" "2";
version_check_cache_path =
env_or path_of_string "SEMGREP_VERSION_CACHE_PATH"
(Sys.getcwd () / ".cache" / "semgrep_version");
git_command_timeout =
env_or int_of_string "SEMGREP_GIT_COMMAND_TIMEOUT" "300";
src_directory = env_or path_of_string "SEMGREP_SRC_DIRECTORY" "/src";
user_data_folder;
user_log_file =
env_or path_of_string "SEMGREP_LOG_FILE" (user_data_folder / "semgrep.log");
user_settings_file =
env_or path_of_string "SEMGREP_SETTINGS_FILE"
(user_data_folder / settings_filename);
in_docker = in_env "SEMGREP_IN_DOCKER";
in_gh_action = in_env "GITHUB_WORKSPACE";
in_agent = in_env "SEMGREP_AGENT";
shouldafound_no_email = in_env "SEMGREP_SHOULDAFOUND_NO_EMAIL";
min_fetch_depth = env_or int_of_string "SEMGREP_GHA_MIN_FETCH_DEPTH" "0";
}
| (*****************************************************************************)
(* Prelude *)
(*****************************************************************************)
(* |
fifo_sync.ml |
open! Base
open Hardcaml
let create
?(overflow_check = true)
?(showahead = false)
?(underflow_check = true)
?(build_mode = Build_mode.Synthesis)
?scope
?fifo_memory_type
()
~capacity
~clock
~clear
~wr
~d
~rd
=
match (build_mode : Build_mode.t) with
| Synthesis ->
Xpm_fifo_sync.create
~overflow_check
~underflow_check
~showahead
?fifo_memory_type
()
~capacity
~clk:clock
~clr:clear
~rd
~wr
~d
| Simulation ->
Fifo.create
?scope
~overflow_check
~underflow_check
~showahead
()
~capacity
~clock
~clear
~rd
~wr
~d
;;
| |
is_irreducible.c |
#include "nmod_poly.h"
int
nmod_poly_is_irreducible(const nmod_poly_t f)
{
if (nmod_poly_length(f) > 2)
return nmod_poly_is_irreducible_ddf(f);
return 1;
}
| /*
Copyright (C) 2007 David Howden
Copyright (C) 2007, 2008, 2009, 2010 William Hart
Copyright (C) 2008 Richard Howell-Peak
Copyright (C) 2011 Fredrik Johansson
Copyright (C) 2012 Lina Kulakova
Copyright (C) 2013 Martin Lee
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/>.
*/ |
constants_repr.ml | let version_number_004 = "\000"
let version_number = "\001"
let proof_of_work_nonce_size = 8
let nonce_length = 32
let max_anon_ops_per_block = 132
let max_proposals_per_delegate = 20
let max_operation_data_length = 16 * 1024 (* 16kB *)
type fixed = {
proof_of_work_nonce_size : int;
nonce_length : int;
max_anon_ops_per_block : int;
max_operation_data_length : int;
max_proposals_per_delegate : int;
}
let fixed_encoding =
let open Data_encoding in
conv
(fun c ->
( c.proof_of_work_nonce_size,
c.nonce_length,
c.max_anon_ops_per_block,
c.max_operation_data_length,
c.max_proposals_per_delegate ))
(fun ( proof_of_work_nonce_size,
nonce_length,
max_anon_ops_per_block,
max_operation_data_length,
max_proposals_per_delegate ) ->
{
proof_of_work_nonce_size;
nonce_length;
max_anon_ops_per_block;
max_operation_data_length;
max_proposals_per_delegate;
})
(obj5
(req "proof_of_work_nonce_size" uint8)
(req "nonce_length" uint8)
(req "max_anon_ops_per_block" uint8)
(req "max_operation_data_length" int31)
(req "max_proposals_per_delegate" uint8))
let fixed =
{
proof_of_work_nonce_size;
nonce_length;
max_anon_ops_per_block;
max_operation_data_length;
max_proposals_per_delegate;
}
type parametric = {
preserved_cycles : int;
blocks_per_cycle : int32;
blocks_per_commitment : int32;
blocks_per_roll_snapshot : int32;
blocks_per_voting_period : int32;
time_between_blocks : Period_repr.t list;
endorsers_per_block : int;
hard_gas_limit_per_operation : Gas_limit_repr.Arith.integral;
hard_gas_limit_per_block : Gas_limit_repr.Arith.integral;
proof_of_work_threshold : int64;
tokens_per_roll : Tez_repr.t;
michelson_maximum_type_size : int;
seed_nonce_revelation_tip : Tez_repr.t;
origination_size : int;
block_security_deposit : Tez_repr.t;
endorsement_security_deposit : Tez_repr.t;
baking_reward_per_endorsement : Tez_repr.t list;
endorsement_reward : Tez_repr.t list;
cost_per_byte : Tez_repr.t;
hard_storage_limit_per_operation : Z.t;
test_chain_duration : int64;
(* in seconds *)
quorum_min : int32;
quorum_max : int32;
min_proposal_quorum : int32;
initial_endorsers : int;
delay_per_missing_endorsement : Period_repr.t;
}
let parametric_encoding =
let open Data_encoding in
conv
(fun c ->
( ( c.preserved_cycles,
c.blocks_per_cycle,
c.blocks_per_commitment,
c.blocks_per_roll_snapshot,
c.blocks_per_voting_period,
c.time_between_blocks,
c.endorsers_per_block,
c.hard_gas_limit_per_operation,
c.hard_gas_limit_per_block ),
( ( c.proof_of_work_threshold,
c.tokens_per_roll,
c.michelson_maximum_type_size,
c.seed_nonce_revelation_tip,
c.origination_size,
c.block_security_deposit,
c.endorsement_security_deposit,
c.baking_reward_per_endorsement ),
( c.endorsement_reward,
c.cost_per_byte,
c.hard_storage_limit_per_operation,
c.test_chain_duration,
c.quorum_min,
c.quorum_max,
c.min_proposal_quorum,
c.initial_endorsers,
c.delay_per_missing_endorsement ) ) ))
(fun ( ( preserved_cycles,
blocks_per_cycle,
blocks_per_commitment,
blocks_per_roll_snapshot,
blocks_per_voting_period,
time_between_blocks,
endorsers_per_block,
hard_gas_limit_per_operation,
hard_gas_limit_per_block ),
( ( proof_of_work_threshold,
tokens_per_roll,
michelson_maximum_type_size,
seed_nonce_revelation_tip,
origination_size,
block_security_deposit,
endorsement_security_deposit,
baking_reward_per_endorsement ),
( endorsement_reward,
cost_per_byte,
hard_storage_limit_per_operation,
test_chain_duration,
quorum_min,
quorum_max,
min_proposal_quorum,
initial_endorsers,
delay_per_missing_endorsement ) ) ) ->
{
preserved_cycles;
blocks_per_cycle;
blocks_per_commitment;
blocks_per_roll_snapshot;
blocks_per_voting_period;
time_between_blocks;
endorsers_per_block;
hard_gas_limit_per_operation;
hard_gas_limit_per_block;
proof_of_work_threshold;
tokens_per_roll;
michelson_maximum_type_size;
seed_nonce_revelation_tip;
origination_size;
block_security_deposit;
endorsement_security_deposit;
baking_reward_per_endorsement;
endorsement_reward;
cost_per_byte;
hard_storage_limit_per_operation;
test_chain_duration;
quorum_min;
quorum_max;
min_proposal_quorum;
initial_endorsers;
delay_per_missing_endorsement;
})
(merge_objs
(obj9
(req "preserved_cycles" uint8)
(req "blocks_per_cycle" int32)
(req "blocks_per_commitment" int32)
(req "blocks_per_roll_snapshot" int32)
(req "blocks_per_voting_period" int32)
(req "time_between_blocks" (list Period_repr.encoding))
(req "endorsers_per_block" uint16)
(req
"hard_gas_limit_per_operation"
Gas_limit_repr.Arith.z_integral_encoding)
(req
"hard_gas_limit_per_block"
Gas_limit_repr.Arith.z_integral_encoding))
(merge_objs
(obj8
(req "proof_of_work_threshold" int64)
(req "tokens_per_roll" Tez_repr.encoding)
(req "michelson_maximum_type_size" uint16)
(req "seed_nonce_revelation_tip" Tez_repr.encoding)
(req "origination_size" int31)
(req "block_security_deposit" Tez_repr.encoding)
(req "endorsement_security_deposit" Tez_repr.encoding)
(req "baking_reward_per_endorsement" (list Tez_repr.encoding)))
(obj9
(req "endorsement_reward" (list Tez_repr.encoding))
(req "cost_per_byte" Tez_repr.encoding)
(req "hard_storage_limit_per_operation" z)
(req "test_chain_duration" int64)
(req "quorum_min" int32)
(req "quorum_max" int32)
(req "min_proposal_quorum" int32)
(req "initial_endorsers" uint16)
(req "delay_per_missing_endorsement" Period_repr.encoding))))
type t = {fixed : fixed; parametric : parametric}
let encoding =
let open Data_encoding in
conv
(fun {fixed; parametric} -> (fixed, parametric))
(fun (fixed, parametric) -> {fixed; parametric})
(merge_objs fixed_encoding parametric_encoding)
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
filter_panel.ml |
open! Core
open! Bonsai_web
module Attr = Vdom.Attr
module Node = Vdom.Node
module Node_svg = Virtual_dom_svg.Node
open Memtrace_viewer_common
let graph_view
~graph
~filtered_graph
~allocated_range
~collected_range
~start_time
~time_view
~set_time_view
: Vdom.Node.t Bonsai.Computation.t
=
let open Bonsai.Let_syntax in
let width = 500 in
let height = 200 in
let series =
let%map graph = graph
and filtered_graph = filtered_graph in
let max_x =
match filtered_graph with
| None -> Data.Graph.max_x graph
| Some filtered_graph ->
Time_ns.Span.max (Data.Graph.max_x graph) (Data.Graph.max_x filtered_graph)
in
let series_of_data_graph css_class (graph : Data.Graph.t) =
let max_y = Data.Graph.max_y graph in
let points_rev = List.rev (Data.Graph.points graph) in
(* Make sure the graph has points at x=0 and x=max_x so that it ranges through the
whole timeline. We can assume that the total allocations start at 0 and don't
change after the last reported point. *)
let last_x, last_y =
match points_rev with
| last_point :: _ -> last_point
| [] -> Time_ns.Span.zero, Byte_units.zero
in
let points_rev =
if Time_ns.Span.(last_x < max_x)
then (max_x, last_y) :: points_rev
else points_rev
in
let points = List.rev points_rev in
let points =
match points with
| (x, _) :: _ when Time_ns.Span.(x = zero) -> points
| _ -> (Time_ns.Span.zero, Byte_units.zero) :: points
in
Graph_view.Series.create ~css_class ~max_x ~max_y points
in
let full_series = series_of_data_graph "full-graph-line" graph in
let filtered_series =
Option.map ~f:(series_of_data_graph "filtered-graph-line") filtered_graph
in
List.filter_opt [ filtered_series; Some full_series ]
in
let regions =
let%map allocated_range = allocated_range
and collected_range = collected_range in
let region_of_range css_class range : Graph_view.Region.t =
Graph_view.Region.create ~css_class range
in
let allocated_region =
region_of_range "graph-allocated-range" (Non_empty allocated_range)
in
let collected_region = region_of_range "graph-collected-range" collected_range in
[ allocated_region; collected_region ]
in
let width = Bonsai.Value.return width in
let height = Bonsai.Value.return height in
Graph_view.component
~series
~regions
~width
~height
~start_time
~time_view
~set_time_view
;;
module Submission_handling = struct
type t =
{ button : Vdom.Node.t
; on_submit : unit Vdom.Effect.t
}
let component ~server_state ~inject_outgoing ~filter =
let open Bonsai.Let_syntax in
return
(let%map server_state = server_state
and inject_outgoing = inject_outgoing
and filter = filter in
let do_submit =
match filter with
| Some filter ->
inject_outgoing (Action.Set_filter filter)
| None -> Vdom.Effect.Ignore
in
let on_submit =
Vdom.Effect.Many
[ Vdom.Effect.Prevent_default (* don't do a real HTML submit! *); do_submit ]
in
let server_is_up = Server_state.Status.is_up Server_state.(server_state.status) in
let filter_is_valid = Option.is_some filter in
let enabled = server_is_up && filter_is_valid in
let button =
Node.input
(* Don't actually put an onclick handler on the button; just return the handler
to be used as the form's onsubmit instead, thus getting Enter key behavior
for free
*)
~attr:
(Attr.many_without_merge
([ Attr.type_ "submit"
; Attr.value "Apply"
; Attr.title "Set current filter and redraw views"
]
@ if not enabled then [ Attr.disabled ] else []))
[]
in
{ button; on_submit })
;;
end
let panel
~server_state
~filtered_allocations
~(filter : Filter.t)
~filter_clauses
~graph_node
~button_node
~on_submit
=
let allocations_line =
match filtered_allocations with
| None -> Util.placeholder_div
| Some bytes ->
Node.p
~attr:(Attr.class_ "total-allocations")
[ Node.textf "Filtered allocations: %s" (bytes |> Byte_units.Short.to_string) ]
in
let swatch swatch_class =
Node_svg.svg
~attr:(Attr.classes [ "swatch"; swatch_class ])
[ Node_svg.rect ~attr:(Attr.class_ "swatch-bg") []
; Node_svg.rect ~attr:(Attr.class_ "swatch-interior") []
; Node_svg.rect ~attr:(Attr.class_ "swatch-border") []
]
in
let region_legend_text =
let phrase swatch_class desc range =
if Range.Time_ns_span.is_all range
then None
else Some [ Node.text " "; swatch swatch_class; Node.textf "%s in this range" desc ]
in
let allocated_phrase = phrase "allocated-swatch" "allocated" filter.allocated_range in
let collected_phrase =
match filter.collected_range with
| Non_empty range -> phrase "collected-swatch" "collected" range
| Empty -> Some [ Node.textf " never collected" ]
in
let initial_fragment = Node.text "Showing objects that are" in
match allocated_phrase, collected_phrase with
| None, None -> []
| Some phrase, None | None, Some phrase -> initial_fragment :: phrase
| Some phrase1, Some phrase2 ->
List.concat [ [ initial_fragment ]; phrase1; [ Node.text " and" ]; phrase2 ]
in
let region_legend =
if List.is_empty region_legend_text
then Util.placeholder_div
else Node.p region_legend_text
in
let connection_lost_message =
match server_state with
| { Server_state.status = Down } -> Node.text " Server connection lost"
| _ -> Node.none
in
let form =
Node.create
"form"
~attr:
(Attr.many
[ Attr.id "filter-form"
; Attr.on_submit (fun _ -> on_submit)
; (* Browser-level validation isn't our friend - it rejects numeric inputs if the
user inputs too many digits (as decided by the step) *)
Attr.create "novalidate" ""
; (* This effectively disables the table or flame graph's keyboard event handler
whenever the focus is anywhere in the form, so that Enter, arrow keys, etc.
all work correcly *)
Attr.on_keydown (fun _ -> Vdom.Effect.Stop_propagation)
])
[ region_legend
; And_view.view filter_clauses
; Node.div [ button_node; connection_lost_message ]
]
in
let main_body =
Vdom.Node.div
~attr:(Vdom.Attr.id "filter-panel-body")
[ allocations_line
; Vdom.Node.div ~attr:(Vdom.Attr.id "filter-graph-container") [ graph_node ]
; form
]
in
Panel.panel main_body ~title:"Filter" ~id:"filter-panel"
;;
let time_view_holder =
Bonsai.state [%here] (module Graph_view.Time_view) ~default_model:Elapsed_seconds
;;
let component
~graph
~filtered_graph
~filtered_allocations
~start_time
~inject_outgoing
~server_state
: Vdom.Node.t Bonsai.Computation.t
=
let open Bonsai.Let_syntax in
let%sub time_view_holder = time_view_holder in
let time_view = Bonsai.Value.map ~f:fst time_view_holder in
let set_time_view = Bonsai.Value.map ~f:snd time_view_holder in
let max_time =
let%map graph = graph in
Data.Graph.max_x graph
in
let%sub filter_clauses = Filter_editor.component ~max_time ~start_time ~time_view in
let filter_spec : Filter_spec.t Bonsai.Value.t =
let%map filter_clauses = filter_clauses in
Filter_spec.{ clauses = filter_clauses.value }
in
(* If the filter is incomplete (that is, there are blank entries), we don't want to
enable Apply but we do want to show as much of the filter as makes sense. This is
especially important because otherwise adding a new clause would cause the displayed
filter (e.g., the ranges in the graph) to disappear.
(We could instead use a component that remembers the last valid filter, but that's
rather involved. We would want something (more or less) of type
[is_valid:('a -> bool) -> 'a Bonsai.Value.t -> 'a Bonsai.Computation.t]
but that won't work because Bonsai computations are pure---it can't store the
last known valid input as a side effect. It could instead be in the style of a
state machine:
[is_valid:('a -> bool) -> ('a * ('a -> unit Vdom.Effect.t)) Bonsai.Computation.t]
but now, to fire that event, all the components in the filter editor would have to
support an on_changed event, which is a much more painful workaround than just
having this [to_filter_allow_incomplete] function.) *)
let filter_to_display =
Bonsai.Value.map ~f:Filter_spec.to_filter_allow_incomplete filter_spec
in
let complete_filter = Bonsai.Value.map ~f:Filter_spec.to_filter filter_spec in
let allocated_range =
let%map filter_to_display = filter_to_display in
filter_to_display.allocated_range
in
let collected_range =
let%map filter_to_display = filter_to_display in
filter_to_display.collected_range
in
let%sub graph_view =
graph_view
~graph
~filtered_graph
~allocated_range
~collected_range
~start_time
~time_view
~set_time_view
in
let%sub submission_handling =
Submission_handling.component ~server_state ~inject_outgoing ~filter:complete_filter
in
return
(let%map filter = filter_to_display
and filter_clauses = filter_clauses
and graph_node = graph_view
and { button = button_node; on_submit } = submission_handling
and server_state = server_state
and filtered_allocations = filtered_allocations in
panel
~server_state
~filtered_allocations
~filter
~filter_clauses
~graph_node
~button_node
~on_submit)
;;
| |
clb_ptrees.h |
#ifndef CLB_PTREES
#define CLB_PTREES
#include <stdint.h>
#include <clb_pstacks.h>
#include <clb_avlgeneric.h>
/*---------------------------------------------------------------------*/
/* Data type declarations */
/*---------------------------------------------------------------------*/
/* Data structure for indexing pointers (which need to be casted
carefully by the wrapper functions). The key comes last in the
struct to circumvent some bug in various gcc versions (apparently,
gcc likes to safe a variable and will not always allocate a
temporary variable when it thinks it can reuse the original
position. In this case, it is wrong (exhibited in
PTreeExtractKey()). Moving key to the back works around it (the
memory management module will overwrite just the first word...) */
typedef struct ptreecell
{
struct ptreecell *lson;
struct ptreecell *rson;
void* key;
}PTreeCell, *PTree_p;
/*---------------------------------------------------------------------*/
/* Exported Functions and Variables */
/*---------------------------------------------------------------------*/
#define PTreeCellAlloc() (PTreeCell*)SizeMalloc(sizeof(PTreeCell))
#define PTreeCellFree(junk) SizeFree(junk, sizeof(PTreeCell))
#ifdef CONSTANT_MEM_ESTIMATE
#define PTREE_CELL_MEM 16
#else
#define PTREE_CELL_MEM MEMSIZE(PTreeCell)
#endif
#define PCmp(p1, p2) PCmpFun(p1, p2)
#define PEqual(p1,p2) ((uintptr_t)(p1))==((uintptr_t)(p2))
#define PGreater(p1,p2) ((uintptr_t)(p1))> ((uintptr_t)(p2))
#define PLesser(p1,p2) ((uintptr_t)(p1))< ((uintptr_t)(p2))
static inline int PCmpFun(void* p1, void*p2);
PTree_p PTreeCellAllocEmpty(void);
void PTreeFree(PTree_p junk);
PTree_p PTreeInsert(PTree_p *root, PTree_p newnode);
bool PTreeStore(PTree_p *root, void* key);
PTree_p PTreeFind(PTree_p *root, void* key);
PTree_p PTreeFindBinary(PTree_p root, void* key);
PTree_p PTreeExtractEntry(PTree_p *root, void* key);
void* PTreeExtractKey(PTree_p *root, void* key);
void* PTreeExtractRootKey(PTree_p *root);
bool PTreeDeleteEntry(PTree_p *root, void* key);
bool PTreeMerge(PTree_p *root, PTree_p add);
void PTreeInsertTree(PTree_p *root, PTree_p add);
long PTreeNodes(PTree_p root);
long PTreeDebugPrint(FILE* out, PTree_p root);
long PStackToPTree(PTree_p *root, PStack_p stack);
long PTreeToPStack(PStack_p target_stack, PTree_p root);
void* PTreeSharedElement(PTree_p *tree1, PTree_p tree2);
PTree_p PTreeIntersection(PTree_p tree1, PTree_p tree2);
long PTreeDestrIntersection(PTree_p *tree1, PTree_p tree2);
PTree_p PTreeCopy(PTree_p tree1);
bool PTreeEquiv(PTree_p t1, PTree_p t2);
bool PTreeIsSubset(PTree_p sub, PTree_p *super);
void PTreeVisitInOrder(PTree_p t, void (*visitor)(void*, void*), void* arg);
AVL_TRAVERSE_DECLARATION(PTree, PTree_p)
#define PTreeTraverseExit(stack) PStackFree(stack)
/*-----------------------------------------------------------------------
//
// Function: PCmpFun()
//
// Compare two pointers, return 1 if the first one is bigger, 0 if
// both are equal, and -1 if the second one is bigger.
//
// Global Variables: -
//
// Side Effects : -
//
/----------------------------------------------------------------------*/
static inline int PCmpFun(void* p1, void*p2)
{
return ((uintptr_t)p1 > (uintptr_t)p2) - ((uintptr_t)p1 < (uintptr_t)p2);
}
#endif
/*---------------------------------------------------------------------*/
/* End of File */
/*---------------------------------------------------------------------*/
| /*-----------------------------------------------------------------------
File : clb_ptrees.h
Author: Stephan Schulz
Contents
Data structures for the efficient management of pointer
sets. I substituted this SPLAY tree version as it consumes less
memory and may even be faster in the average case. As pointers are
managed, all additional information can go into the pointed-to
structures.
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
Created: Thu Sep 25 02:36:58 MET DST 1997
-----------------------------------------------------------------------*/ |
seed_storage.ml | open Misc
open Misc.Syntax
type error +=
| Unknown of {
oldest : Cycle_repr.t;
cycle : Cycle_repr.t;
latest : Cycle_repr.t;
}
(* `Permanent *)
let () =
register_error_kind
`Permanent
~id:"seed.unknown_seed"
~title:"Unknown seed"
~description:"The requested seed is not available"
~pp:(fun ppf (oldest, cycle, latest) ->
if Cycle_repr.(cycle < oldest) then
Format.fprintf
ppf
"The seed for cycle %a has been cleared from the context (oldest \
known seed is for cycle %a)"
Cycle_repr.pp
cycle
Cycle_repr.pp
oldest
else
Format.fprintf
ppf
"The seed for cycle %a has not been computed yet (latest known \
seed is for cycle %a)"
Cycle_repr.pp
cycle
Cycle_repr.pp
latest)
Data_encoding.(
obj3
(req "oldest" Cycle_repr.encoding)
(req "requested" Cycle_repr.encoding)
(req "latest" Cycle_repr.encoding))
(function
| Unknown {oldest; cycle; latest} ->
Some (oldest, cycle, latest)
| _ ->
None)
(fun (oldest, cycle, latest) -> Unknown {oldest; cycle; latest})
let compute_for_cycle c ~revealed cycle =
match Cycle_repr.pred cycle with
| None ->
assert false (* should not happen *)
| Some previous_cycle ->
let levels = Level_storage.levels_with_commitments_in_cycle c revealed in
let combine (c, random_seed, unrevealed) level =
Storage.Seed.Nonce.get c level
>>=? function
| Revealed nonce ->
Storage.Seed.Nonce.delete c level
>|=? fun c -> (c, Seed_repr.nonce random_seed nonce, unrevealed)
| Unrevealed u ->
Storage.Seed.Nonce.delete c level
>|=? fun c -> (c, random_seed, u :: unrevealed)
in
Storage.Seed.For_cycle.get c previous_cycle
>>=? fun prev_seed ->
let seed = Seed_repr.deterministic_seed prev_seed in
fold_left_s combine (c, seed, []) levels
>>=? fun (c, seed, unrevealed) ->
Storage.Seed.For_cycle.init c cycle seed >|=? fun c -> (c, unrevealed)
let for_cycle ctxt cycle =
let preserved = Constants_storage.preserved_cycles ctxt in
let current_level = Level_storage.current ctxt in
let current_cycle = current_level.cycle in
let latest =
if Cycle_repr.(current_cycle = root) then
Cycle_repr.add current_cycle (preserved + 1)
else Cycle_repr.add current_cycle preserved
in
let oldest =
match Cycle_repr.sub current_cycle preserved with
| None ->
Cycle_repr.root
| Some oldest ->
oldest
in
error_unless
Cycle_repr.(oldest <= cycle && cycle <= latest)
(Unknown {oldest; cycle; latest})
>>?= fun () -> Storage.Seed.For_cycle.get ctxt cycle
let clear_cycle c cycle = Storage.Seed.For_cycle.delete c cycle
let init ctxt =
let preserved = Constants_storage.preserved_cycles ctxt in
List.fold_left2
(fun ctxt c seed ->
ctxt
>>=? fun ctxt ->
let cycle = Cycle_repr.of_int32_exn (Int32.of_int c) in
Storage.Seed.For_cycle.init ctxt cycle seed)
(return ctxt)
(0 --> (preserved + 1))
(Seed_repr.initial_seeds (preserved + 2))
let cycle_end ctxt last_cycle =
let preserved = Constants_storage.preserved_cycles ctxt in
( match Cycle_repr.sub last_cycle preserved with
| None ->
return ctxt
| Some cleared_cycle ->
clear_cycle ctxt cleared_cycle )
>>=? fun ctxt ->
match Cycle_repr.pred last_cycle with
| None ->
return (ctxt, [])
| Some revealed ->
(* cycle with revelations *)
let inited_seed_cycle = Cycle_repr.add last_cycle (preserved + 1) in
compute_for_cycle ctxt ~revealed inited_seed_cycle
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
omake_lexer.ml | (*
* We build lexers from channels.
*)
(*
* An action is a symbol.
*)
module LexerAction =
struct
type action = Lm_symbol.t
let choose = max
let pp_print_action = Lm_symbol.pp_print_symbol
let hash : action -> int = Hashtbl.hash
let compare = Lm_symbol.compare
end
module Lexer = Lm_lexer.MakeLexer (Lm_channel.LexerInput) (LexerAction);;
(*
* Some extra functions.
*)
let lexer_of_string s =
snd (Lexer.add_clause Lexer.empty Omake_symbol.lex_sym s)
let lexer_matches info s =
Lexer.matches info (Lm_channel.of_string s)
| (*
* We build lexers from channels.
*) |
dune |
(executable
(name config)
(libraries f0))
(cram
(package functoria)
(deps config.exe ../../../functoria-runtime.opam))
| |
lib.c |
/*
* This file contains code derived from musl libc, licensed under the
* following standard MIT license:
*
* Copyright © 2005-2014 Rich Felker, et al.
*
* 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.
*/
/*
* This file currently serves dual purposes; it's used both by the Solo5
* bindings code and the tests. The presence of __SOLO5_BINDINGS__ controls
* which mode of operation is selected.
*
* When adding functions to this file ensure that they are entirely
* self-contained, or, even better, work on the TODO below instead.
*
* TODO: Replace this with a proper intergration of nolibc into both the
* kernel and tests.
*/
#ifdef __SOLO5_BINDINGS__
#include "bindings.h"
#endif
void *memset(void *dest, int c, size_t n)
{
unsigned char *s = dest;
for (; n; n--, s++) *s = c;
return dest;
}
void *memcpy(void *restrict dest, const void *restrict src, size_t n)
{
unsigned char *d = dest;
const unsigned char *s = src;
for (; n; n--) *d++ = *s++;
return dest;
}
#define WT size_t
#define WS (sizeof(WT))
void *memmove(void *dest, const void *src, size_t n)
{
char *d = dest;
const char *s = src;
if (d==s) return d;
if (s+n <= d || d+n <= s) return memcpy(d, s, n);
if (d<s) {
if ((uintptr_t)s % WS == (uintptr_t)d % WS) {
while ((uintptr_t)d % WS) {
if (!n--) return dest;
*d++ = *s++;
}
for (; n>=WS; n-=WS, d+=WS, s+=WS) *(WT *)d = *(WT *)s;
}
for (; n; n--) *d++ = *s++;
} else {
if ((uintptr_t)s % WS == (uintptr_t)d % WS) {
while ((uintptr_t)(d+n) % WS) {
if (!n--) return dest;
d[n] = s[n];
}
while (n>=WS) n-=WS, *(WT *)(d+n) = *(WT *)(s+n);
}
while (n) n--, d[n] = s[n];
}
return dest;
}
int memcmp(const void *vl, const void *vr, size_t n)
{
const unsigned char *l=vl, *r=vr;
for (; n && *l == *r; n--, l++, r++);
return n ? *l-*r : 0;
}
int strcmp(const char *l, const char *r)
{
for (; *l==*r && *l; l++, r++);
return *(unsigned char *)l - *(unsigned char *)r;
}
char *strcpy(char *restrict dest, const char *restrict src)
{
const unsigned char *s = (const unsigned char *)src;
unsigned char *d = (unsigned char *)dest;
while ((*d++ = *s++));
return dest;
}
#define UCHAR_MAX 255
#define ALIGN (sizeof(size_t))
#define ONES ((size_t)-1/UCHAR_MAX)
#define HIGHS (ONES * (UCHAR_MAX/2+1))
#define HASZERO(x) (((x)-ONES) & ~(x) & HIGHS)
size_t strlen(const char *s)
{
const char *a = s;
const size_t *w;
for (; (uintptr_t)s % ALIGN; s++) if (!*s) return s-a;
for (w = (const void *)s; !HASZERO(*w); w++);
for (s = (const void *)w; *s; s++);
return s-a;
}
int isspace(int c)
{
return c == ' ' || (unsigned)c-'\t' < 5;
}
int strncmp(const char *_l, const char *_r, size_t n)
{
const unsigned char *l=(void *)_l, *r=(void *)_r;
if (!n--) return 0;
for (; *l && *r && n && *l == *r ; l++, r++, n--);
return *l - *r;
}
| /*
* Copyright (c) 2015-2019 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.
*/ |
role.ml |
type t = [ `Viewer | `Builder | `Monitor | `Admin ] [@@deriving show]
| |
nativeint.mli | (** This module extends {{!Base.Nativeint}[Base.Nativeint]}. *)
(** @inline *)
include module type of struct
include Base.Nativeint
end
include
Int_intf.Extension with type t := t and type comparator_witness := comparator_witness
| (** This module extends {{!Base.Nativeint}[Base.Nativeint]}. *)
|
tx_rollup_withdraw_list_hash_repr.mli | include S.HASH
val hash_uncarbonated : Tx_rollup_withdraw_repr.t list -> t
val empty : t
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2022 Nomadic Labs <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
operation_result.mli | open Protocol
open Alpha_context
val pp_internal_operation :
Format.formatter -> Script_typed_ir.packed_internal_operation -> unit
val pp_internal_operation_result :
Format.formatter -> Apply_results.packed_internal_contents -> unit
val pp_operation_result :
Format.formatter ->
'kind contents_list * 'kind Apply_results.contents_result_list ->
unit
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
t-log.c |
#include "arb.h"
int main()
{
slong iter;
flint_rand_t state;
flint_printf("log....");
fflush(stdout);
flint_randinit(state);
/* compare with mpfr */
for (iter = 0; iter < 100000 * arb_test_multiplier(); iter++)
{
arb_t a, b;
fmpq_t q;
mpfr_t t;
slong prec = 2 + n_randint(state, 200);
arb_init(a);
arb_init(b);
fmpq_init(q);
mpfr_init2(t, prec + 100);
do {
arb_randtest(a, state, 1 + n_randint(state, 200), 10);
} while (arb_contains_nonpositive(a));
arb_randtest(b, state, 1 + n_randint(state, 200), 10);
arb_get_rand_fmpq(q, state, a, 1 + n_randint(state, 200));
fmpq_get_mpfr(t, q, MPFR_RNDN);
/* todo: estimate cancellation precisely */
if (mpfr_cmp_d(t, 1 - 1e-10) > 0 && mpfr_cmp_d(t, 1 + 1e-10) < 0)
{
mpfr_set_prec(t, prec + 1000);
fmpq_get_mpfr(t, q, MPFR_RNDN);
}
mpfr_log(t, t, MPFR_RNDN);
arb_log(b, a, prec);
if (!arb_contains_mpfr(b, t))
{
flint_printf("FAIL: containment\n\n");
flint_printf("a = "); arb_print(a); flint_printf("\n\n");
flint_printf("b = "); arb_print(b); flint_printf("\n\n");
flint_abort();
}
arb_log(a, a, prec);
if (!arb_equal(a, b))
{
flint_printf("FAIL: aliasing\n\n");
flint_abort();
}
arb_clear(a);
arb_clear(b);
fmpq_clear(q);
mpfr_clear(t);
}
/* compare with mpfr (higher precision) */
for (iter = 0; iter < 1000 * arb_test_multiplier(); iter++)
{
arb_t a, b;
fmpq_t q;
mpfr_t t;
slong prec = 2 + n_randint(state, 6000);
arb_init(a);
arb_init(b);
fmpq_init(q);
mpfr_init2(t, prec + 100);
do {
arb_randtest(a, state, 1 + n_randint(state, 6000), 10);
} while (arb_contains_nonpositive(a));
if (n_randint(state, 10) == 0)
arb_set_ui(a, n_randint(state, 100));
arb_randtest(b, state, 1 + n_randint(state, 6000), 10);
arb_get_rand_fmpq(q, state, a, 1 + n_randint(state, 200));
fmpq_get_mpfr(t, q, MPFR_RNDN);
/* todo: estimate cancellation precisely */
if (mpfr_cmp_d(t, 1 - 1e-10) > 0 && mpfr_cmp_d(t, 1 + 1e-10) < 0)
{
mpfr_set_prec(t, prec + 10000);
fmpq_get_mpfr(t, q, MPFR_RNDN);
}
mpfr_log(t, t, MPFR_RNDN);
arb_log(b, a, prec);
if (!arb_contains_mpfr(b, t))
{
flint_printf("FAIL: containment\n\n");
flint_printf("a = "); arb_print(a); flint_printf("\n\n");
flint_printf("b = "); arb_print(b); flint_printf("\n\n");
flint_abort();
}
arb_log(a, a, prec);
if (!arb_equal(a, b))
{
flint_printf("FAIL: aliasing\n\n");
flint_abort();
}
arb_clear(a);
arb_clear(b);
fmpq_clear(q);
mpfr_clear(t);
}
/* test large numbers */
for (iter = 0; iter < 10000 * arb_test_multiplier(); iter++)
{
arb_t a, b, ab, lab, la, lb, lalb;
slong prec = 2 + n_randint(state, 6000);
arb_init(a);
arb_init(b);
arb_init(ab);
arb_init(lab);
arb_init(la);
arb_init(lb);
arb_init(lalb);
arb_randtest(a, state, 1 + n_randint(state, 400), 400);
arb_randtest(b, state, 1 + n_randint(state, 400), 400);
arb_log(la, a, prec);
arb_log(lb, b, prec);
arb_mul(ab, a, b, prec);
arb_log(lab, ab, prec);
arb_add(lalb, la, lb, prec);
if (!arb_overlaps(lab, lalb))
{
flint_printf("FAIL: containment\n\n");
flint_printf("a = "); arb_print(a); flint_printf("\n\n");
flint_printf("b = "); arb_print(b); flint_printf("\n\n");
flint_printf("la = "); arb_print(la); flint_printf("\n\n");
flint_printf("lb = "); arb_print(lb); flint_printf("\n\n");
flint_printf("ab = "); arb_print(ab); flint_printf("\n\n");
flint_printf("lab = "); arb_print(lab); flint_printf("\n\n");
flint_printf("lalb = "); arb_print(lalb); flint_printf("\n\n");
flint_abort();
}
arb_log(a, a, prec);
if (!arb_overlaps(a, la))
{
flint_printf("FAIL: aliasing\n\n");
flint_abort();
}
arb_clear(a);
arb_clear(b);
arb_clear(ab);
arb_clear(lab);
arb_clear(la);
arb_clear(lb);
arb_clear(lalb);
}
flint_randclear(state);
flint_cleanup();
flint_printf("PASS\n");
return EXIT_SUCCESS;
}
| /*
Copyright (C) 2012 Fredrik Johansson
This file is part of Arb.
Arb is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <http://www.gnu.org/licenses/>.
*/ |
Exception.mli | (*
Wrapper around Printexc to ensure or at least encourage uniform
exception tracing.
In some cases, exceptions are caught and passed around as data before
being ultimately reraised. When doing this, it's important to keep track
of where the exception was originally raised so we can understand what
happened and debug the issue.
To do this, we must capture a stack trace where the exception
is first caught. Then, we can reraise this exception later with a proper
function that will extend the original backtrace and give us a full trace.
How to use exceptions for successful error tracking:
1. Raise fresh exceptions normally using 'raise'.
2. Use 'Exception.reraise' to reraise exceptions.
3. Right after catching an exception with a try-with,
call 'Exception.catch'.
4. When defining a new exception, define an exception printer and
register it globally with 'Printexc.register_printer'.
* Do not pass exceptions around without an accompanying trace.
* Do not re-raise exceptions using 'raise'.
*)
(*
A traced exception is a pair (exception, stack trace)
The stack trace is a best effort to track the execution of the program
up to the point where the exception was raised. OCaml offers mechanisms
to produce the following kinds of traces under the same type:
- stack backtrace: represents the call stack at the point where the last
exception to be raised was raised ('Printexc.get_backtrace ()').
- stack trace: represents the current call stack, possibly truncated to
some maximum size ('Printexc.get_callstack 100').
- extended trace: a trace that was extended by stitching multiple traces
together ('Printexc.raise_with_backtrace exn trace').
This module provides a thin interface to the standard 'Printexc'
module with the goal of forcing the programmer to do the right thing
and/or understand what they're doing.
*)
type t
(* Catch any exception and capture a stack backtrace *)
val catch_all : (unit -> 'a) -> ('a, t) Result.t
(* Create a traced exception in case we can't use 'catch_all'.
This records the stack backtrace which is the state of the call stack
where the exception was raised. *)
val catch : exn -> t
(* Re-raise an exception, extending the previous trace. *)
val reraise : t -> 'a
(* Re-raise a freshly-caught exception, preserving the stack backtrace
that indicates where the exception was originally raised.
Must be called immediately after catching the exception with try-with
before any other exception could be raised and caught during the
execution of other functions. *)
val catch_and_reraise : exn -> 'a
(* Create a traced exception and record the state of the stack at this point
in the program execution. When catching an exception, it's best to
use 'catch' instead so as to get the full stack
(where the exception was raised rather than the smaller stack where
the exception was caught). *)
val trace : exn -> t
(* Low-level creation of a traced exception. *)
val create : exn -> Printexc.raw_backtrace -> t
(* Get the original exception without the trace. *)
val get_exn : t -> exn
(* Get the trace. *)
val get_trace : t -> Printexc.raw_backtrace
(*
Convert the exception and the trace into a string in a multiline format
suitable for error messages. It always includes a terminal newline ('\n').
It uses the standard 'Printexc.to_string' function, which itself will
call the custom exception printers registered with
'Printexc.register_printer'.
*)
val to_string : t -> string
| (*
Wrapper around Printexc to ensure or at least encourage uniform
exception tracing.
In some cases, exceptions are caught and passed around as data before
being ultimately reraised. When doing this, it's important to keep track
of where the exception was originally raised so we can understand what
happened and debug the issue.
To do this, we must capture a stack trace where the exception
is first caught. Then, we can reraise this exception later with a proper
function that will extend the original backtrace and give us a full trace.
How to use exceptions for successful error tracking:
1. Raise fresh exceptions normally using 'raise'.
2. Use 'Exception.reraise' to reraise exceptions.
3. Right after catching an exception with a try-with,
call 'Exception.catch'.
4. When defining a new exception, define an exception printer and
register it globally with 'Printexc.register_printer'.
* Do not pass exceptions around without an accompanying trace.
* Do not re-raise exceptions using 'raise'.
*) |
dune |
(executable
(modes native byte_complete)
(modules stubs_exe)
(name stubs_exe)
(foreign_stubs
(mode native)
(language c)
(flags :standard -DNATIVE_CODE)
(names c_stubs))
(foreign_stubs
(mode byte)
(language c)
(flags :standard)
(names c_stubs)))
(executable
(modes native byte_complete)
(modules stubs_lib)
(name stubs_lib)
(libraries lib_with_md_stubs))
| |
main.ml | (* 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. *)
open Tester
let () =
Test.concurrent "unix" [
Test_lwt_unix.suite;
Test_lwt_io.suite;
Test_lwt_io_non_block.suite;
Test_lwt_process.suite;
Test_lwt_engine.suite;
Test_mcast.suite;
Test_lwt_fmt.suite;
Test_lwt_timeout.suite;
Test_lwt_bytes.suite;
Test_sleep_and_timeout.suite;
]
| (* 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. *) |
script_int.mli | (** The types for arbitrary precision integers in Michelson.
The type variable ['t] is always [n] or [z],
[n num] and [z num] are incompatible.
This is internally a [Z.t].
This module mostly adds signedness preservation guarantees. *)
type 't repr
(** [num] is made algebraic in order to distinguish it from the other type
parameters of [Script_typed_ir.ty]. *)
type 't num = Num_tag of 't repr [@@ocaml.unboxed]
(** Flag for natural numbers. *)
type n = Natural_tag
(** Flag for relative numbers. *)
type z = Integer_tag
(** Natural zero. *)
val zero_n : n num
(** Natural one. *)
val one_n : n num
(** Natural successor.
[succ_n x] is the same as [add_n one_n].
*)
val succ_n : n num -> n num
(** Relative zero. *)
val zero : z num
(** Relative one. *)
val one : z num
(** Compare two numbers as if they were *)
val compare : 'a num -> 'a num -> int
(** Conversion to an OCaml [string] in decimal notation. *)
val to_string : _ num -> string
(** Conversion from an OCaml [string].
Returns [None] in case of an invalid notation.
Supports [+] and [-] sign modifiers, and [0x], [0o] and [0b] base modifiers. *)
val of_string : string -> z num option
(** Conversion from an OCaml [int32]. *)
val of_int32 : int32 -> z num
(** Conversion to an OCaml [int64], returns [None] on overflow. *)
val to_int64 : _ num -> int64 option
(** Conversion from an OCaml [int64]. *)
val of_int64 : int64 -> z num
(** Conversion to an OCaml [int], returns [None] on overflow. *)
val to_int : _ num -> int option
(** Conversion from an OCaml [int]. *)
val of_int : int -> z num
(** Conversion from a Zarith integer ([Z.t]). *)
val of_zint : Z.t -> z num
(** Conversion to a Zarith integer ([Z.t]). *)
val to_zint : 'a num -> Z.t
(** Addition between naturals. *)
val add_n : n num -> n num -> n num
(** Multiplication with a natural. *)
val mul_n : n num -> 'a num -> 'a num
(** Euclidean division of a natural.
[ediv_n n d] returns [None] if divisor is zero,
or [Some (q, r)] where [n = d * q + r] and [[0 <= r < d]] otherwise. *)
val ediv_n : n num -> 'a num -> ('a num * n num) option
(** Sign agnostic addition.
Use {!add_n} when working with naturals to preserve the sign. *)
val add : _ num -> _ num -> z num
(** Sign agnostic subtraction.
Use {!sub_n} when working with naturals to preserve the sign. *)
val sub : _ num -> _ num -> z num
(** Sign agnostic multiplication.
Use {!mul_n} when working with a natural to preserve the sign. *)
val mul : _ num -> _ num -> z num
(** Sign agnostic euclidean division.
[ediv n d] returns [None] if divisor is zero,
or [Some (q, r)] where [n = d * q + r] and [[0 <= r < |d|]] otherwise.
Use {!ediv_n} when working with a natural to preserve the sign. *)
val ediv : _ num -> _ num -> (z num * n num) option
(** Compute the absolute value of a relative, turning it into a natural. *)
val abs : z num -> n num
(** Partial identity over [N]. *)
val is_nat : z num -> n num option
(** Negates a number. *)
val neg : _ num -> z num
(** Turns a natural into a relative, not changing its value. *)
val int : n num -> z num
(** Reverses each bit in the representation of the number.
Also applies to the sign. *)
val lognot : _ num -> z num
(** Shifts the natural to the left of a number of bits between 0 and 256.
Returns [None] if the amount is too high. *)
val shift_left_n : n num -> n num -> n num option
(** Shifts the natural to the right of a number of bits between 0 and 256.
Returns [None] if the amount is too high. *)
val shift_right_n : n num -> n num -> n num option
(** Shifts the number to the left of a number of bits between 0 and 256.
Returns [None] if the amount is too high. *)
val shift_left : 'a num -> n num -> 'a num option
(** Shifts the number to the right of a number of bits between 0 and 256.
Returns [None] if the amount is too high. *)
val shift_right : 'a num -> n num -> 'a num option
(** Applies a boolean or operation to each bit. *)
val logor : 'a num -> 'a num -> 'a num
(** Applies a boolean and operation to each bit. *)
val logand : _ num -> n num -> n num
(** Applies a boolean xor operation to each bit. *)
val logxor : n num -> n num -> n num
(** Naturals are encoded using Data_encoding.n *)
val n_encoding : n num Data_encoding.encoding
(** Integers are encoded using Data_encoding.z *)
val z_encoding : z num Data_encoding.encoding
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* Copyright (c) 2021-2022 Nomadic Labs <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
dune |
(test
(name tests)
(libraries ca-certs-nss alcotest))
| |
cursor.ml | (* Dump a table to stdout (using a cursor for demonstration) *)
open! Postgresql
let _ =
if Array.length Sys.argv <> 3 then (
Printf.printf "\
Usage: cursor conninfo table\n\
Connect to PostgreSQL with [conninfo] (e.g. \"host=localhost\"),\n\
and copy [table] to stdout using a cursor\n";
exit 1)
let main () =
let c = new connection ~conninfo:Sys.argv.(1) () in
ignore (c#exec ~expect:[Command_ok] "BEGIN");
ignore (
c#exec
~expect:[Command_ok]
("DECLARE my_cursor CURSOR FOR SELECT * FROM " ^ Sys.argv.(2)));
let rec loop () =
let res = c#exec ~expect:[Tuples_ok] "FETCH IN my_cursor" in
if res#ntuples <> 0 then (
let tpl = res#get_tuple 0 in
print_string tpl.(0);
for i = 1 to Array.length tpl - 1 do print_string (" " ^ tpl.(i)) done;
print_newline ();
loop ()) in
loop ();
ignore (c#exec ~expect:[Command_ok] "CLOSE my_cursor");
ignore (c#exec ~expect:[Command_ok] "END");
c#finish
let _ =
try main () with
| Error e -> prerr_endline (string_of_error e)
| e -> prerr_endline (Printexc.to_string e)
| (* Dump a table to stdout (using a cursor for demonstration) *)
|
registry_intf.ml |
module type Intf = sig
type t
(** The type of the component registry *)
(** The type of the component selector. Either all components,
or just the specified components plus all of their dependencies. *)
type component_selector =
| All_components
| Just_named_components_plus_their_dependencies of string list
val get : unit -> t
(** Get a reference to the global component registry *)
val add_component :
?raise_on_error:bool ->
t ->
(module Dkml_install_api.Component_config) ->
unit
(** [add_component ?raise_on_error registry component] adds the component to the registry.
Ordinarily if there is an error a process {!exit} is performed. Set
[raise_on_error] to [true] to raise an {!Invalid_argument} error instead. *)
val validate : ?raise_on_error:bool -> t -> unit
(** [validate ?raise_on_error registry] succeeds if and only if all dependencies of all
[add_component registry] have been themselves added.
Ordinarily if there is an error a process {!exit} is performed. Set
[raise_on_error] to [true] to raise an {!Invalid_argument} error instead. *)
val install_eval :
t ->
selector:component_selector ->
f:
((module Dkml_install_api.Component_config) ->
'a Dkml_install_api.Forward_progress.t) ->
fl:Dkml_install_api.Forward_progress.fatal_logger ->
'a list Dkml_install_api.Forward_progress.t
(** [install_eval registry ~f ~fl] iterates through the registry in dependency order
using component's {!Dkml_install_api.Component_config.install_depends_on} value,
executing function [f] on each component configuration.
Errors will go to the fatal logger [fl]. *)
val uninstall_eval :
t ->
selector:component_selector ->
f:
((module Dkml_install_api.Component_config) ->
'a Dkml_install_api.Forward_progress.t) ->
fl:Dkml_install_api.Forward_progress.fatal_logger ->
'a list Dkml_install_api.Forward_progress.t
(** [uninstall_eval registry ~f ~fl] iterates through the registry in reverse
dependency order using component's {!Dkml_install_api.Component_config.install_depends_on} value,
executing function [f] on each component configuration.
Errors will go to the fatal logger [fl]. *)
(** The module [Private] is meant for internal use only. *)
module Private : sig
val reset : unit -> unit
end
end
| |
fs_access.ml |
type mode = [
| `R
| `Rw
| `chown
| `chmod
| `stat
]
type t = {
r : string list Stramon_lib.Path_trie.t;
rw : string list Stramon_lib.Path_trie.t;
chown : string list Stramon_lib.Path_trie.t;
chmod : string list Stramon_lib.Path_trie.t;
stat : string list Stramon_lib.Path_trie.t;
}
let empty : t =
{
r = Stramon_lib.Path_trie.empty;
rw = Stramon_lib.Path_trie.empty;
chown = Stramon_lib.Path_trie.empty;
chmod = Stramon_lib.Path_trie.empty;
stat = Stramon_lib.Path_trie.empty;
}
let string_of_file_kind (kind : Unix.file_kind) : string =
let open Unix in
match kind with
| S_REG -> "REG"
| S_DIR -> "DIR"
| S_CHR -> "CHR"
| S_BLK -> "BLK"
| S_LNK -> "LNK"
| S_FIFO -> "FIFO"
| S_SOCK -> "SOCK"
let add (path : Stramon_lib.Abs_path.t) (mode : mode) (t : t) : t =
let aux trie =
let l = Stramon_lib.Path_trie.find path trie
|> Option.value ~default:[]
|> (fun l ->
match Stramon_lib.Utils.kind_of_file path with
| None -> l
| Some kind ->
string_of_file_kind kind :: l
)
|> List.sort_uniq String.compare
in
Stramon_lib.Path_trie.add path l trie
in
match mode with
| `R -> { t with r = aux t.r }
| `Rw -> { t with rw = aux t.rw }
| `chmod -> { t with chmod = aux t.chmod }
| `chown -> { t with chown = aux t.chown }
| `stat -> { t with stat = aux t.stat }
let json_of_trie (trie : string list Stramon_lib.Path_trie.t) : Yojson.Basic.t =
let l = Stramon_lib.Path_trie.to_seq trie
|> Seq.map (fun (path, kinds) ->
let v =
match kinds with
| [] -> `Null
| [x] -> `String x
| l -> `List (List.map (fun s -> `String s) l)
in
(Stramon_lib.Abs_path.to_string path, v)
)
|> List.of_seq
in
`Assoc l
let to_json (t : t) : Yojson.Basic.t =
`Assoc
[
("r", json_of_trie t.r);
("rw", json_of_trie t.rw);
("chmod", json_of_trie t.chmod);
("chown", json_of_trie t.chown);
("stat", json_of_trie t.stat);
]
| |
module1.ml |
let hello_string = "hello"
let hello name = Printf.printf "hello %s!\n" name
| |
forutop.mli |
val run : unit -> unit
| |
t-compose.c |
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
#include "flint.h"
#include "fmpz.h"
#include "fmpz_poly.h"
#include "ulong_extras.h"
int
main(void)
{
int i, result;
FLINT_TEST_INIT(state);
flint_printf("compose....");
fflush(stdout);
/* Bill's bug */
{
fmpz_poly_t f, g, h, s, t;
slong k;
fmpz_poly_init(f);
fmpz_poly_init(g);
fmpz_poly_init(h);
fmpz_poly_init(s);
fmpz_poly_init(t);
fmpz_poly_set_str(g, "21 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6");
fmpz_poly_set_str(h, "8 -2411740686 -274861162464 -4294966273 -35167058005888 4261511676 -1 8589869056 -70334401183747");
fmpz_poly_set_ui(t, 1);
for (k = 0; k < g->length; k++)
{
fmpz_poly_scalar_addmul_fmpz(s, t, g->coeffs + k);
fmpz_poly_mul(t, t, h);
}
fmpz_poly_compose(f, g, h);
result = (fmpz_poly_equal(f, s));
if (!result)
{
flint_printf("FAIL (Bill's bug):\n");
flint_printf("g = "), fmpz_poly_print(g), flint_printf("\n\n");
flint_printf("h = "), fmpz_poly_print(h), flint_printf("\n\n");
flint_printf("f = "), fmpz_poly_print(f), flint_printf("\n\n");
flint_printf("s = "), fmpz_poly_print(s), flint_printf("\n\n");
fflush(stdout);
flint_abort();
}
fmpz_poly_clear(f);
fmpz_poly_clear(g);
fmpz_poly_clear(h);
fmpz_poly_clear(s);
fmpz_poly_clear(t);
}
/* Check aliasing of the first argument */
for (i = 0; i < 10 * flint_test_multiplier(); i++)
{
fmpz_poly_t f, g, h;
fmpz_poly_init(f);
fmpz_poly_init(g);
fmpz_poly_init(h);
fmpz_poly_randtest(g, state, n_randint(state, 40), 80);
fmpz_poly_randtest(h, state, n_randint(state, 20), 50);
fmpz_poly_compose(f, g, h);
fmpz_poly_compose(g, g, h);
result = (fmpz_poly_equal(f, g));
if (!result)
{
flint_printf("FAIL (aliasing 1):\n");
fmpz_poly_print(f), flint_printf("\n\n");
fmpz_poly_print(g), flint_printf("\n\n");
fflush(stdout);
flint_abort();
}
fmpz_poly_clear(f);
fmpz_poly_clear(g);
fmpz_poly_clear(h);
}
/* Check aliasing of the second argument */
for (i = 0; i < 10 * flint_test_multiplier(); i++)
{
fmpz_poly_t f, g, h;
fmpz_poly_init(f);
fmpz_poly_init(g);
fmpz_poly_init(h);
fmpz_poly_randtest(g, state, n_randint(state, 40), 80);
fmpz_poly_randtest(h, state, n_randint(state, 20), 50);
fmpz_poly_compose(f, g, h);
fmpz_poly_compose(h, g, h);
result = (fmpz_poly_equal(f, h));
if (!result)
{
flint_printf("FAIL (aliasing 2):\n");
fmpz_poly_print(f), flint_printf("\n\n");
fmpz_poly_print(h), flint_printf("\n\n");
fflush(stdout);
flint_abort();
}
fmpz_poly_clear(f);
fmpz_poly_clear(g);
fmpz_poly_clear(h);
}
/* Compare with the naive method for g(h(t)) */
for (i = 0; i < 10 * flint_test_multiplier(); i++)
{
fmpz_poly_t f, g, h, s, t;
slong k;
fmpz_poly_init(f);
fmpz_poly_init(g);
fmpz_poly_init(h);
fmpz_poly_init(s);
fmpz_poly_init(t);
fmpz_poly_randtest(g, state, n_randint(state, 40), 80);
fmpz_poly_randtest(h, state, n_randint(state, 20), 50);
fmpz_poly_set_ui(t, 1);
for (k = 0; k < g->length; k++)
{
fmpz_poly_scalar_addmul_fmpz(s, t, g->coeffs + k);
fmpz_poly_mul(t, t, h);
}
fmpz_poly_compose(f, g, h);
result = (fmpz_poly_equal(f, s));
if (!result)
{
flint_printf("FAIL (comparison):\n");
flint_printf("g = "), fmpz_poly_print(g), flint_printf("\n\n");
flint_printf("h = "), fmpz_poly_print(h), flint_printf("\n\n");
flint_printf("f = "), fmpz_poly_print(f), flint_printf("\n\n");
flint_printf("s = "), fmpz_poly_print(s), flint_printf("\n\n");
fflush(stdout);
flint_abort();
}
fmpz_poly_clear(f);
fmpz_poly_clear(g);
fmpz_poly_clear(h);
fmpz_poly_clear(s);
fmpz_poly_clear(t);
}
/* Testing linear composition*/
for (i = 0; i < 10 * flint_test_multiplier(); i++)
{
fmpz_poly_t f, g, h, s, t;
fmpz_t c;
slong k;
fmpz_init(c);
fmpz_poly_init(f);
fmpz_poly_init(g);
fmpz_poly_init(h);
fmpz_poly_init(s);
fmpz_poly_init(t);
/* h is a linear polynomial*/
for (k = 0; k < 2; k++)
{
fmpz_randtest(c, state, 50);
fmpz_poly_set_coeff_fmpz(h, k, c);
}
fmpz_poly_randtest(g, state, n_randint(state, 40), 80);
fmpz_poly_set_ui(t, 1);
for (k = 0; k < g->length; k++)
{
fmpz_poly_scalar_addmul_fmpz(s, t, g->coeffs + k);
fmpz_poly_mul(t, t, h);
}
fmpz_poly_compose(f, g, h);
result = (fmpz_poly_equal(f, s));
if (!result)
{
flint_printf("FAIL (linear composition):\n");
flint_printf("g = "), fmpz_poly_print(g), flint_printf("\n\n");
flint_printf("h = "), fmpz_poly_print(h), flint_printf("\n\n");
flint_printf("f = "), fmpz_poly_print(f), flint_printf("\n\n");
flint_printf("s = "), fmpz_poly_print(s), flint_printf("\n\n");
fflush(stdout);
flint_abort();
}
fmpz_poly_clear(f);
fmpz_poly_clear(g);
fmpz_poly_clear(h);
fmpz_poly_clear(s);
fmpz_poly_clear(t);
}
FLINT_TEST_CLEANUP(state);
flint_printf("PASS\n");
return 0;
}
| /*
Copyright (C) 2009 William Hart
Copyright (C) 2010 Sebastian Pancratz
Copyright (C) 2016 Shivin Srivastava
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/>.
*/ |
luarun.ml |
module type INTERP = sig
module Value : Luavalue.S
type value = Value.value
type state = Value.state
val mk : unit -> state
val dostring : ?file:string -> state -> string -> value list
val dofile : state -> string -> value list
end
module Make (I : INTERP) = struct
module V = I.Value
let state = I.mk()
let dumpstate = ref false
let run infile = ignore (I.dofile state infile)
let run_interactive infile =
let rec loop n pfx =
let line = input_line infile in
if String.length line > 0 && String.get line (String.length line - 1) = '\\' then
loop n (pfx ^ String.sub line 0 (String.length line - 1) ^ "\n")
else
begin
ignore (I.dostring state (pfx ^ line ^ "\n"));
flush stdout; flush stderr;
loop (n+1) ""
end
in try loop 1 "" with End_of_file -> ()
let rec args = function
| "-dump" :: a's -> (dumpstate := true; args a's)
| "-new" :: a's -> args a's
| [] -> run_interactive stdin
| files -> List.iter run files
let _ = args (List.tl (Array.to_list (Sys.argv)))
let _ = if !dumpstate then
begin
print_endline "final state: ";
V.Luahash.iter (fun k v -> print_string " ";
print_string (V.to_string k); print_string " |-> ";
print_endline (V.to_string v)) state.V.globals
end
end
| |
btorsimhelpers.h |
#ifndef BTOR2HELP_H_INCLUDED
#define BTOR2HELP_H_INCLUDED
#include <cassert>
#include <cstdarg>
#include <string>
#include <vector>
#include "btor2parser/btor2parser.h"
#include "btorsimbv.h"
extern int32_t verbosity;
void die (const char *m, ...);
void msg (int32_t level, const char *m, ...);
// get the sort for a line (have to go through argument for some operators)
Btor2Sort *get_sort (Btor2Line *l, Btor2Parser *model);
// same as btorsim_bv_to_char and btorsim_bv_to_hex_char but return value is
// std::string
std::string btorsim_bv_to_string (const BtorSimBitVector *bv);
std::string btorsim_bv_to_hex_string (const BtorSimBitVector *bv);
#endif
| /**
* Btor2Tools: A tool package for the BTOR format.
*
* Copyright (c) 2013-2016 Mathias Preiner.
* Copyright (c) 2015-2018 Aina Niemetz.
* Copyright (c) 2018 Armin Biere.
* Copyright (c) 2020 Nina Engelhardt.
*
* All rights reserved.
*
* This file is part of the Btor2Tools package.
* See LICENSE.txt for more information on using this software.
*/ |
alternative.mli | (** Building a {!module:Preface_specs.Alternative} *)
(** {1 Using the minimal definition} *)
(** {2 Using pure, apply, neutral and combine}
Build a {!module-type:Preface_specs.ALTERNATIVE} using
{!module-type:Preface_specs.Alternative.WITH_APPLY}.
Standard method, using the minimal definition of an alt to derive its full
API. *)
module Via_pure_and_apply (Req : Preface_specs.Alternative.WITH_PURE_AND_APPLY) :
Preface_specs.ALTERNATIVE with type 'a t = 'a Req.t
(** {2 Using pure, map, product, neutral and combine}
Build a {!module-type:Preface_specs.ALTERNATIVE} using
{!module-type:Preface_specs.Alternative.WITH_MAP_AND_PRODUCT}.
Other standard method, using the minimal definition of an alt to derive its
full API. *)
module Via_pure_map_and_product
(Req : Preface_specs.Alternative.WITH_PURE_MAP_AND_PRODUCT) :
Preface_specs.ALTERNATIVE with type 'a t = 'a Req.t
(** {2 Using pure, lift2, neutral and combine}
Build a {!module-type:Preface_specs.ALTERNATIVE} using
{!module-type:Preface_specs.Alternative.WITH_LIFT2}.
Other standard method, using the minimal definition of an alt to derive its
full API. *)
module Via_pure_and_lift2 (Req : Preface_specs.Alternative.WITH_PURE_AND_LIFT2) :
Preface_specs.ALTERNATIVE with type 'a t = 'a Req.t
(** {2 Over an applicative}
Build a {!module-type:Preface_specs.ALTERNATIVE} over an
{!module-type:Preface_specs.APPLICATIVE}.
If you already have an Applicative, you can enrich it by passing only
[combine] and [neutral].. *)
module Over_applicative
(Applicative : Preface_specs.APPLICATIVE)
(Req : Preface_specs.Alternative.WITH_NEUTRAL_AND_COMBINE
with type 'a t = 'a Applicative.t) :
Preface_specs.ALTERNATIVE with type 'a t = 'a Req.t
(** {1 Alternative Algebra}
Construction of {!module-type:Preface_specs.ALTERNATIVE} by combining them. *)
(** {2 Composition}
Right-to-left composition of {!module-type:Preface_specs.ALTERNATIVE} with
{!module-type:Preface_specs.APPLICATIVE}.*)
module Composition
(F : Preface_specs.ALTERNATIVE)
(G : Preface_specs.APPLICATIVE) :
Preface_specs.ALTERNATIVE with type 'a t = 'a G.t F.t
(** {2 Product}
Construct the product of two {!module-type:Preface_specs.ALTERNATIVE}. *)
module Product (F : Preface_specs.ALTERNATIVE) (G : Preface_specs.ALTERNATIVE) :
Preface_specs.ALTERNATIVE with type 'a t = 'a F.t * 'a G.t
(** {1 From other abstraction} *)
(** {2 From an Arrow Plus}
Produces an {!module-type:Preface_specs.ALTERNATIVE} from an
{!module-type:Preface_specs.ARROW_PLUS}. *)
module From_arrow_plus (A : Preface_specs.ARROW_PLUS) :
Preface_specs.ALTERNATIVE with type 'a t = (unit, 'a) A.t
(** {1 Manual construction}
Advanced way to build an {!module-type:Preface_specs.ALTERNATIVE},
constructing and assembling a component-by-component of
{!module-type:Preface_specs.ALTERNATIVE}. (In order to provide your own
implementation for some features.) *)
(** {2 Grouping of all components} *)
module Via
(Core : Preface_specs.Alternative.CORE)
(Operation : Preface_specs.Alternative.OPERATION with type 'a t = 'a Core.t)
(Infix : Preface_specs.Alternative.INFIX with type 'a t = 'a Core.t)
(Syntax : Preface_specs.Alternative.SYNTAX with type 'a t = 'a Core.t) :
Preface_specs.ALTERNATIVE with type 'a t = 'a Core.t
(** {2 Building Core} *)
module Core_via_pure_map_and_product
(Req : Preface_specs.Alternative.WITH_PURE_MAP_AND_PRODUCT) :
Preface_specs.Alternative.CORE with type 'a t = 'a Req.t
module Core_via_pure_and_apply
(Req : Preface_specs.Alternative.WITH_PURE_AND_APPLY) :
Preface_specs.Alternative.CORE with type 'a t = 'a Req.t
module Core_via_pure_and_lift2
(Req : Preface_specs.Alternative.WITH_PURE_AND_LIFT2) :
Preface_specs.Alternative.CORE with type 'a t = 'a Req.t
(** {2 Deriving Operation} *)
module Operation (Core : Preface_specs.Alternative.CORE) :
Preface_specs.Alternative.OPERATION with type 'a t = 'a Core.t
(** {2 Deriving Syntax} *)
module Syntax (Core : Preface_specs.Alternative.CORE) :
Preface_specs.Alternative.SYNTAX with type 'a t = 'a Core.t
(** {2 Deriving Infix} *)
module Infix
(Core : Preface_specs.Alternative.CORE)
(Operation : Preface_specs.Alternative.OPERATION with type 'a t = 'a Core.t) :
Preface_specs.Alternative.INFIX with type 'a t = 'a Core.t
| (** Building a {!module:Preface_specs.Alternative} *)
|
value.ml |
module Make (I : Cstubs_inverted.INTERNAL) = struct
open Util.Make (I)
let () =
fn "value_unit" (void @-> returning value) (fun () -> Root.create_value ())
let () =
fn "value_int"
(int64_t @-> returning value)
(fun i -> Root.create_value (Int64.to_int i))
let () =
fn "value_float" (double @-> returning value) (fun i -> Root.create_value i)
let () =
fn "value_bool" (bool @-> returning value) (fun b -> Root.create_value b)
let () =
fn "value_clone"
(value @-> returning value)
(fun x -> Root.create_value (Root.get_value x))
let () =
fn "realloc"
(ptr void @-> ptr void @-> returning (ptr void))
(fun src dest ->
Ctypes.Root.set src (Ctypes.Root.get dest);
src)
let () =
fn "value_get_string"
(value @-> returning irmin_string)
(fun value ->
let obj = Root.get_value value |> Obj.repr in
if Obj.tag obj = Obj.string_tag then Root.create_string (Obj.obj obj)
else null irmin_string)
let () =
fn "value_get_int"
(value @-> returning int64_t)
(fun x ->
let obj = Root.get_value x |> Obj.repr in
if Obj.is_int obj then Int64.of_int (Obj.obj obj) else Int64.zero)
let () =
fn "value_get_bool"
(value @-> returning bool)
(fun x ->
let obj = Root.get_value x |> Obj.repr in
if Obj.is_int obj then Obj.obj obj else false)
let () =
fn "value_get_float"
(value @-> returning double)
(fun x ->
let obj = Root.get_value x |> Obj.repr in
if Obj.is_int obj then Obj.obj obj else 0.)
let () =
fn "value_bytes"
(ptr char @-> int64_t @-> returning value)
(fun s length ->
let length = get_length length s in
Root.create_value (Bytes.of_string (string_from_ptr s ~length)))
let () =
fn "value_string"
(ptr char @-> int64_t @-> returning value)
(fun s length ->
let length = get_length length s in
Root.create_value (string_from_ptr s ~length))
let () =
fn "value_array"
(ptr value @-> uint64_t @-> returning value)
(fun arr n ->
let n = UInt64.to_int n in
let a =
if is_null arr || n = 0 then [||]
else
CArray.from_ptr arr n
|> CArray.to_list
|> List.map Root.get_value
|> Array.of_list
in
Root.create_value a)
let () =
fn "value_list"
(ptr value @-> uint64_t @-> returning value)
(fun arr n ->
let n = UInt64.to_int n in
let l =
if is_null arr || n = 0 then []
else
CArray.from_ptr arr n |> CArray.to_list |> List.map Root.get_value
in
Root.create_value l)
let () =
fn "value_option"
(value @-> returning value)
(fun value ->
if is_null value then Root.create_value None
else
let x = Root.get_value value in
Root.create_value (Some x))
let () =
fn "value_pair"
(value @-> value @-> returning value)
(fun a b ->
let a = Root.get_value a in
let b = Root.get_value b in
Root.create_value (a, b))
let () =
fn "value_triple"
(value @-> value @-> value @-> returning value)
(fun a b c ->
let a = Root.get_value a in
let b = Root.get_value b in
let c = Root.get_value c in
Root.create_value (a, b, c))
let () =
fn "value_to_string"
(ty @-> value @-> returning irmin_string)
(fun ty value ->
let t = Root.get_ty ty in
let v = Root.get_value value in
let s = Irmin.Type.to_string t v in
Root.create_string s)
let () =
fn "value_of_string"
(ty @-> ptr char @-> int64_t @-> returning value)
(fun ty s length ->
let length = get_length length s in
let ty = Root.get_ty ty in
let s = string_from_ptr s ~length in
match Irmin.Type.(of_string ty) s with
| Ok x -> Root.create_value x
| Error (`Msg _) -> null value)
let () =
fn "value_to_bin"
(ty @-> value @-> returning irmin_string)
(fun ty v ->
let t = Root.get_ty ty in
let v = Root.get_value v in
let s = Irmin.Type.(unstage (to_bin_string t)) v in
Root.create_string s)
let () =
fn "value_of_bin"
(ty @-> ptr char @-> int64_t @-> returning value)
(fun ty s length ->
let length = get_length length s in
let ty = Root.get_ty ty in
let s = string_from_ptr s ~length in
match Irmin.Type.(unstage (of_bin_string ty)) s with
| Ok x -> Root.create_value x
| Error (`Msg _) -> null value)
let () =
fn "value_to_json"
(ty @-> value @-> returning irmin_string)
(fun ty v ->
let t = Root.get_ty ty in
let v = Root.get_value v in
let s = Irmin.Type.(to_json_string t) v in
Root.create_string s)
let () =
fn "value_of_json"
(ty @-> ptr char @-> int64_t @-> returning value)
(fun ty s length ->
let length = get_length length s in
let ty = Root.get_ty ty in
let s = string_from_ptr s ~length in
match Irmin.Type.(of_json_string ty) s with
| Ok x -> Root.create_value x
| Error (`Msg _) -> null value)
let () =
fn "value_equal"
(ty @-> value @-> value @-> returning bool)
(fun ty a b ->
let ty = Root.get_ty ty in
let a = Root.get_value a in
let b = Root.get_value b in
Irmin.Type.(unstage (equal ty)) a b)
let () =
fn "value_compare"
(ty @-> value @-> value @-> returning int)
(fun ty a b ->
let ty = Root.get_ty ty in
let a = Root.get_value a in
let b = Root.get_value b in
Irmin.Type.(unstage (compare ty)) a b)
let () = fn "value_free" (value @-> returning void) free
let () =
fn "string_new"
(ptr char @-> int64_t @-> returning irmin_string)
(fun ptr i ->
let i = Int64.to_int i in
let length = if i < 0 then strlen ptr else i in
let s = string_from_ptr ptr ~length in
Root.create_string s)
let () =
fn "string_data"
(irmin_string @-> returning (ptr char))
(fun s ->
if is_null s then null (ptr char)
else
let s : string = Root.get_string s in
coerce string (ptr char) s)
let () =
fn "string_length"
(irmin_string @-> returning uint64_t)
(fun s ->
if is_null s then UInt64.zero
else
let s : string = Root.get_string s in
String.length s |> UInt64.of_int)
let () = fn "string_free" (irmin_string @-> returning void) free
end
| |
image.ml |
let create_mmap (type color) ?mode kind
(module C : Bimage.COLOR with type t = color) ~filename w h =
let data = Data.create_mmap ?mode kind ~filename (w * h * C.channels C.t) in
Bimage.Image.of_data (module C) w h data
| |
dune |
(executables
(names test_tzList
test_lwt_pipe
test_lru_cache
test_ring_basic
test_ring_plus
test_weakringtable
test_ring_weakness)
(libraries tezos-stdlib
alcotest
lwt_log
bigstring
lwt.unix)
(flags (:standard -open Tezos_stdlib)))
(alias
(name buildtest)
(deps test_tzList.exe
test_lwt_pipe.exe
test_ring_basic.exe
test_ring_plus.exe
test_weakringtable.exe))
(alias
(name runtest_tzList)
(action (run %{exe:test_tzList.exe})))
(alias
(name runtest_lwt_pipe)
(action (run %{exe:test_lwt_pipe.exe})))
(alias
(name runtest_lru_cache)
(action (run %{exe:test_lru_cache.exe})))
(alias
(name runtest_ring_basic)
(action (run %{exe:test_ring_basic.exe})))
(alias
(name runtest_ring_plus)
(action (run %{exe:test_ring_plus.exe})))
(alias
(name runtest_weakringtable)
(action (run %{exe:test_weakringtable.exe})))
(alias
(name runtest)
(package tezos-stdlib)
(deps (alias runtest_tzList)
(alias runtest_lwt_pipe)
(alias runtest_lru_cache)
(alias runtest_ring_basic)
(alias runtest_ring_plus)
(alias runtest_weakringtable)))
(alias
(name buildweaknesstest)
(deps test_ring_weakness.exe))
(alias
(name runweaknesstest)
(action (setenv OCAMLRUNPARAM "o=20,h=16,s=16,i=2" (run %{exe:test_ring_weakness.exe}))))
(alias
(name runtest_lint)
(deps (glob_files *.ml{,i}))
(action (run %{lib:tezos-tooling:lint.sh} %{deps})))
| |
store_logging.mli | include Internal_event.Legacy_logging.LOG
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
mrcu.ml |
(* RCU translation *)
open Printf
let prog = if Array.length Sys.argv > 0 then Sys.argv.(0) else "mrcu"
module Top
(O:
sig
val verbose : int
val outputdir : string option
val outall : string -> unit
val force : bool
end) =
struct
module LISA = BellBase
module LISALexParse = struct
type instruction = LISA.parsedPseudo
type token = LISAParser.token
module L = BellLexer.Make(Splitter.Default)
let lexer = L.token
let parser = LISAParser.main
end
module Dec = struct let hexa = false end
module P = GenParser.Make(GenParser.DefaultConfig)(LISA)(LISALexParse)
module A = ArchExtra_tools.Make(Dec)(LISA)(PteVal.No)
module Alloc = SymbReg.Make(A)
module D = Dumper.Make(A)
module RegAlloc = struct
type t = A.RegSet.t A.ProcMap.t
let all_regs = A.RegSet.of_list A.allowed_for_symb
module Collect = CollectRegs.Make(A)
let create t =
let m0 = Collect.collect t in
A.ProcMap.map
(fun rs -> A.RegSet.diff all_regs rs)
m0
let alloc p m =
let rs = A.ProcMap.safe_find all_regs p m in
let r =
try A.RegSet.min_elt rs
with Not_found -> Warn.fatal "Not enough registers" in
r,A.ProcMap.add p (A.RegSet.remove r rs) m
end
module F = struct
open LISA
(* Reduce critical sections to useful ones *)
let rec opt d p = match p with
| Macro _|Symbolic _ -> assert false
| Label (lbl,p) ->
let d,p = opt d p in
d,Label (lbl,p)
| Nop -> d,Nop
| Instruction i ->
begin match i with
| Pfence (Fence (["rcu_read_unlock"],None)) ->
if d <= 0 then Warn.user_error "extra unlock"
else if d = 1 then 0,p
else d-1,Nop
| Pfence (Fence (["rcu_read_lock"],None)) ->
if d > 0 then d+1,Nop
else 1,p
| _ -> d,p
end
let rec do_opt_code d = function
| [] -> d,[]
| p::k ->
let d,p = opt d p in
begin match p with
| Nop -> do_opt_code d k
| _ ->
let d,k = do_opt_code d k in
d,p::k
end
let opt_code cs =
let d,cs = do_opt_code 0 cs in
if d > 0 then Warn.user_error "extra lock"
else cs
let opt_test t =
let open MiscParser in
{ t with prog = List.map (fun (i,cs) -> i,opt_code cs) t.prog; }
(* Count sync and unlock *)
let count (syncs,unlocks as c) = function
| Pcall "sync"|Pfence (Fence (["sync"],None)) -> syncs+1,unlocks
| Pfence (Fence (["rcu_read_unlock"],None)) -> syncs,unlocks+1
| _ -> c
let count_test t =
List.fold_right
(fun (_,cs) k ->
List.fold_right
(fun c k -> pseudo_fold count k c)
cs k)
t.MiscParser.prog (0,0)
(* Big work: translate call[sync], f[lock] and f[unlock] *)
let sync_var i = sprintf "S%i" i
let cs_var i = sprintf "C%i" i
let fence = Pfence (Fence (["mb"],None))
let store_release x v =
Pst (Addr_op_atom (Abs x),Imm v,["release"])
let read_acquire r x =
Pld (r,Addr_op_atom (Abs x),["acquire"])
let set r = Pmov (r,RAI (IAR_imm 1))
let cons_ins i k= Instruction i::k
let tr n m u v s c id =
let rec do_tr (idx_sync,idx_unlock,free as st) p = match p with
| Macro _|Symbolic _ -> assert false
| Nop -> st,[Nop]
| Label (lbl,p) ->
let st,ps = do_tr st p in
begin match ps with
| [] -> st,[Label (lbl,Nop); ]
| p::ps -> st,Label (lbl,p)::ps
end
| Instruction i ->
begin match i with
| Pcall "sync"
| Pfence (Fence (["sync"],None)) ->
let k = cons_ins fence [] in
let rec add_reads free i k =
if i >= m then free,k
else
let r,free = RegAlloc.alloc id free in
v.(i).(idx_sync) <- (id,r) ;
let free,k = add_reads free (i+1) k in
free,cons_ins (read_acquire r (cs_var i)) k in
let free,k = add_reads free 0 k in
let r,free = RegAlloc.alloc id free in
s.(idx_sync) <- (id,r) ;
let k = cons_ins fence k in
let k = cons_ins (set r) k in
let k = cons_ins (store_release (sync_var idx_sync) 1) k in
let k = cons_ins fence k in
(idx_sync+1,idx_unlock,free),k
| Pfence (Fence (["rcu_read_lock"],None)) ->
let rec add_reads free j k =
if j >= n then free,k
else
let r,free = RegAlloc.alloc id free in
u.(j).(idx_unlock) <- (id,r) ;
let free,k = add_reads free (j+1) k in
free,cons_ins (read_acquire r (sync_var j)) k in
let free,ps = add_reads free 0 [] in
(idx_sync,idx_unlock,free),ps
| Pfence (Fence (["rcu_read_unlock"],None)) ->
let r,free = RegAlloc.alloc id free in
c.(idx_unlock) <- (id,r) ;
(idx_sync,idx_unlock+1,free),
cons_ins
(store_release (cs_var idx_unlock) 1)
(cons_ins (set r) [])
| _ -> st,[p]
end
and tr_code st ps = match ps with
| [] -> st,[]
| p::ps ->
let st,p = do_tr st p in
let st,ps = tr_code st ps in
st,p@ps in
tr_code
let zero = A.zero
let one = A.one
let tr_test n m u v s c free =
let rec tr_rec st = function
| [] -> []
| ((p,_,f) as id,ps)::rem ->
assert (f = MiscParser.Main) ;
let st,ps = tr n m u v s c p st ps in
(id,ps)::tr_rec st rem in
fun t ->
let open MiscParser in
let prog = tr_rec (0,0,free) t.prog in
let open ConstrGen in
let rec loop_i i k =
if i >= m then k
else
let rec loop_j j k =
if j >= n then k
else
let id1,r1 = v.(i).(j) and id2,r2 = u.(j).(i) in
let id3,r3 = s.(j) and id4,r4 = c.(i) in
Or
[
Atom (LV (Loc (A.Location_reg (id1,r1)),one));
Atom (LV (Loc (A.Location_reg (id2,r2)),one));
Atom (LV (Loc (A.Location_reg (id3,r3)),zero));
Atom (LV (Loc (A.Location_reg (id4,r4)),zero));
]::loop_j (j+1) k in
loop_j 0 (loop_i (i+1) k) in
let filter = Some (ConstrGen.And (loop_i 0 []) ) in
{ t with prog; filter; }
let noreg = -1,LISA.GPRreg (-1)
let dump = match O.outputdir with
| None -> D.dump_info stdout
| Some d ->
fun name t ->
let fname = name.Name.file in
let base = Filename.basename fname in
let fname = Filename.concat d base in
Misc.output_protect
(fun chan -> D.dump_info chan name t)
fname ;
O.outall base
let zyva name t =
try
let t = opt_test t in
let n,m = count_test t in
if O.verbose > 0 then begin
eprintf "%s: nsyncs=%i, nunlock=%i\n" name.Name.name n m ;
end ;
(* silent fail if no real rcu *)
if O.force then begin
if (n = 0 && m = 0) then raise Misc.Exit
end else begin
if (n = 0 || m = 0) then raise Misc.Exit
end ;
let u = Array.make_matrix n m noreg
and v = Array.make_matrix m n noreg
and s = Array.make n noreg
and c = Array.make m noreg
and free = RegAlloc.create t in
let t = tr_test n m u v s c free t in
dump name t
with Misc.Fatal msg|Misc.UserError msg ->
eprintf "Adios: %s\n" msg ;
D.dump_info stderr name t ;
raise Misc.Exit
end
let from_chan chan splitted = match splitted.Splitter.arch with
| `LISA ->
let name = splitted.Splitter.name in
let parsed = P.parse chan splitted in
let parsed = Alloc.allocate_regs parsed in
F.zyva name parsed
| arch -> Warn.user_error "Bad arch for %s: %s" prog (Archs.pp arch)
module SP = Splitter.Make(Splitter.Default)
let from_file fname =
Misc.input_protect
(fun chan ->
let (splitted:Splitter.result) = SP.split fname chan in
from_chan chan splitted) fname
end
let verbose = ref 0
let outputdir = ref None
let force = ref false
let args = ref []
let opts =
[
"-v",Arg.Unit (fun () -> incr verbose), " be verbose";
"-o", Arg.String (fun s -> outputdir := Some s),
"<name> all output in directory <name>";
"-force", Arg.Bool (fun b -> force := b),
sprintf "<bool> force translation, default %b" !force;
]
let () =
Arg.parse opts
(fun s -> args := !args @ [s])
(sprintf "Usage: %s [options]* [test]*" prog)
let allchan = match !outputdir with
| None -> None
| Some d -> Some (open_out (Filename.concat d "@all"))
module X =
Top
(struct
let verbose = !verbose
let outputdir = !outputdir
let outall = match allchan with
| None -> fun _ -> ()
| Some chan -> Printf.fprintf chan "%s\n"
let force = !force
end)
let () =
Misc.iter_argv_or_stdin
(fun fname ->
try X.from_file fname with
| Misc.Exit -> ()
| Misc.Fatal msg|Misc.UserError msg ->
Warn.warn_always "%a %s" Pos.pp_pos0 fname msg ;
()
| e ->
Printf.eprintf "\nFatal: %a Adios\n" Pos.pp_pos0 fname ;
raise e)
!args ;
match allchan with
| None -> ()
| Some chan -> close_out chan
| (****************************************************************************)
(* the diy toolsuite *)
(* *)
(* Jade Alglave, University College London, UK. *)
(* Luc Maranget, INRIA Paris-Rocquencourt, France. *)
(* *)
(* Copyright 2016-present Institut National de Recherche en Informatique et *)
(* en Automatique and the authors. All rights reserved. *)
(* *)
(* This software is governed by the CeCILL-B license under French law and *)
(* abiding by the rules of distribution of free software. You can use, *)
(* modify and/ or redistribute the software under the terms of the CeCILL-B *)
(* license as circulated by CEA, CNRS and INRIA at the following URL *)
(* "http://www.cecill.info". We also give a copy in LICENSE.txt. *)
(****************************************************************************)
|
dune |
(executable
(name main)
(libraries tezt)
(flags (:standard) -open Tezt -open Tezt.Base))
(cram
(deps tezt.sh main.exe))
| |
int_replace_polymorphic_compare.ml |
let ( = ) : int -> int -> bool = Stdlib.( = )
let ( <> ) : int -> int -> bool = Stdlib.( <> )
let ( < ) : int -> int -> bool = Stdlib.( < )
let ( > ) : int -> int -> bool = Stdlib.( > )
let ( <= ) : int -> int -> bool = Stdlib.( <= )
let ( >= ) : int -> int -> bool = Stdlib.( >= )
let compare : int -> int -> int = Stdlib.compare
| |
period_repr.ml | type t = Int64.t
type period = t
include (Compare.Int64 : Compare.S with type t := t)
let encoding = Data_encoding.int64
let rpc_arg = RPC_arg.int64
let pp ppf v = Format.fprintf ppf "%Ld" v
type error += (* `Permanent *)
Malformed_period | Invalid_arg
let () =
let open Data_encoding in
(* Malformed period *)
register_error_kind
`Permanent
~id:"malformed_period"
~title:"Malformed period"
~description:"Period is negative."
~pp:(fun ppf () -> Format.fprintf ppf "Malformed period")
empty
(function Malformed_period -> Some () | _ -> None)
(fun () -> Malformed_period) ;
(* Invalid arg *)
register_error_kind
`Permanent
~id:"invalid_arg"
~title:"Invalid arg"
~description:"Negative multiple of periods are not allowed."
~pp:(fun ppf () -> Format.fprintf ppf "Invalid arg")
empty
(function Invalid_arg -> Some () | _ -> None)
(fun () -> Invalid_arg)
let of_seconds t =
if Compare.Int64.(t >= 0L) then ok t else error Malformed_period
let to_seconds t = t
let of_seconds_exn t =
match of_seconds t with
| Ok t ->
t
| _ ->
invalid_arg "Period.of_seconds_exn"
let mult i p =
(* TODO check overflow *)
if Compare.Int32.(i < 0l) then error Invalid_arg
else ok (Int64.mul (Int64.of_int32 i) p)
let zero = of_seconds_exn 0L
let one_second = of_seconds_exn 1L
let one_minute = of_seconds_exn 60L
let one_hour = of_seconds_exn 3600L
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
lwt_react.mli | (* 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. *)
(** React utilities *)
(** This module is an overlay for the [React] module. You can open it
instead of the [React] module in order to get all of [React]'s functions
plus Lwt ones.
This module is provided by OPAM package [lwt_react]. Link with ocamlfind
package [lwt_react]. *)
type 'a event = 'a React.event
(** Type of events. *)
type 'a signal = 'a React.signal
(** Type of signals. *)
module E : sig
include module type of React.E
(** {2 Lwt-specific utilities} *)
val with_finaliser : (unit -> unit) -> 'a event -> 'a event
(** [with_finaliser f e] returns an event [e'] which behave as
[e], except that [f] is called when [e'] is garbage
collected. *)
val next : 'a event -> 'a Lwt.t
(** [next e] returns the next occurrence of [e].
Avoid trying to create an “asynchronous loop” by calling [next e] again in
a callback attached to the promise returned by [next e]:
- The callback is called within the React update step, so calling [next e]
within it will return a promise that is fulfilled with the same value as
the current occurrence.
- If you instead arrange for the React update step to end (for example, by
calling [Lwt.pause ()] within the callback), multiple React update steps
may occur before the callback calls [next e] again, so some occurrences
can be effectively “lost.”
To robustly asynchronously process occurrences of [e] in a loop, use
[to_stream e], and repeatedly call {!Lwt_stream.next} on the resulting
stream. *)
val limit : (unit -> unit Lwt.t) -> 'a event -> 'a event
(** [limit f e] limits the rate of [e] with [f].
For example, to limit the rate of an event to 1 per second you
can use: [limit (fun () -> Lwt_unix.sleep 1.0) event]. *)
val from : (unit -> 'a Lwt.t) -> 'a event
(** [from f] creates an event which occurs each time [f ()]
returns a value. If [f] raises an exception, the event is just
stopped. *)
val to_stream : 'a event -> 'a Lwt_stream.t
(** Creates a stream holding all values occurring on the given
event *)
val of_stream : 'a Lwt_stream.t -> 'a event
(** [of_stream stream] creates an event which occurs each time a
value is available on the stream.
If updating the event causes an exception at any point during the update
step, the exception is passed to [!]{!Lwt.async_exception_hook}, which
terminates the process by default. *)
val delay : 'a event Lwt.t -> 'a event
(** [delay promise] is an event which does not occur until
[promise] resolves. Then it behaves as the event returned by
[promise]. *)
val keep : 'a event -> unit
(** [keep e] keeps a reference to [e] so it will never be garbage
collected. *)
(** {2 Threaded versions of React transformation functions} *)
(** The following functions behave as their [React] counterpart,
except that they take functions that may yield.
As usual the [_s] suffix is used when calls are serialized, and
the [_p] suffix is used when they are not.
Note that [*_p] functions may not preserve event order. *)
val app_s : ('a -> 'b Lwt.t) event -> 'a event -> 'b event
val app_p : ('a -> 'b Lwt.t) event -> 'a event -> 'b event
val map_s : ('a -> 'b Lwt.t) -> 'a event -> 'b event
val map_p: ('a -> 'b Lwt.t) -> 'a event -> 'b event
val filter_s : ('a -> bool Lwt.t) -> 'a event -> 'a event
val filter_p : ('a -> bool Lwt.t) -> 'a event -> 'a event
val fmap_s : ('a -> 'b option Lwt.t) -> 'a event -> 'b event
val fmap_p : ('a -> 'b option Lwt.t) -> 'a event -> 'b event
val diff_s : ('a -> 'a -> 'b Lwt.t) -> 'a event -> 'b event
val accum_s : ('a -> 'a Lwt.t) event -> 'a -> 'a event
val fold_s : ('a -> 'b -> 'a Lwt.t) -> 'a -> 'b event -> 'a event
val merge_s : ('a -> 'b -> 'a Lwt.t) -> 'a -> 'b event list -> 'a event
val run_s : 'a Lwt.t event -> 'a event
val run_p : 'a Lwt.t event -> 'a event
end
module S : sig
include module type of React.S
(** {2 Monadic interface} *)
val return : 'a -> 'a signal
(** Same as [const]. *)
val bind : ?eq : ('b -> 'b -> bool) -> 'a signal -> ('a -> 'b signal) -> 'b signal
(** [bind ?eq s f] is initially [f x] where [x] is the current
value of [s]. Each time [s] changes to a new value [y], [bind
signal f] is set to [f y], until the next change of
[signal]. *)
val bind_s : ?eq : ('b -> 'b -> bool) -> 'a signal -> ('a -> 'b signal Lwt.t) -> 'b signal Lwt.t
(** Same as {!bind} except that [f] returns a promise. Calls to [f]
are serialized. *)
(** {2 Lwt-specific utilities} *)
val with_finaliser : (unit -> unit) -> 'a signal -> 'a signal
(** [with_finaliser f s] returns a signal [s'] which behaves as
[s], except that [f] is called when [s'] is garbage
collected. *)
val limit : ?eq : ('a -> 'a -> bool) -> (unit -> unit Lwt.t) -> 'a signal -> 'a signal
(** [limit f s] limits the rate of [s] update with [f].
For example, to limit it to 1 per second, you can use: [limit
(fun () -> Lwt_unix.sleep 1.0) s]. *)
val keep : 'a signal -> unit
(** [keep s] keeps a reference to [s] so it will never be garbage
collected. *)
(** {2 Threaded versions of React transformation functions} *)
(** The following functions behave as their [React] counterpart,
except that they take functions that may yield.
The [_s] suffix means that calls are serialized.
*)
val app_s : ?eq : ('b -> 'b -> bool) -> ('a -> 'b Lwt.t) signal -> 'a signal -> 'b signal Lwt.t
val map_s : ?eq : ('b -> 'b -> bool) -> ('a -> 'b Lwt.t) -> 'a signal -> 'b signal Lwt.t
val filter_s : ?eq : ('a -> 'a -> bool) -> ('a -> bool Lwt.t) -> 'a -> 'a signal -> 'a signal Lwt.t
val fmap_s : ?eq:('b -> 'b -> bool) -> ('a -> 'b option Lwt.t) -> 'b -> 'a signal -> 'b signal Lwt.t
val diff_s : ('a -> 'a -> 'b Lwt.t) -> 'a signal -> 'b event
val sample_s : ('b -> 'a -> 'c Lwt.t) -> 'b event -> 'a signal -> 'c event
val accum_s : ?eq : ('a -> 'a -> bool) -> ('a -> 'a Lwt.t) event -> 'a -> 'a signal
val fold_s : ?eq : ('a -> 'a -> bool) -> ('a -> 'b -> 'a Lwt.t) -> 'a -> 'b event -> 'a signal
val merge_s : ?eq : ('a -> 'a -> bool) -> ('a -> 'b -> 'a Lwt.t) -> 'a -> 'b signal list -> 'a signal Lwt.t
val l1_s : ?eq : ('b -> 'b -> bool) -> ('a -> 'b Lwt.t) -> 'a signal -> 'b signal Lwt.t
val l2_s : ?eq : ('c -> 'c -> bool) -> ('a -> 'b -> 'c Lwt.t) -> 'a signal -> 'b signal -> 'c signal Lwt.t
val l3_s : ?eq : ('d -> 'd -> bool) -> ('a -> 'b -> 'c -> 'd Lwt.t) -> 'a signal -> 'b signal -> 'c signal -> 'd signal Lwt.t
val l4_s : ?eq : ('e -> 'e -> bool) -> ('a -> 'b -> 'c -> 'd -> 'e Lwt.t) -> 'a signal -> 'b signal -> 'c signal -> 'd signal -> 'e signal Lwt.t
val l5_s : ?eq : ('f -> 'f -> bool) -> ('a -> 'b -> 'c -> 'd -> 'e -> 'f Lwt.t) -> 'a signal -> 'b signal -> 'c signal -> 'd signal -> 'e signal -> 'f signal Lwt.t
val l6_s : ?eq : ('g -> 'g -> bool) -> ('a -> 'b -> 'c -> 'd -> 'e -> 'f -> 'g Lwt.t) -> 'a signal -> 'b signal -> 'c signal -> 'd signal -> 'e signal -> 'f signal -> 'g signal Lwt.t
val run_s : ?eq : ('a -> 'a -> bool) -> 'a Lwt.t signal -> 'a signal Lwt.t
end
| (* 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. *) |
ptr_queues.h |
/*
* QUEUES OF POINTERS
*/
#ifndef __PTR_QUEUES_H
#define __PTR_QUEUES_H
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>
/*
* Components:
* - data = integer array to store the pointers
* - size = size of that array
* - head, tail = indices between 0 and size - 1.
* The queue is managed as a circular array:
* - if head = tail, the queue is empty
* - if head < tail, queue content is data[head ... tail-1]
* - if head > tail, queue content is
* data[head...size-1] + data[0 ... tail-1]
*/
typedef struct ptr_queue_s {
void **data;
uint32_t size;
uint32_t head;
uint32_t tail;
} ptr_queue_t;
#define DEF_PTR_QUEUE_SIZE 16
#define MAX_PTR_QUEUE_SIZE (UINT32_MAX/sizeof(void *))
/*
* Initialize a queue of size n.
* If n = 0 then the default size is used
*/
extern void init_ptr_queue(ptr_queue_t *q, uint32_t n);
/*
* Delete q
*/
extern void delete_ptr_queue(ptr_queue_t *q);
/*
* Push element p in the queue (at the end)
*/
extern void ptr_queue_push(ptr_queue_t *q, void *p);
/*
* Check whether the queue is empty
*/
static inline bool ptr_queue_is_empty(ptr_queue_t *q) {
return q->head == q->tail;
}
/*
* Return the first element and remove it from q.
* - q must be non-empty.
*/
extern void *ptr_queue_pop(ptr_queue_t *q);
/*
* Get the first element or last element (don't remove it)
* - q must be non-empty
*/
extern void *ptr_queue_first(ptr_queue_t *q);
extern void *ptr_queue_last(ptr_queue_t *q);
/*
* Empty the queue
*/
static inline void ptr_queue_reset(ptr_queue_t *q) {
q->head = 0;
q->tail = 0;
}
#endif /* __PTR_QUEUES_H */
| /*
* The Yices SMT Solver. Copyright 2014 SRI International.
*
* This program may only be used subject to the noncommercial end user
* license agreement which is downloadable along with this program.
*/ |
dune |
(library
(name ocamlc_loc)
(public_name ocamlc-loc)
(libraries dyn))
(ocamllex lexer)
| |
indent-empty-1.ml |
module M = struct
let f =
end
let g =
fun x -> 3 + 4 *
| |
operation_repr.ml | (* Tezos Protocol Implementation - Low level Repr. of Operations *)
module Kind = struct
type seed_nonce_revelation = Seed_nonce_revelation_kind
type double_endorsement_evidence = Double_endorsement_evidence_kind
type double_baking_evidence = Double_baking_evidence_kind
type activate_account = Activate_account_kind
type endorsement = Endorsement_kind
type proposals = Proposals_kind
type ballot = Ballot_kind
type reveal = Reveal_kind
type transaction = Transaction_kind
type origination = Origination_kind
type delegation = Delegation_kind
type 'a manager =
| Reveal_manager_kind : reveal manager
| Transaction_manager_kind : transaction manager
| Origination_manager_kind : origination manager
| Delegation_manager_kind : delegation manager
end
type raw = Operation.t = {shell : Operation.shell_header; proto : MBytes.t}
let raw_encoding = Operation.encoding
type 'kind operation = {
shell : Operation.shell_header;
protocol_data : 'kind protocol_data;
}
and 'kind protocol_data = {
contents : 'kind contents_list;
signature : Signature.t option;
}
and _ contents_list =
| Single : 'kind contents -> 'kind contents_list
| Cons :
'kind Kind.manager contents * 'rest Kind.manager contents_list
-> ('kind * 'rest) Kind.manager contents_list
and _ contents =
| Endorsement : {level : Raw_level_repr.t} -> Kind.endorsement contents
| Seed_nonce_revelation : {
level : Raw_level_repr.t;
nonce : Seed_repr.nonce;
}
-> Kind.seed_nonce_revelation contents
| Double_endorsement_evidence : {
op1 : Kind.endorsement operation;
op2 : Kind.endorsement operation;
}
-> Kind.double_endorsement_evidence contents
| Double_baking_evidence : {
bh1 : Block_header_repr.t;
bh2 : Block_header_repr.t;
}
-> Kind.double_baking_evidence contents
| Activate_account : {
id : Ed25519.Public_key_hash.t;
activation_code : Blinded_public_key_hash.activation_code;
}
-> Kind.activate_account contents
| Proposals : {
source : Signature.Public_key_hash.t;
period : Voting_period_repr.t;
proposals : Protocol_hash.t list;
}
-> Kind.proposals contents
| Ballot : {
source : Signature.Public_key_hash.t;
period : Voting_period_repr.t;
proposal : Protocol_hash.t;
ballot : Vote_repr.ballot;
}
-> Kind.ballot contents
| Manager_operation : {
source : Signature.public_key_hash;
fee : Tez_repr.tez;
counter : counter;
operation : 'kind manager_operation;
gas_limit : Z.t;
storage_limit : Z.t;
}
-> 'kind Kind.manager contents
and _ manager_operation =
| Reveal : Signature.Public_key.t -> Kind.reveal manager_operation
| Transaction : {
amount : Tez_repr.tez;
parameters : Script_repr.lazy_expr;
entrypoint : string;
destination : Contract_repr.contract;
}
-> Kind.transaction manager_operation
| Origination : {
delegate : Signature.Public_key_hash.t option;
script : Script_repr.t;
credit : Tez_repr.tez;
preorigination : Contract_repr.t option;
}
-> Kind.origination manager_operation
| Delegation :
Signature.Public_key_hash.t option
-> Kind.delegation manager_operation
and counter = Z.t
let manager_kind : type kind. kind manager_operation -> kind Kind.manager =
function
| Reveal _ ->
Kind.Reveal_manager_kind
| Transaction _ ->
Kind.Transaction_manager_kind
| Origination _ ->
Kind.Origination_manager_kind
| Delegation _ ->
Kind.Delegation_manager_kind
type 'kind internal_operation = {
source : Contract_repr.contract;
operation : 'kind manager_operation;
nonce : int;
}
type packed_manager_operation =
| Manager : 'kind manager_operation -> packed_manager_operation
type packed_contents = Contents : 'kind contents -> packed_contents
type packed_contents_list =
| Contents_list : 'kind contents_list -> packed_contents_list
type packed_protocol_data =
| Operation_data : 'kind protocol_data -> packed_protocol_data
type packed_operation = {
shell : Operation.shell_header;
protocol_data : packed_protocol_data;
}
let pack ({shell; protocol_data} : _ operation) : packed_operation =
{shell; protocol_data = Operation_data protocol_data}
type packed_internal_operation =
| Internal_operation : 'kind internal_operation -> packed_internal_operation
let rec to_list = function
| Contents_list (Single o) ->
[Contents o]
| Contents_list (Cons (o, os)) ->
Contents o :: to_list (Contents_list os)
let rec of_list = function
| [] ->
assert false
| [Contents o] ->
Contents_list (Single o)
| Contents o :: os -> (
let (Contents_list os) = of_list os in
match (o, os) with
| (Manager_operation _, Single (Manager_operation _)) ->
Contents_list (Cons (o, os))
| (Manager_operation _, Cons _) ->
Contents_list (Cons (o, os))
| _ ->
Pervasives.failwith
"Operation list of length > 1 should only contains manager \
operations." )
module Encoding = struct
open Data_encoding
let case tag name args proj inj =
let open Data_encoding in
case
tag
~title:(String.capitalize_ascii name)
(merge_objs (obj1 (req "kind" (constant name))) args)
(fun x -> match proj x with None -> None | Some x -> Some ((), x))
(fun ((), x) -> inj x)
module Manager_operations = struct
type 'kind case =
| MCase : {
tag : int;
name : string;
encoding : 'a Data_encoding.t;
select : packed_manager_operation -> 'kind manager_operation option;
proj : 'kind manager_operation -> 'a;
inj : 'a -> 'kind manager_operation;
}
-> 'kind case
let reveal_case =
MCase
{
tag = 0;
name = "reveal";
encoding = obj1 (req "public_key" Signature.Public_key.encoding);
select = (function Manager (Reveal _ as op) -> Some op | _ -> None);
proj = (function Reveal pkh -> pkh);
inj = (fun pkh -> Reveal pkh);
}
let entrypoint_encoding =
def
~title:"entrypoint"
~description:"Named entrypoint to a Michelson smart contract"
"entrypoint"
@@
let builtin_case tag name =
Data_encoding.case
(Tag tag)
~title:name
(constant name)
(fun n -> if Compare.String.(n = name) then Some () else None)
(fun () -> name)
in
union
[ builtin_case 0 "default";
builtin_case 1 "root";
builtin_case 2 "do";
builtin_case 3 "set_delegate";
builtin_case 4 "remove_delegate";
Data_encoding.case
(Tag 255)
~title:"named"
(Bounded.string 31)
(fun s -> Some s)
(fun s -> s) ]
let transaction_case =
MCase
{
tag = 1;
name = "transaction";
encoding =
obj3
(req "amount" Tez_repr.encoding)
(req "destination" Contract_repr.encoding)
(opt
"parameters"
(obj2
(req "entrypoint" entrypoint_encoding)
(req "value" Script_repr.lazy_expr_encoding)));
select =
(function Manager (Transaction _ as op) -> Some op | _ -> None);
proj =
(function
| Transaction {amount; destination; parameters; entrypoint} ->
let parameters =
if
Script_repr.is_unit_parameter parameters
&& Compare.String.(entrypoint = "default")
then None
else Some (entrypoint, parameters)
in
(amount, destination, parameters));
inj =
(fun (amount, destination, parameters) ->
let (entrypoint, parameters) =
match parameters with
| None ->
("default", Script_repr.unit_parameter)
| Some (entrypoint, value) ->
(entrypoint, value)
in
Transaction {amount; destination; parameters; entrypoint});
}
let origination_case =
MCase
{
tag = 2;
name = "origination";
encoding =
obj3
(req "balance" Tez_repr.encoding)
(opt "delegate" Signature.Public_key_hash.encoding)
(req "script" Script_repr.encoding);
select =
(function Manager (Origination _ as op) -> Some op | _ -> None);
proj =
(function
| Origination
{ credit;
delegate;
script;
preorigination =
_
(* the hash is only used internally
when originating from smart
contracts, don't serialize it *)
} ->
(credit, delegate, script));
inj =
(fun (credit, delegate, script) ->
Origination {credit; delegate; script; preorigination = None});
}
let delegation_case =
MCase
{
tag = 3;
name = "delegation";
encoding = obj1 (opt "delegate" Signature.Public_key_hash.encoding);
select =
(function Manager (Delegation _ as op) -> Some op | _ -> None);
proj = (function Delegation key -> key);
inj = (fun key -> Delegation key);
}
let encoding =
let make (MCase {tag; name; encoding; select; proj; inj}) =
case
(Tag tag)
name
encoding
(fun o ->
match select o with None -> None | Some o -> Some (proj o))
(fun x -> Manager (inj x))
in
union
~tag_size:`Uint8
[ make reveal_case;
make transaction_case;
make origination_case;
make delegation_case ]
end
type 'b case =
| Case : {
tag : int;
name : string;
encoding : 'a Data_encoding.t;
select : packed_contents -> 'b contents option;
proj : 'b contents -> 'a;
inj : 'a -> 'b contents;
}
-> 'b case
let endorsement_encoding = obj1 (req "level" Raw_level_repr.encoding)
let endorsement_case =
Case
{
tag = 0;
name = "endorsement";
encoding = endorsement_encoding;
select =
(function Contents (Endorsement _ as op) -> Some op | _ -> None);
proj = (fun (Endorsement {level}) -> level);
inj = (fun level -> Endorsement {level});
}
let endorsement_encoding =
let make (Case {tag; name; encoding; select = _; proj; inj}) =
case (Tag tag) name encoding (fun o -> Some (proj o)) (fun x -> inj x)
in
let to_list : Kind.endorsement contents_list -> _ = function
| Single o ->
o
in
let of_list : Kind.endorsement contents -> _ = function o -> Single o in
def "inlined.endorsement"
@@ conv
(fun ({shell; protocol_data = {contents; signature}} : _ operation) ->
(shell, (contents, signature)))
(fun (shell, (contents, signature)) ->
({shell; protocol_data = {contents; signature}} : _ operation))
(merge_objs
Operation.shell_header_encoding
(obj2
(req
"operations"
( conv to_list of_list
@@ def "inlined.endorsement.contents"
@@ union [make endorsement_case] ))
(varopt "signature" Signature.encoding)))
let seed_nonce_revelation_case =
Case
{
tag = 1;
name = "seed_nonce_revelation";
encoding =
obj2
(req "level" Raw_level_repr.encoding)
(req "nonce" Seed_repr.nonce_encoding);
select =
(function
| Contents (Seed_nonce_revelation _ as op) -> Some op | _ -> None);
proj = (fun (Seed_nonce_revelation {level; nonce}) -> (level, nonce));
inj = (fun (level, nonce) -> Seed_nonce_revelation {level; nonce});
}
let double_endorsement_evidence_case : Kind.double_endorsement_evidence case
=
Case
{
tag = 2;
name = "double_endorsement_evidence";
encoding =
obj2
(req "op1" (dynamic_size endorsement_encoding))
(req "op2" (dynamic_size endorsement_encoding));
select =
(function
| Contents (Double_endorsement_evidence _ as op) ->
Some op
| _ ->
None);
proj = (fun (Double_endorsement_evidence {op1; op2}) -> (op1, op2));
inj = (fun (op1, op2) -> Double_endorsement_evidence {op1; op2});
}
let double_baking_evidence_case =
Case
{
tag = 3;
name = "double_baking_evidence";
encoding =
obj2
(req "bh1" (dynamic_size Block_header_repr.encoding))
(req "bh2" (dynamic_size Block_header_repr.encoding));
select =
(function
| Contents (Double_baking_evidence _ as op) -> Some op | _ -> None);
proj = (fun (Double_baking_evidence {bh1; bh2}) -> (bh1, bh2));
inj = (fun (bh1, bh2) -> Double_baking_evidence {bh1; bh2});
}
let activate_account_case =
Case
{
tag = 4;
name = "activate_account";
encoding =
obj2
(req "pkh" Ed25519.Public_key_hash.encoding)
(req "secret" Blinded_public_key_hash.activation_code_encoding);
select =
(function
| Contents (Activate_account _ as op) -> Some op | _ -> None);
proj =
(fun (Activate_account {id; activation_code}) ->
(id, activation_code));
inj =
(fun (id, activation_code) -> Activate_account {id; activation_code});
}
let proposals_case =
Case
{
tag = 5;
name = "proposals";
encoding =
obj3
(req "source" Signature.Public_key_hash.encoding)
(req "period" Voting_period_repr.encoding)
(req "proposals" (list Protocol_hash.encoding));
select =
(function Contents (Proposals _ as op) -> Some op | _ -> None);
proj =
(fun (Proposals {source; period; proposals}) ->
(source, period, proposals));
inj =
(fun (source, period, proposals) ->
Proposals {source; period; proposals});
}
let ballot_case =
Case
{
tag = 6;
name = "ballot";
encoding =
obj4
(req "source" Signature.Public_key_hash.encoding)
(req "period" Voting_period_repr.encoding)
(req "proposal" Protocol_hash.encoding)
(req "ballot" Vote_repr.ballot_encoding);
select = (function Contents (Ballot _ as op) -> Some op | _ -> None);
proj =
(function
| Ballot {source; period; proposal; ballot} ->
(source, period, proposal, ballot));
inj =
(fun (source, period, proposal, ballot) ->
Ballot {source; period; proposal; ballot});
}
let manager_encoding =
obj5
(req "source" Signature.Public_key_hash.encoding)
(req "fee" Tez_repr.encoding)
(req "counter" (check_size 10 n))
(req "gas_limit" (check_size 10 n))
(req "storage_limit" (check_size 10 n))
let extract (type kind)
(Manager_operation
{source; fee; counter; gas_limit; storage_limit; operation = _} :
kind Kind.manager contents) =
(source, fee, counter, gas_limit, storage_limit)
let rebuild (source, fee, counter, gas_limit, storage_limit) operation =
Manager_operation
{source; fee; counter; gas_limit; storage_limit; operation}
let make_manager_case tag (type kind)
(Manager_operations.MCase mcase : kind Manager_operations.case) =
Case
{
tag;
name = mcase.name;
encoding = merge_objs manager_encoding mcase.encoding;
select =
(function
| Contents (Manager_operation ({operation; _} as op)) -> (
match mcase.select (Manager operation) with
| None ->
None
| Some operation ->
Some (Manager_operation {op with operation}) )
| _ ->
None);
proj =
(function
| Manager_operation {operation; _} as op ->
(extract op, mcase.proj operation));
inj = (fun (op, contents) -> rebuild op (mcase.inj contents));
}
let reveal_case = make_manager_case 107 Manager_operations.reveal_case
let transaction_case =
make_manager_case 108 Manager_operations.transaction_case
let origination_case =
make_manager_case 109 Manager_operations.origination_case
let delegation_case =
make_manager_case 110 Manager_operations.delegation_case
let contents_encoding =
let make (Case {tag; name; encoding; select; proj; inj}) =
case
(Tag tag)
name
encoding
(fun o -> match select o with None -> None | Some o -> Some (proj o))
(fun x -> Contents (inj x))
in
def "operation.alpha.contents"
@@ union
[ make endorsement_case;
make seed_nonce_revelation_case;
make double_endorsement_evidence_case;
make double_baking_evidence_case;
make activate_account_case;
make proposals_case;
make ballot_case;
make reveal_case;
make transaction_case;
make origination_case;
make delegation_case ]
let contents_list_encoding =
conv to_list of_list (Variable.list contents_encoding)
let optional_signature_encoding =
conv
(function Some s -> s | None -> Signature.zero)
(fun s -> if Signature.equal s Signature.zero then None else Some s)
Signature.encoding
let protocol_data_encoding =
def "operation.alpha.contents_and_signature"
@@ conv
(fun (Operation_data {contents; signature}) ->
(Contents_list contents, signature))
(fun (Contents_list contents, signature) ->
Operation_data {contents; signature})
(obj2
(req "contents" contents_list_encoding)
(req "signature" optional_signature_encoding))
let operation_encoding =
conv
(fun {shell; protocol_data} -> (shell, protocol_data))
(fun (shell, protocol_data) -> {shell; protocol_data})
(merge_objs Operation.shell_header_encoding protocol_data_encoding)
let unsigned_operation_encoding =
def "operation.alpha.unsigned_operation"
@@ merge_objs
Operation.shell_header_encoding
(obj1 (req "contents" contents_list_encoding))
let internal_operation_encoding =
def "operation.alpha.internal_operation"
@@ conv
(fun (Internal_operation {source; operation; nonce}) ->
((source, nonce), Manager operation))
(fun ((source, nonce), Manager operation) ->
Internal_operation {source; operation; nonce})
(merge_objs
(obj2 (req "source" Contract_repr.encoding) (req "nonce" uint16))
Manager_operations.encoding)
end
let encoding = Encoding.operation_encoding
let contents_encoding = Encoding.contents_encoding
let contents_list_encoding = Encoding.contents_list_encoding
let protocol_data_encoding = Encoding.protocol_data_encoding
let unsigned_operation_encoding = Encoding.unsigned_operation_encoding
let internal_operation_encoding = Encoding.internal_operation_encoding
let raw ({shell; protocol_data} : _ operation) =
let proto =
Data_encoding.Binary.to_bytes_exn
protocol_data_encoding
(Operation_data protocol_data)
in
{Operation.shell; proto}
let acceptable_passes (op : packed_operation) =
let (Operation_data protocol_data) = op.protocol_data in
match protocol_data.contents with
| Single (Endorsement _) ->
[0]
| Single (Proposals _) ->
[1]
| Single (Ballot _) ->
[1]
| Single (Seed_nonce_revelation _) ->
[2]
| Single (Double_endorsement_evidence _) ->
[2]
| Single (Double_baking_evidence _) ->
[2]
| Single (Activate_account _) ->
[2]
| Single (Manager_operation _) ->
[3]
| Cons _ ->
[3]
type error += Invalid_signature (* `Permanent *)
type error += Missing_signature (* `Permanent *)
let () =
register_error_kind
`Permanent
~id:"operation.invalid_signature"
~title:"Invalid operation signature"
~description:
"The operation signature is ill-formed or has been made with the wrong \
public key"
~pp:(fun ppf () -> Format.fprintf ppf "The operation signature is invalid")
Data_encoding.unit
(function Invalid_signature -> Some () | _ -> None)
(fun () -> Invalid_signature) ;
register_error_kind
`Permanent
~id:"operation.missing_signature"
~title:"Missing operation signature"
~description:
"The operation is of a kind that must be signed, but the signature is \
missing"
~pp:(fun ppf () -> Format.fprintf ppf "The operation requires a signature")
Data_encoding.unit
(function Missing_signature -> Some () | _ -> None)
(fun () -> Missing_signature)
let check_signature_sync (type kind) key chain_id
({shell; protocol_data} : kind operation) =
let check ~watermark contents signature =
let unsigned_operation =
Data_encoding.Binary.to_bytes_exn
unsigned_operation_encoding
(shell, contents)
in
if Signature.check ~watermark key signature unsigned_operation then Ok ()
else error Invalid_signature
in
match (protocol_data.contents, protocol_data.signature) with
| (Single _, None) ->
error Missing_signature
| (Cons _, None) ->
error Missing_signature
| ((Single (Endorsement _) as contents), Some signature) ->
check
~watermark:(Endorsement chain_id)
(Contents_list contents)
signature
| ((Single _ as contents), Some signature) ->
check ~watermark:Generic_operation (Contents_list contents) signature
| ((Cons _ as contents), Some signature) ->
check ~watermark:Generic_operation (Contents_list contents) signature
let check_signature pk chain_id op =
Lwt.return (check_signature_sync pk chain_id op)
let hash_raw = Operation.hash
let hash (o : _ operation) =
let proto =
Data_encoding.Binary.to_bytes_exn
protocol_data_encoding
(Operation_data o.protocol_data)
in
Operation.hash {shell = o.shell; proto}
let hash_packed (o : packed_operation) =
let proto =
Data_encoding.Binary.to_bytes_exn protocol_data_encoding o.protocol_data
in
Operation.hash {shell = o.shell; proto}
type ('a, 'b) eq = Eq : ('a, 'a) eq
let equal_manager_operation_kind :
type a b. a manager_operation -> b manager_operation -> (a, b) eq option =
fun op1 op2 ->
match (op1, op2) with
| (Reveal _, Reveal _) ->
Some Eq
| (Reveal _, _) ->
None
| (Transaction _, Transaction _) ->
Some Eq
| (Transaction _, _) ->
None
| (Origination _, Origination _) ->
Some Eq
| (Origination _, _) ->
None
| (Delegation _, Delegation _) ->
Some Eq
| (Delegation _, _) ->
None
let equal_contents_kind :
type a b. a contents -> b contents -> (a, b) eq option =
fun op1 op2 ->
match (op1, op2) with
| (Endorsement _, Endorsement _) ->
Some Eq
| (Endorsement _, _) ->
None
| (Seed_nonce_revelation _, Seed_nonce_revelation _) ->
Some Eq
| (Seed_nonce_revelation _, _) ->
None
| (Double_endorsement_evidence _, Double_endorsement_evidence _) ->
Some Eq
| (Double_endorsement_evidence _, _) ->
None
| (Double_baking_evidence _, Double_baking_evidence _) ->
Some Eq
| (Double_baking_evidence _, _) ->
None
| (Activate_account _, Activate_account _) ->
Some Eq
| (Activate_account _, _) ->
None
| (Proposals _, Proposals _) ->
Some Eq
| (Proposals _, _) ->
None
| (Ballot _, Ballot _) ->
Some Eq
| (Ballot _, _) ->
None
| (Manager_operation op1, Manager_operation op2) -> (
match equal_manager_operation_kind op1.operation op2.operation with
| None ->
None
| Some Eq ->
Some Eq )
| (Manager_operation _, _) ->
None
let rec equal_contents_kind_list :
type a b. a contents_list -> b contents_list -> (a, b) eq option =
fun op1 op2 ->
match (op1, op2) with
| (Single op1, Single op2) ->
equal_contents_kind op1 op2
| (Single _, Cons _) ->
None
| (Cons _, Single _) ->
None
| (Cons (op1, ops1), Cons (op2, ops2)) -> (
match equal_contents_kind op1 op2 with
| None ->
None
| Some Eq -> (
match equal_contents_kind_list ops1 ops2 with
| None ->
None
| Some Eq ->
Some Eq ) )
let equal : type a b. a operation -> b operation -> (a, b) eq option =
fun op1 op2 ->
if not (Operation_hash.equal (hash op1) (hash op2)) then None
else
equal_contents_kind_list
op1.protocol_data.contents
op2.protocol_data.contents
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
test.ml | (* TEST
include ocamlcommon
* hasunix
include unix
arguments = "${ocamlsrcdir}"
** native
*)
(* This test checks all ml files in the ocaml repository that are accepted
by the parser satisfy [Ast_invariants].
We don't check the invariants on the output of the parser, so this test
is to ensure that the parser doesn't accept more than [Ast_invariants].
*)
let root = Sys.argv.(1)
let () = assert (Sys.file_exists (Filename.concat root "VERSION"))
type _ kind =
| Implem : Parsetree.structure kind
| Interf : Parsetree.signature kind
let parse : type a. a kind -> Lexing.lexbuf -> a = function
| Implem -> Parse.implementation
| Interf -> Parse.interface
let invariants : type a. a kind -> a -> unit = function
| Implem -> Ast_invariants.structure
| Interf -> Ast_invariants.signature
let check_file kind fn =
Warnings.parse_options false "-a";
let ic = open_in fn in
Location.input_name := fn;
let lexbuf = Lexing.from_channel ic in
Location.init lexbuf fn;
match parse kind lexbuf with
| exception _ ->
(* A few files don't parse as they are meant for the toplevel;
ignore them *)
close_in ic
| ast ->
close_in ic;
try
invariants kind ast
with exn ->
Location.report_exception Format.std_formatter exn
type file_kind =
| Regular_file
| Directory
| Other
let kind fn =
match Unix.lstat fn with
| exception _ -> Other
| { Unix.st_kind = Unix.S_DIR } -> Directory
| { Unix.st_kind = Unix.S_REG } -> Regular_file
| { Unix.st_kind = _ } -> Other
let rec walk dir =
Array.iter
(fun fn ->
if fn = "" || fn.[0] = '.' then
()
else begin
let fn = Filename.concat dir fn in
match kind fn with
| Other -> ()
| Directory -> walk fn
| Regular_file ->
if Filename.check_suffix fn ".mli" then
check_file Interf fn
else if Filename.check_suffix fn ".ml" then
check_file Implem fn
end)
(Sys.readdir dir)
let () = walk root
| (* TEST
include ocamlcommon
* hasunix
include unix
arguments = "${ocamlsrcdir}"
** native
*) |
dune |
(executable
(name links)
(public_name linx)
(package links)
(modes native)
(libraries threads.posix dynlink ANSITerminal linenoise links.core))
| |
api.mli |
(** Performs API requests and manipulates API data. Needs a working Internet
connection to work *)
(** {2 Requests}*)
type access_token
(** The [access_token] is the OAuth token used in every API request for
authentication *)
val get_token : string -> string -> access_token
(** [get_token cliend_id client_secret] retrieves the access token from the
LegiFrance API. You have to register on the
{{:https://developer.aife.economie.gouv.fr/} the official website of the
French government} to get your OAuth client ID and Secret for the LegiFrance
API *)
type article
type article_id
val parse_id : string -> article_id
(** [parse_id id] parses the string representing the LégiFrance object to be
fetched from the API, checks its validity (for instance
["LEGIARTI000006307920"]) and returns an [object_id]*)
val retrieve_article : access_token -> article_id -> article
(** [retrieve_article token article_id] returns the article from the LegiFrance
API.*)
(**{2 Manipulating API objects}*)
(**{3 Articles}*)
val get_article_id : article -> string
val get_article_text : article -> string
val get_article_title : article -> string
val get_article_expiration_date : article -> Unix.tm
val get_article_new_version : article -> string
| (* This file is part of the Catala compiler, a specification language for tax
and social benefits computation rules. Copyright (C) 2022 Inria, contributor:
Denis Merigoux <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License. *) |
owl_maths_interpolate.ml |
(** Interpolation and Extrapolation *)
let polint xs ys x =
let n = Array.length xs in
let m = Array.length ys in
let error () =
let s =
Printf.sprintf
"polint requires that xs and ys have the same length, but xs length is %i \
whereas ys length is %i"
n
m
in
Owl_exception.INVALID_ARGUMENT s
in
Owl_exception.verify (m = n) error;
let c = Array.copy ys in
let d = Array.copy ys in
let ns = ref 0 in
let dy = ref 0. in
let dif = ref (abs_float (x -. xs.(0))) in
for i = 0 to n - 1 do
let dift = abs_float (x -. xs.(i)) in
if dift < !dif
then (
ns := i;
dif := dift)
done;
let y = ref ys.(!ns) in
ns := !ns - 1;
for m = 0 to n - 2 do
for i = 0 to n - m - 2 do
let ho = xs.(i) -. x in
let hp = xs.(i + m + 1) -. x in
let w = c.(i + 1) -. d.(i) in
let den = ho -. hp in
assert (den <> 0.);
let den = w /. den in
c.(i) <- ho *. den;
d.(i) <- hp *. den
done;
if (2 * !ns) + 2 < n - m - 1
then dy := c.(!ns + 1)
else (
dy := d.(!ns);
ns := !ns - 1);
y := !y +. !dy
done;
!y, !dy
(* TODO: not tested yet *)
let ratint xs ys x =
let n = Array.length xs in
let m = Array.length ys in
let error () =
let s =
Printf.sprintf
"ratint requires that xs and ys have the same length, but xs length is %i \
whereas ys length is %i"
n
m
in
Owl_exception.INVALID_ARGUMENT s
in
Owl_exception.verify (m = n) error;
let c = Array.copy ys in
let d = Array.copy ys in
let hh = ref (abs_float (x -. xs.(0))) in
let y = ref 0. in
let dy = ref 0. in
let ns = ref 0 in
let eps = 1e-25 in
try
for i = 0 to n do
let h = abs_float (x -. xs.(i)) in
if h = 0.
then (
y := ys.(i);
dy := 0.;
raise Owl_exception.FOUND)
else if h < !hh
then (
ns := i;
hh := h;
c.(i) <- ys.(i);
d.(i) <- ys.(i) +. eps)
done;
y := ys.(!ns);
ns := !ns - 1;
for m = 1 to n - 1 do
for i = 1 to n - m do
let w = c.(i) -. d.(i - 1) in
let h = xs.(i + m - 1) -. x in
let t = (xs.(i - 1) -. x) *. d.(i - 1) /. h in
let dd = t -. c.(i) in
if dd = 0. then failwith "Has a pole";
let dd = w /. dd in
d.(i - 1) <- c.(i) *. dd;
c.(i - 1) <- t *. dd
done
done;
!y, !dy
with
| Owl_exception.FOUND -> !y, !dy
| e -> raise e
| (*
* OWL - OCaml Scientific and Engineering Computing
* Copyright (c) 2016-2020 Liang Wang <[email protected]>
*) |
test_poly_compare.ml | open Js_of_ocaml
let%expect_test "poly equal" =
let obj1 = Js.Unsafe.obj [||] in
let obj2 = Js.Unsafe.obj [||] in
assert (List.mem obj1 [ obj1 ]);
assert (List.mem obj1 [ obj2; obj1 ]);
assert (not (List.mem obj1 [ obj2 ]));
()
let%expect_test "poly equal neg" =
let obj1 = Js.Unsafe.obj [||] in
let obj2 = Js.Unsafe.obj [||] in
assert (obj1 <> obj2);
assert (not (obj1 <> obj1));
()
let%expect_test "poly compare" =
let obj1 = Js.Unsafe.obj [| "a", Js.Unsafe.inject 0 |] in
let obj2 = Js.Unsafe.obj [| "a", Js.Unsafe.inject 0 |] in
(match List.sort compare [ obj1; obj1 ] with
| [ a; b ] ->
if a == obj1 && b == obj2
then print_endline "preserve"
else print_endline "not preserve"
| _ -> assert false);
[%expect {| not preserve |}];
(match List.sort compare [ obj2; obj1 ] with
| [ a; b ] ->
if a == obj2 && b == obj1
then print_endline "preserve"
else print_endline "not preserve"
| _ -> assert false);
[%expect {| not preserve |}]
type pack = Pack : 'a -> pack
let%expect_test "number comparison" =
assert (Pack 2 = Pack 2.);
assert (Pack (Js.Unsafe.js_expr "Number(2)") = Pack 2.);
assert (Pack (Js.Unsafe.js_expr "new Number(2)") = Pack 2.);
assert (Pack 2 <> Pack 2.1);
assert (Pack (Js.Unsafe.js_expr "Number(2.1)") <> Pack 2.);
assert (Pack (Js.Unsafe.js_expr "new Number(2.1)") <> Pack 2.);
assert (
Pack (Js.Unsafe.js_expr "new Number(2.1)")
= Pack (Js.Unsafe.js_expr "new Number(2.1)"))
let js_string_enabled = Js.typeof (Obj.magic "") == Js.string "string"
let%expect_test "string comparison" =
assert (Pack (Js.Unsafe.js_expr "String(2)") = Pack (Js.string "2"));
assert (Pack (Js.Unsafe.js_expr "String('abc')") = Pack (Js.string "abc"));
assert (
js_string_enabled
= (Pack (Js.Unsafe.js_expr "new String('abc')") <> Pack (Js.string "abc")));
assert (Pack (Js.Unsafe.js_expr "new String('abcሴ')") = Pack (Js.string "abcሴ"));
assert (Pack (Js.Unsafe.js_expr "String(1)") <> Pack (Js.string "2"));
assert (Pack (Js.Unsafe.js_expr "String('abcd')") <> Pack (Js.string "abc"));
assert (Pack (Js.Unsafe.js_expr "new String('abcd')") <> Pack (Js.string "abc"));
assert (
Pack (Js.Unsafe.js_expr "new String('abcd')")
= Pack (Js.Unsafe.js_expr "new String('abcd')"))
let%expect_test "symbol comparison" =
let s1 = Pack (Js.Unsafe.js_expr "Symbol('2')") in
let s2 = Pack (Js.Unsafe.js_expr "Symbol('2')") in
assert (s1 <> s2);
assert (s1 = s1);
assert (compare s1 s1 = 0);
assert (compare s1 s2 = 1);
assert (compare s2 s1 = 1)
let%expect_test "object comparison" =
let s1 = Pack (Js.Unsafe.js_expr "{}") in
let s2 = Pack (Js.Unsafe.js_expr "{}") in
assert (s1 <> s2);
assert (s1 = s1);
assert (compare s1 s1 = 0);
assert (compare s1 s2 = 1);
assert (compare s2 s1 = 1)
let%expect_test "poly compare" =
let l =
[ Pack (object end)
; Pack 0
; Pack (Some "")
; Pack None
; Pack (Js.Unsafe.obj [| "a", Js.Unsafe.inject 0 |])
; Pack (Js.Unsafe.obj [| "a", Js.Unsafe.inject 0 |])
; Pack Js.undefined
; Pack Js.null
]
|> List.mapi (fun i x -> i, x)
in
let l' = List.sort (fun (_, a) (_, b) -> compare a b) l in
List.iter (fun (i, _) -> Printf.printf "%d\n" i) l';
print_endline "";
[%expect {|
1
3
2
0
6
7
5
4 |}];
let l' = List.sort (fun (_, a) (_, b) -> compare a b) (List.rev l) in
let l'' = List.sort (fun (_, a) (_, b) -> compare a b) (List.rev l') in
List.iter (fun (i, _) -> Printf.printf "%d\n" i) l';
print_endline "";
[%expect {|
3
1
2
0
4
5
7
6 |}];
List.iter (fun (i, _) -> Printf.printf "%d\n" i) l'';
print_endline "";
[%expect {|
1
3
2
0
4
5
6
7 |}]
| (* Js_of_ocaml tests
* http://www.ocsigen.org/js_of_ocaml/
* Copyright (C) 2019 Hugo Heuzard
*
* 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.
*) |
maps_string.mli |
(* This file is free software, part of dolmen. See file "LICENSE" for more information *)
include Dolmen_intf.Map.S with type key := string
| |
client_proto_contracts.mli | open Protocol
open Alpha_context
open Clic
module RawContractAlias : Client_aliases.Alias with type t = Contract.t
module ContractAlias : sig
val get_contract :
#Client_context.wallet -> string -> (string * Contract.t) tzresult Lwt.t
val alias_param :
?name:string ->
?desc:string ->
('a, (#Client_context.wallet as 'wallet)) params ->
(Lwt_io.file_name * Contract.t -> 'a, 'wallet) params
val destination_param :
?name:string ->
?desc:string ->
('a, (#Client_context.wallet as 'wallet)) params ->
(Lwt_io.file_name * Contract.t -> 'a, 'wallet) params
val rev_find :
#Client_context.wallet -> Contract.t -> string option tzresult Lwt.t
val name : #Client_context.wallet -> Contract.t -> string tzresult Lwt.t
val autocomplete : #Client_context.wallet -> string list tzresult Lwt.t
end
val list_contracts :
#Client_context.wallet ->
(string * string * RawContractAlias.t) list tzresult Lwt.t
val get_manager :
#Alpha_client_context.rpc_context ->
chain:Shell_services.chain ->
block:Shell_services.block ->
Contract.t ->
public_key_hash tzresult Lwt.t
val get_delegate :
#Alpha_client_context.rpc_context ->
chain:Shell_services.chain ->
block:Shell_services.block ->
Contract.t ->
public_key_hash option tzresult Lwt.t
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
ode.mli |
(** {2:odelib Ode library} *)
(** [step (module Solver) f dt y0 t0 ()] takes one step with the evolution
function f(y,t) starting at time t0 with a step size of dt and returns
output of type step_output.
*)
val step
: (module Types.Solver
with type f = 'a
and type solve_output = 'b
and type state = 'c
and type step_output = 'd)
-> 'a
-> dt:float
-> 'c
-> float
-> 'd
(** [odeint (module Solver) f y0 timespec ()] numerically integrates
an initial value problem for a system of ODEs given an initial value:
∂ₜ y = f(y, t)
y(t₀) = y₀
Here t is a one-dimensional independent variable (time), y(t) is an
n-dimensional vector-valued function (state), and the n-dimensional
vector-valued function f(y, t) determines the differential equations.
The goal is to find y(t) approximately satisfying the differential
equations, given an initial value y(t₀)=y₀. The time t₀ is passed as
part of the timespec, that includes also the final integration time
and a time step. Refer to {!Owl_ode_base.Types.tspec} for further
information.
The solver has to be passed as a first-class module and have a common
type, {!Owl_ode_base.Types.Solver}. This is useful to write new custom
solvers or extend and customise the provided ones.
Refer to the documentation of the {!Owl_ode_base.Types.Solver} type
for further information.
*)
val odeint
: (module Types.Solver
with type f = 'a
and type solve_output = 'b
and type state = 'c
and type step_output = 'd)
-> 'a
-> 'c
-> Types.tspec
-> unit
-> 'b
| (*
* OWL - OCaml Scientific and Engineering Computing
* OWL-ODE - Ordinary Differential Equation Solvers
*
* Copyright (c) 2019 Ta-Chu Kao <[email protected]>
* Copyright (c) 2019 Marcello Seri <[email protected]>
*) |
static.ml |
module Formats = Dream_pure.Formats
module Message = Dream_pure.Message
module Method = Dream_pure.Method
module Router = Dream__server.Router
module Stream = Dream_pure.Stream
(* TODO Not at all efficient; can at least stream the file, maybe even cache. *)
(* TODO Also mind newlines on Windows. *)
(* TODO NOTE Using Lwt_io because it has a nice "read the whole thing"
function. *)
let mime_lookup filename =
let content_type =
match Magic_mime.lookup filename with
| "text/html" -> Formats.text_html
| content_type -> content_type
in
["Content-Type", content_type]
let from_filesystem local_root path _ =
let file = Filename.concat local_root path in
Lwt.catch
(fun () ->
Lwt_io.(with_file ~mode:Input file) (fun channel ->
let%lwt content = Lwt_io.read channel in
Message.response
~headers:(mime_lookup path) (Stream.string content) Stream.null
|> Lwt.return))
(fun _exn ->
Message.response ~status:`Not_Found Stream.empty Stream.null
|> Lwt.return)
(* TODO Add ETag handling. *)
(* TODO Add Content-Length handling? *)
(* TODO Support HEAD requests? *)
(* TODO On Windows, should we also check for \ and drive letters? *)
(* TODO Not an efficient implementation at the moment. *)
let validate_path request =
let path = Router.path request in
let has_slash component = String.contains component '/' in
let has_backslash component = String.contains component '\\' in
let has_slash = List.exists has_slash path in
let has_backslash = List.exists has_backslash path in
let has_dot = List.exists ((=) Filename.current_dir_name) path in
let has_dotdot = List.exists ((=) Filename.parent_dir_name) path in
let has_empty = List.exists ((=) "") path in
let is_empty = path = [] in
if has_slash ||
has_backslash ||
has_dot ||
has_dotdot ||
has_empty ||
is_empty then
None
else
let path = String.concat Filename.dir_sep path in
if Filename.is_relative path then
Some path
else
None
let static ?(loader = from_filesystem) local_root = fun request ->
if not @@ Method.methods_equal (Message.method_ request) `GET then
Message.response ~status:`Not_Found Stream.empty Stream.null
|> Lwt.return
else
match validate_path request with
| None ->
Message.response ~status:`Not_Found Stream.empty Stream.null
|> Lwt.return
| Some path ->
let%lwt response = loader local_root path request in
if not (Message.has_header response "Content-Type") then begin
match Message.status response with
| `OK
| `Non_Authoritative_Information
| `No_Content
| `Reset_Content
| `Partial_Content ->
Message.add_header response "Content-Type" (Magic_mime.lookup path)
| _ ->
()
end;
Lwt.return response
| (* This file is part of Dream, released under the MIT license. See LICENSE.md
for details, or visit https://github.com/aantron/dream.
Copyright 2021 Anton Bachin *) |
dune |
(library
(name hello_world)
(c_names file.xx))
| |
pr5757.ml | (* TEST *)
Random.init 3;;
for i = 0 to 100_000 do
ignore (Bytes.create (Random.int 1_000_000))
done;;
Printf.printf "hello world\n";;
| (* TEST *)
|
parser.ml |
open! Core
include Parser_intf
(* Stores thread kernel objects as a tuple of (pid, tid) *)
module Thread_kernel_object = struct
include Tuple.Make (Int) (Int)
include Tuple.Hashable (Int) (Int)
end
module String_index = Int
module Thread_index = Int
module Event_arg = struct
type value =
| String of String_index.t
| Int of int
| Int64 of int64
| Pointer of Int64.Hex.t
| Float of float
[@@deriving sexp_of, compare]
type t = String_index.t * value [@@deriving sexp_of, compare]
end
module Event = struct
type t =
{ timestamp : Time_ns.Span.t
; thread : Thread_index.t
; category : String_index.t
; name : String_index.t
; arguments : Event_arg.t list
; event_type : Event_type.t
}
[@@deriving sexp_of, compare]
end
module Record = struct
type t =
| Event of Event.t
| Interned_string of
{ index : String_index.t
; value : string
}
| Interned_thread of
{ index : Thread_index.t
; value : Thread.t
}
| Process_name_change of
{ name : String_index.t
; pid : int
}
| Thread_name_change of
{ name : String_index.t
; pid : int
; tid : int
}
| Tick_initialization of
{ ticks_per_second : int
; base_time : Time_ns.Option.t
}
[@@deriving sexp_of, compare]
end
type t =
{ iobuf : (read, Iobuf.seek) Iobuf.t
; cur_record : (read, Iobuf.seek) Iobuf.t
; mutable current_provider : int option
; provider_name_by_id : string Int.Table.t
; mutable ticks_per_second : int
; mutable base_tick : int
; mutable base_time : Time_ns.Option.t
; thread_table : Thread.t Int.Table.t
; string_table : string Int.Table.t
; process_names : string Int.Table.t
; thread_names : string Thread_kernel_object.Table.t
; warnings : Warnings.t
}
[@@deriving fields]
let create iobuf =
{ iobuf
; cur_record = Iobuf.create ~len:0
; current_provider = None
; provider_name_by_id = Int.Table.create ()
; ticks_per_second = 1_000_000_000
; base_tick = 0
; base_time = Time_ns.Option.none
; thread_table = Int.Table.create ()
; string_table = Int.Table.create ()
; process_names = Int.Table.create ()
; thread_names = Thread_kernel_object.Table.create ()
; warnings = { num_unparsed_records = 0; num_unparsed_args = 0 }
}
;;
exception Ticks_too_large
exception Invalid_tick_rate
exception Invalid_record
exception String_not_found
exception Thread_not_found
let consume_int32_exn iobuf =
if Iobuf.length iobuf < 4 then raise Invalid_record else Iobuf.Consume.int32_le iobuf
;;
(* Many things don't use the most significant bit of their word so we can safely use a
normal OCaml 63 bit int to parse them. *)
let consume_int64_trunc_exn iobuf =
if Iobuf.length iobuf < 8
then raise Invalid_record
else Iobuf.Consume.int64_le_trunc iobuf
;;
let consume_int64_t_exn iobuf =
if Iobuf.length iobuf < 8 then raise Invalid_record else Iobuf.Consume.int64_t_le iobuf
;;
let consume_tail_padded_string_exn iobuf ~len =
if Iobuf.length iobuf < len
then raise Invalid_record
else Iobuf.Consume.tail_padded_fixed_string ~padding:Char.min_value ~len iobuf
;;
let advance_iobuf_exn iobuf ~by:len =
if Iobuf.length iobuf < len then raise Invalid_record else Iobuf.advance iobuf len
;;
let[@inline] extract_field word ~pos ~size = (word lsr pos) land ((1 lsl size) - 1)
(* Because the format guarantees aligned 64-bit words, some things need to be padded to
8 bytes. This is an efficient expression for doing that. *)
let padding_to_word x = -x land (8 - 1)
(* Method for converting a tick count to nanoseconds taken from the Perfetto source code.
Raises [Ticks_too_large] if the result doesn't fit in an int63.
This implements a kind of elementary school long multiplication to handle larger
values without overflowing in the intermediate steps or losing precision. We do
this complicated method instead of just using floats because it's nice if our
tools don't lose precision if a ticks value is an absolute [Time_ns.t], even if
those traces won't work perfectly in the Perfetto web UI. *)
let ticks_to_ns ticks ~ticks_per_sec =
let ticks_hi = ticks lsr 32 in
let ticks_lo = ticks land ((1 lsl 32) - 1) in
let ns_per_sec = 1_000_000_000 in
(* Calculating [result_hi] can overflow, so we check for that case. *)
let result_hi = ticks_hi * ((ns_per_sec lsl 32) / ticks_per_sec) in
if ticks_hi <> 0 && result_hi / ticks_hi <> (ns_per_sec lsl 32) / ticks_per_sec
then raise Ticks_too_large;
(* Calculating [result_lo] can't overflow since [ticks_lo * ns_per_sec] is less than
2^62. *)
let result_lo = ticks_lo * ns_per_sec / ticks_per_sec in
(* Adding [result_lo + result_hi] can overflow. *)
let result = result_lo + result_hi in
if result < 0 then raise Ticks_too_large;
result
;;
let event_tick_to_span t tick =
let ticks_elapsed = tick - t.base_tick in
let ticks_ns = ticks_to_ns ticks_elapsed ~ticks_per_sec:t.ticks_per_second in
Time_ns.Span.of_int_ns ticks_ns
;;
let lookup_string_exn t ~index =
if index = 0
then ""
else (
try Int.Table.find_exn t.string_table index with
| _ -> raise String_not_found)
;;
let lookup_thread_exn t ~index =
try Int.Table.find_exn t.thread_table index with
| _ -> raise Thread_not_found
;;
(* Extracts a 16-bit string index. Will raise if the string index isn't in the string
table or if attempting to read an inline string reference.
Since inline string references have their highest bit set to 1 and use the lower 15
bits to indicate the length of the string stream, the value will always be >= 32768.
Values >= 32768 will never be in the string table because in [parse_string_record],
we only write strings to indices [1, 32767]. *)
let[@inline] extract_string_index t word ~pos =
let index = extract_field word ~pos ~size:16 in
(* raise an exception if the string is not in the string table *)
lookup_string_exn t ~index |> (ignore : string -> unit);
index
;;
(* Extracts an 8-bit thread index. Will raise if the thread index isn't in the
thread table. *)
let[@inline] extract_thread_index t word ~pos =
let index = extract_field word ~pos ~size:8 in
(* raise an exception if the thread is not in the thread table *)
lookup_thread_exn t ~index |> (ignore : Thread.t -> unit);
index
;;
let[@inline] consume_tick t =
let ticks = consume_int64_trunc_exn t.cur_record in
(* We raise [Ticks_too_large] in case a bug (e.g. overflow) caused the ticks value to
become negative when converted to a 63-bit OCaml int. *)
if ticks < 0 then raise Ticks_too_large;
ticks
;;
let parse_metadata_record t =
let header = consume_int64_trunc_exn t.cur_record in
let mtype = extract_field header ~pos:16 ~size:4 in
match mtype with
| 1 (* Provider info metadata *) ->
let provider_id = extract_field header ~pos:20 ~size:32 in
let name_len = extract_field header ~pos:52 ~size:8 in
let padding = padding_to_word name_len in
let provider_name =
consume_tail_padded_string_exn t.cur_record ~len:(name_len + padding)
in
Int.Table.set t.provider_name_by_id ~key:provider_id ~data:provider_name;
t.current_provider <- Some provider_id
| 2 (* Provider section metadata *) ->
let provider_id = extract_field header ~pos:20 ~size:32 in
t.current_provider <- Some provider_id
| 4 (* Trace info metadata *) ->
let trace_info_type = extract_field header ~pos:20 ~size:4 in
let trace_info = extract_field header ~pos:24 ~size:32 in
(* Check for magic number record *)
if not (trace_info_type = 0 && trace_info = 0x16547846)
then t.warnings.num_unparsed_records <- t.warnings.num_unparsed_records + 1
| _ ->
(* Unsupported metadata type *)
t.warnings.num_unparsed_records <- t.warnings.num_unparsed_records + 1
;;
let parse_initialization_record t =
let header = consume_int64_trunc_exn t.cur_record in
let rsize = extract_field header ~pos:4 ~size:12 in
let ticks_per_second = consume_int64_trunc_exn t.cur_record in
if ticks_per_second <= 0 then raise Invalid_tick_rate;
t.ticks_per_second <- ticks_per_second;
(* By default, initialization records have size = 2. This checks for the extended
initialization record that has two extra words. *)
if rsize = 4
then (
let base_tick = consume_tick t in
let base_time_in_ns = consume_int64_trunc_exn t.cur_record in
let base_time =
Time_ns.of_int_ns_since_epoch base_time_in_ns |> Time_ns.Option.some
in
t.base_tick <- base_tick;
t.base_time <- base_time;
Record.Tick_initialization { ticks_per_second; base_time })
else Record.Tick_initialization { ticks_per_second; base_time = Time_ns.Option.none }
;;
(* Reads a zero-padded string and stores it at the associated 15-bit index (from 1 to
32767) in the string table. *)
let parse_string_record t =
let header = consume_int64_trunc_exn t.cur_record in
let string_index = extract_field header ~pos:16 ~size:15 in
(* Index 0 is used to denote the empty string. The spec mandates that string records
which attempt to define it anyways be ignored. *)
if string_index = 0
then None
else (
let str_len = extract_field header ~pos:32 ~size:15 in
let padding = padding_to_word str_len in
let interned_string =
consume_tail_padded_string_exn t.cur_record ~len:(str_len + padding)
in
Int.Table.set t.string_table ~key:string_index ~data:interned_string;
Some (Record.Interned_string { index = string_index; value = interned_string }))
;;
(* Reads a PID and TID and stores them at the associated 8-bit index (from 1 to 255) in
the thread table. *)
let parse_thread_record t =
let header = consume_int64_trunc_exn t.cur_record in
let thread_index = extract_field header ~pos:16 ~size:8 in
(* Index 0 is reserved for inline thread refs, sets to it must be ignored. *)
if thread_index = 0
then None
else (
let process_koid = consume_int64_trunc_exn t.cur_record in
let thread_koid = consume_int64_trunc_exn t.cur_record in
let thread =
{ Thread.pid = process_koid
; tid = thread_koid
; process_name = Int.Table.find t.process_names process_koid
; thread_name =
Thread_kernel_object.Table.find t.thread_names (process_koid, thread_koid)
}
in
Int.Table.set t.thread_table ~key:thread_index ~data:thread;
Some (Record.Interned_thread { index = thread_index; value = thread }))
;;
let rec parse_args ?(args = []) t ~num_args =
if num_args = 0
then List.rev args
else (
let header_low_word = consume_int32_exn t.cur_record in
let arg_type = extract_field header_low_word ~pos:0 ~size:4 in
let rsize = extract_field header_low_word ~pos:4 ~size:12 in
let arg_name = extract_string_index t header_low_word ~pos:16 in
(* The Fuchsia spec says the upper 32-bits of the header are reserved for future
extensions, and should just be ignored if they aren't used. *)
let header_high_word = consume_int32_exn t.cur_record in
let (args : Event_arg.t list) =
match arg_type with
(* arg_type 0 is a null argument with no value. We never write these so we just
collapse them into an Int with value zero. *)
| 0 | 1 -> (arg_name, Int header_high_word) :: args
| 3 ->
let value = consume_int64_t_exn t.cur_record in
let arg =
match Int64.to_int value with
| Some value -> Event_arg.Int value
| None -> Int64 value
in
(arg_name, arg) :: args
| 5 ->
let value_as_int64 = consume_int64_t_exn t.cur_record in
let value = Int64.float_of_bits value_as_int64 in
(arg_name, Float value) :: args
| 6 ->
let value = extract_string_index t header_high_word ~pos:0 in
(arg_name, String value) :: args
| 7 ->
let value = consume_int64_t_exn t.cur_record in
(arg_name, Pointer value) :: args
| _ ->
(* Advance [rsize - 1] words to the next argument after reading the header word. *)
advance_iobuf_exn t.cur_record ~by:(8 * (rsize - 1));
(* Unsupported argument types: unsigned integers, pointers, kernel IDs *)
t.warnings.num_unparsed_args <- t.warnings.num_unparsed_args + 1;
args
in
parse_args t ~num_args:(num_args - 1) ~args)
;;
let parse_kernel_object_record t =
let header = consume_int64_trunc_exn t.cur_record in
let obj_type = extract_field header ~pos:16 ~size:8 in
let name = extract_string_index t header ~pos:24 in
let name_str = lookup_string_exn t ~index:name in
let num_args = extract_field header ~pos:40 ~size:4 in
match obj_type with
| 1 (* process *) ->
let koid = consume_int64_trunc_exn t.cur_record in
Int.Table.set t.process_names ~key:koid ~data:name_str;
(* Update the name of any matching process in the process table. *)
Int.Table.iter t.thread_table ~f:(fun thread ->
if thread.pid = koid then thread.process_name <- Some name_str);
if num_args > 0
then t.warnings.num_unparsed_args <- t.warnings.num_unparsed_args + num_args;
Some (Record.Process_name_change { name; pid = koid })
| 2 (* thread *) ->
let koid = consume_int64_trunc_exn t.cur_record in
if num_args > 0
then (
(* We expect the first arg to be a koid argument named "process". *)
let arg_header = consume_int32_exn t.cur_record in
let arg_type = extract_field arg_header ~pos:0 ~size:4 in
let arg_name_ref = extract_string_index t arg_header ~pos:16 in
let arg_name = lookup_string_exn t ~index:arg_name_ref in
if arg_type = 8 && String.( = ) arg_name "process"
then (
consume_int32_exn t.cur_record |> (ignore : int -> unit);
let process_koid = consume_int64_trunc_exn t.cur_record in
Thread_kernel_object.Table.set
t.thread_names
~key:(process_koid, koid)
~data:name_str;
(* Update the name of any matching thread in the thread table. *)
Int.Table.iter t.thread_table ~f:(fun thread ->
if thread.pid = process_koid && thread.tid = koid
then thread.thread_name <- Some name_str);
(* Mark any remaining arguments as unparsed. *)
t.warnings.num_unparsed_args <- t.warnings.num_unparsed_args + (num_args - 1);
Some (Record.Thread_name_change { name; pid = process_koid; tid = koid }))
else (
t.warnings.num_unparsed_records <- t.warnings.num_unparsed_records + 1;
None))
else (
t.warnings.num_unparsed_records <- t.warnings.num_unparsed_records + 1;
None)
| _ ->
(* The record contains an unsupported kernel object type. *)
t.warnings.num_unparsed_records <- t.warnings.num_unparsed_records + 1;
None
;;
let parse_event_record t =
(* Parse the header in two 32-bit pieces so that we can avoid allocating despite it
being possible the most significant bit is one. *)
let header_lower = consume_int32_exn t.cur_record in
let ev_type = extract_field header_lower ~pos:16 ~size:4 in
let num_args = extract_field header_lower ~pos:20 ~size:4 in
let thread = extract_thread_index t header_lower ~pos:24 in
let header_upper = consume_int32_exn t.cur_record in
let category = extract_string_index t header_upper ~pos:0 in
let name = extract_string_index t header_upper ~pos:16 in
let timestamp_tick = consume_tick t in
let args = parse_args t ~num_args in
let event_type : Event_type.t option =
match ev_type with
| 0 -> Some Instant
| 1 ->
let counter_id = consume_int64_trunc_exn t.cur_record in
Some (Counter { id = counter_id })
| 2 -> Some Duration_begin
| 3 -> Some Duration_end
| 4 ->
let end_time_tick = consume_int64_trunc_exn t.cur_record in
Some (Duration_complete { end_time = event_tick_to_span t end_time_tick })
| 8 ->
let flow_correlation_id = consume_int64_trunc_exn t.cur_record in
Some (Flow_begin { flow_correlation_id })
| 9 ->
let flow_correlation_id = consume_int64_trunc_exn t.cur_record in
Some (Flow_step { flow_correlation_id })
| 10 ->
let flow_correlation_id = consume_int64_trunc_exn t.cur_record in
Some (Flow_end { flow_correlation_id })
(* Unsupported event type: Async begin, instant or end *)
| _ -> None
in
match event_type with
| Some event_type ->
let timestamp = event_tick_to_span t timestamp_tick in
let event =
{ Event.timestamp; thread; category; name; arguments = args; event_type }
in
Some (Record.Event event)
| None ->
t.warnings.num_unparsed_records <- t.warnings.num_unparsed_records + 1;
None
;;
(* This function advances through the trace until it finds a Fuschia record matching one
of the records types defined in [Record.t]. *)
let rec parse_until_next_external_record t =
if Iobuf.length t.iobuf < 8 then raise End_of_file;
let header = Iobuf.Peek.int64_le_trunc t.iobuf ~pos:0 in
let rtype = extract_field header ~pos:0 ~size:4 in
let rsize =
(* large blob records use a larger length field *)
if rtype = 15
then extract_field header ~pos:4 ~size:32
else extract_field header ~pos:4 ~size:12
in
let rlen = 8 * rsize in
(* We raise an exception if the current record is split across two iobufs. Subsequent
calls to parse will attempt to parse this record again. *)
if Iobuf.length t.iobuf < rlen then raise End_of_file;
Iobuf.Expert.set_bounds_and_buffer_sub ~pos:0 ~len:rlen ~src:t.iobuf ~dst:t.cur_record;
(* Because this happens before parsing, errors thrown when parsing will cause subsequent
calls to parse to begin with the next record, allowing skipping invalid records. *)
Iobuf.advance t.iobuf rlen;
let record =
match rtype with
| 0 (* Metadata record *) ->
parse_metadata_record t;
None
| 1 (* Initialization record *) -> Some (parse_initialization_record t)
| 2 (* String record *) -> parse_string_record t
| 3 (* Thread record *) -> parse_thread_record t
| 4 (* Event record *) -> parse_event_record t
| 7 (* Kernel object record *) -> parse_kernel_object_record t
| _ (* Unsupported record type *) ->
t.warnings.num_unparsed_records <- t.warnings.num_unparsed_records + 1;
None
in
match record with
| Some record -> record
| None -> parse_until_next_external_record t
;;
let parse_next t =
try
let record = parse_until_next_external_record t in
Result.return record
with
| End_of_file -> Result.fail Parse_error.No_more_words
| Ticks_too_large ->
t.warnings.num_unparsed_records <- t.warnings.num_unparsed_records + 1;
Result.fail Parse_error.Timestamp_too_large
| Invalid_tick_rate ->
t.warnings.num_unparsed_records <- t.warnings.num_unparsed_records + 1;
Result.fail Parse_error.Invalid_tick_initialization
| Invalid_record ->
t.warnings.num_unparsed_records <- t.warnings.num_unparsed_records + 1;
Result.fail Parse_error.Invalid_size_on_record
| String_not_found ->
t.warnings.num_unparsed_records <- t.warnings.num_unparsed_records + 1;
Result.fail Parse_error.Invalid_string_ref
| Thread_not_found ->
t.warnings.num_unparsed_records <- t.warnings.num_unparsed_records + 1;
Result.fail Parse_error.Invalid_thread_ref
;;
| |
t-ci_series.c |
#include "acb_hypgeom.h"
int main()
{
slong iter;
flint_rand_t state;
flint_printf("ci_series....");
fflush(stdout);
flint_randinit(state);
for (iter = 0; iter < 200 * arb_test_multiplier(); iter++)
{
slong m, n1, n2, n3, bits1, bits2, bits3;
acb_poly_t S, A, B, C, T, U;
bits1 = 2 + n_randint(state, 200);
bits2 = 2 + n_randint(state, 200);
bits3 = 2 + n_randint(state, 200);
m = 1 + n_randint(state, 10);
n1 = 1 + n_randint(state, 10);
n2 = 1 + n_randint(state, 10);
n3 = FLINT_MIN(n1, n2);
acb_poly_init(S);
acb_poly_init(A);
acb_poly_init(B);
acb_poly_init(C);
acb_poly_init(T);
acb_poly_init(U);
acb_poly_randtest(S, state, m, bits1, 3);
acb_poly_randtest(A, state, m, bits1, 3);
acb_poly_randtest(B, state, m, bits1, 3);
acb_hypgeom_ci_series(A, S, n1, bits2);
acb_hypgeom_ci_series(B, S, n2, bits3);
acb_poly_set(C, A);
acb_poly_truncate(C, n3);
acb_poly_truncate(B, n3);
/* [Ci(h(x))]' h(x) = cos(h(x)) h'(x) */
acb_poly_cos_series(U, S, n3, bits2);
acb_poly_derivative(T, S, bits2);
acb_poly_mullow(U, U, T, FLINT_MAX(0, n3 - 1), bits2);
acb_poly_derivative(T, A, bits2);
acb_poly_mullow(T, T, S, FLINT_MAX(0, n3 - 1), bits2);
if (!acb_poly_overlaps(B, C) || !acb_poly_overlaps(T, U))
{
flint_printf("FAIL\n\n");
flint_printf("S = "); acb_poly_printd(S, 15); flint_printf("\n\n");
flint_printf("A = "); acb_poly_printd(A, 15); flint_printf("\n\n");
flint_printf("B = "); acb_poly_printd(B, 15); flint_printf("\n\n");
flint_printf("T = "); acb_poly_printd(T, 15); flint_printf("\n\n");
flint_printf("U = "); acb_poly_printd(U, 15); flint_printf("\n\n");
flint_abort();
}
acb_hypgeom_ci_series(S, S, n1, bits2);
if (!acb_poly_overlaps(A, S))
{
flint_printf("FAIL (aliasing)\n\n");
flint_abort();
}
acb_poly_clear(S);
acb_poly_clear(A);
acb_poly_clear(B);
acb_poly_clear(C);
acb_poly_clear(T);
acb_poly_clear(U);
}
flint_randclear(state);
flint_cleanup();
flint_printf("PASS\n");
return EXIT_SUCCESS;
}
| /*
Copyright (C) 2013 Fredrik Johansson
This file is part of Arb.
Arb is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <http://www.gnu.org/licenses/>.
*/ |
automata.ml |
type sem = [ `Longest | `Shortest | `First ]
type rep_kind = [ `Greedy | `Non_greedy ]
type mark = int
type idx = int
type expr = { id : int; def : def }
and def =
Cst of Cset.t
| Alt of expr list
| Seq of sem * expr * expr
| Eps
| Rep of rep_kind * sem * expr
| Mark of int
| Erase of int * int
| Before of Category.t
| After of Category.t
| Pmark of Pmark.t
let hash_combine h accu = accu * 65599 + h
module Marks = struct
type t =
{ marks : (int * int) list
; pmarks : Pmark.Set.t }
let empty = { marks = [] ; pmarks = Pmark.Set.empty }
let rec merge_marks_offset old = function
| [] ->
old
| (i, v) :: rem ->
let nw' = merge_marks_offset (List.remove_assq i old) rem in
if v = -2 then
nw'
else
(i, v) :: nw'
let merge old nw =
{ marks = merge_marks_offset old.marks nw.marks
; pmarks = Pmark.Set.union old.pmarks nw.pmarks }
let rec hash_marks_offset l accu =
match l with
[] -> accu
| (a, i) :: r -> hash_marks_offset r (hash_combine a (hash_combine i accu))
let hash m accu =
hash_marks_offset m.marks (hash_combine (Hashtbl.hash m.pmarks) accu)
let rec marks_set_idx idx = function
| (a, -1) :: rem ->
(a, idx) :: marks_set_idx idx rem
| marks ->
marks
let marks_set_idx marks idx =
{ marks with marks = marks_set_idx idx marks.marks }
let pp_marks ch t =
match t.marks with
| [] ->
()
| (a, i) :: r ->
Format.fprintf ch "%d-%d" a i;
List.iter (fun (a, i) -> Format.fprintf ch " %d-%d" a i) r
end
(****)
let pp_sem ch k =
Format.pp_print_string ch
(match k with
`Shortest -> "short"
| `Longest -> "long"
| `First -> "first")
let pp_rep_kind fmt = function
| `Greedy -> Format.pp_print_string fmt "Greedy"
| `Non_greedy -> Format.pp_print_string fmt "Non_greedy"
let rec pp ch e =
let open Fmt in
match e.def with
Cst l ->
sexp ch "cst" Cset.pp l;
| Alt l ->
sexp ch "alt" (list pp) l
| Seq (k, e, e') ->
sexp ch "seq" (triple pp_sem pp pp) (k, e, e')
| Eps ->
str ch "eps"
| Rep (_rk, k, e) ->
sexp ch "rep" (pair pp_sem pp) (k, e)
| Mark i ->
sexp ch "mark" int i
| Pmark i ->
sexp ch "pmark" int (i :> int)
| Erase (b, e) ->
sexp ch "erase" (pair int int) (b, e)
| Before c ->
sexp ch "before" Category.pp c
| After c ->
sexp ch "after" Category.pp c
(****)
let rec first f = function
| [] ->
None
| x :: r ->
match f x with
None -> first f r
| Some _ as res -> res
(****)
type ids = int ref
let create_ids () = ref 0
let eps_expr = { id = 0; def = Eps }
let mk_expr ids def =
incr ids;
{ id = !ids; def = def }
let empty ids = mk_expr ids (Alt [])
let cst ids s =
if Cset.is_empty s
then empty ids
else mk_expr ids (Cst s)
let alt ids = function
| [] -> empty ids
| [c] -> c
| l -> mk_expr ids (Alt l)
let seq ids kind x y =
match x.def, y.def with
Alt [], _ -> x
| _, Alt [] -> y
| Eps, _ -> y
| _, Eps when kind = `First -> x
| _ -> mk_expr ids (Seq (kind, x, y))
let is_eps expr =
match expr.def with
| Eps -> true
| _ -> false
let eps ids = mk_expr ids Eps
let rep ids kind sem x = mk_expr ids (Rep (kind, sem, x))
let mark ids m = mk_expr ids (Mark m)
let pmark ids i = mk_expr ids (Pmark i)
let erase ids m m' = mk_expr ids (Erase (m, m'))
let before ids c = mk_expr ids (Before c)
let after ids c = mk_expr ids (After c)
(****)
let rec rename ids x =
match x.def with
Cst _ | Eps | Mark _ | Pmark _ | Erase _ | Before _ | After _ ->
mk_expr ids x.def
| Alt l ->
mk_expr ids (Alt (List.map (rename ids) l))
| Seq (k, y, z) ->
mk_expr ids (Seq (k, rename ids y, rename ids z))
| Rep (g, k, y) ->
mk_expr ids (Rep (g, k, rename ids y))
(****)
type hash = int
type mark_infos = int array
type status = Failed | Match of mark_infos * Pmark.Set.t | Running
module E = struct
type t =
| TSeq of t list * expr * sem
| TExp of Marks.t * expr
| TMatch of Marks.t
let rec equal l1 l2 =
match l1, l2 with
| [], [] ->
true
| TSeq (l1', e1, _) :: r1, TSeq (l2', e2, _) :: r2 ->
e1.id = e2.id && equal l1' l2' && equal r1 r2
| TExp (marks1, e1) :: r1, TExp (marks2, e2) :: r2 ->
e1.id = e2.id && marks1 = marks2 && equal r1 r2
| TMatch marks1 :: r1, TMatch marks2 :: r2 ->
marks1 = marks2 && equal r1 r2
| _ ->
false
let rec hash l accu =
match l with
| [] ->
accu
| TSeq (l', e, _) :: r ->
hash r (hash_combine 0x172a1bce (hash_combine e.id (hash l' accu)))
| TExp (marks, e) :: r ->
hash r
(hash_combine 0x2b4c0d77 (hash_combine e.id (Marks.hash marks accu)))
| TMatch marks :: r ->
hash r (hash_combine 0x1c205ad5 (Marks.hash marks accu))
let texp marks x = TExp (marks, x)
let tseq kind x y rem =
match x with
[] -> rem
| [TExp (marks, {def = Eps ; _})] -> TExp (marks, y) :: rem
| _ -> TSeq (x, y, kind) :: rem
let rec print_state_rec ch e y =
match e with
| TMatch marks ->
Format.fprintf ch "@[<2>(Match@ %a)@]" Marks.pp_marks marks
| TSeq (l', x, _kind) ->
Format.fprintf ch "@[<2>(Seq@ ";
print_state_lst ch l' x;
Format.fprintf ch " %a)@]" pp x
| TExp (marks, {def = Eps; _}) ->
Format.fprintf ch "(Exp %d (%a) (eps))" y.id Marks.pp_marks marks
| TExp (marks, x) ->
Format.fprintf ch "(Exp %d (%a) %a)" x.id Marks.pp_marks marks pp x
and print_state_lst ch l y =
match l with
[] ->
Format.fprintf ch "()"
| e :: rem ->
print_state_rec ch e y;
List.iter
(fun e ->
Format.fprintf ch " | ";
print_state_rec ch e y)
rem
let pp ch t = print_state_lst ch [t] { id = 0; def = Eps }
end
module State = struct
type t =
{ idx: idx
; category: Category.t
; desc: E.t list
; mutable status: status option
; hash: hash }
let dummy =
{ idx = -1
; category = Category.dummy
; desc = []
; status = None
; hash = -1 }
let hash idx cat desc =
E.hash desc (hash_combine idx (hash_combine (Category.to_int cat) 0)) land 0x3FFFFFFF
let mk idx cat desc =
{ idx
; category = cat
; desc
; status = None
; hash = hash idx cat desc}
let create cat e = mk 0 cat [E.TExp (Marks.empty, e)]
let equal x y =
(x.hash : int) = y.hash && (x.idx : int) = y.idx &&
Category.equal x.category y.category && E.equal x.desc y.desc
let compare x y =
let c = compare (x.hash : int) y.hash in
if c <> 0 then c else
let c = Category.compare x.category y.category in
if c <> 0 then c else
compare x.desc y.desc
type t' = t
module Table = Hashtbl.Make(
struct
type t = t'
let equal = equal
let hash t = t.hash
end)
end
(**** Find a free index ****)
type working_area = bool array ref
let create_working_area () = ref [| false |]
let index_count w = Array.length !w
let reset_table a = Array.fill a 0 (Array.length a) false
let rec mark_used_indices tbl =
List.iter (function
| E.TSeq (l, _, _) -> mark_used_indices tbl l
| E.TExp (marks, _)
| E.TMatch marks ->
List.iter (fun (_, i) -> if i >= 0 then tbl.(i) <- true)
marks.Marks.marks)
let rec find_free tbl idx len =
if idx = len || not tbl.(idx) then idx else find_free tbl (idx + 1) len
let free_index tbl_ref l =
let tbl = !tbl_ref in
reset_table tbl;
mark_used_indices tbl l;
let len = Array.length tbl in
let idx = find_free tbl 0 len in
if idx = len then tbl_ref := Array.make (2 * len) false;
idx
(**** Computation of the next state ****)
let remove_matches = List.filter (function E.TMatch _ -> false | _ -> true)
let rec split_at_match_rec l' = function
| [] -> assert false
| E.TMatch _ :: r -> (List.rev l', remove_matches r)
| x :: r -> split_at_match_rec (x :: l') r
let split_at_match l = split_at_match_rec [] l
let rec remove_duplicates prev l y =
match l with
[] ->
([], prev)
| E.TMatch _ as x :: _ -> (* Truncate after first match *)
([x], prev)
| E.TSeq (l', x, kind) :: r ->
let (l'', prev') = remove_duplicates prev l' x in
let (r', prev'') = remove_duplicates prev' r y in
(E.tseq kind l'' x r', prev'')
| E.TExp (_marks, {def = Eps; _}) as e :: r ->
if List.memq y.id prev then
remove_duplicates prev r y
else
let (r', prev') = remove_duplicates (y.id :: prev) r y in
(e :: r', prev')
| E.TExp (_marks, x) as e :: r ->
if List.memq x.id prev then
remove_duplicates prev r y
else
let (r', prev') = remove_duplicates (x.id :: prev) r y in
(e :: r', prev')
let rec set_idx idx = function
| [] ->
[]
| E.TMatch marks :: r ->
E.TMatch (Marks.marks_set_idx marks idx) :: set_idx idx r
| E.TSeq (l', x, kind) :: r ->
E.TSeq (set_idx idx l', x, kind) :: set_idx idx r
| E.TExp (marks, x) :: r ->
E.TExp ((Marks.marks_set_idx marks idx), x) :: set_idx idx r
let filter_marks b e marks =
{marks with Marks.marks = List.filter (fun (i, _) -> i < b || i > e) marks.Marks.marks }
let rec delta_1 marks c ~next_cat ~prev_cat x rem =
(*Format.eprintf "%d@." x.id;*)
match x.def with
Cst s ->
if Cset.mem c s then E.texp marks eps_expr :: rem else rem
| Alt l ->
delta_2 marks c ~next_cat ~prev_cat l rem
| Seq (kind, y, z) ->
let y' = delta_1 marks c ~next_cat ~prev_cat y [] in
delta_seq c ~next_cat ~prev_cat kind y' z rem
| Rep (rep_kind, kind, y) ->
let y' = delta_1 marks c ~next_cat ~prev_cat y [] in
let (y'', marks') =
match
first
(function E.TMatch marks -> Some marks | _ -> None) y'
with
None -> (y', marks)
| Some marks' -> (remove_matches y', marks')
in
begin match rep_kind with
`Greedy -> E.tseq kind y'' x (E.TMatch marks' :: rem)
| `Non_greedy -> E.TMatch marks :: E.tseq kind y'' x rem
end
| Eps ->
E.TMatch marks :: rem
| Mark i ->
let marks = { marks with Marks.marks = (i, -1) :: List.remove_assq i marks.Marks.marks } in
E.TMatch marks :: rem
| Pmark i ->
let marks = { marks with Marks.pmarks = Pmark.Set.add i marks.Marks.pmarks } in
E.TMatch marks :: rem
| Erase (b, e) ->
E.TMatch (filter_marks b e marks) :: rem
| Before cat'' ->
if Category.intersect next_cat cat'' then E.TMatch marks :: rem else rem
| After cat'' ->
if Category.intersect prev_cat cat'' then E.TMatch marks :: rem else rem
and delta_2 marks c ~next_cat ~prev_cat l rem =
match l with
[] -> rem
| y :: r ->
delta_1 marks c ~next_cat ~prev_cat y
(delta_2 marks c ~next_cat ~prev_cat r rem)
and delta_seq c ~next_cat ~prev_cat kind y z rem =
match
first (function E.TMatch marks -> Some marks | _ -> None) y
with
None ->
E.tseq kind y z rem
| Some marks ->
match kind with
`Longest ->
E.tseq kind (remove_matches y) z
(delta_1 marks c ~next_cat ~prev_cat z rem)
| `Shortest ->
delta_1 marks c ~next_cat ~prev_cat z
(E.tseq kind (remove_matches y) z rem)
| `First ->
let (y', y'') = split_at_match y in
E.tseq kind y' z
(delta_1 marks c ~next_cat ~prev_cat z (E.tseq kind y'' z rem))
let rec delta_3 c ~next_cat ~prev_cat x rem =
match x with
E.TSeq (y, z, kind) ->
let y' = delta_4 c ~next_cat ~prev_cat y [] in
delta_seq c ~next_cat ~prev_cat kind y' z rem
| E.TExp (marks, e) ->
delta_1 marks c ~next_cat ~prev_cat e rem
| E.TMatch _ ->
x :: rem
and delta_4 c ~next_cat ~prev_cat l rem =
match l with
[] -> rem
| y :: r ->
delta_3 c ~next_cat ~prev_cat y
(delta_4 c ~next_cat ~prev_cat r rem)
let delta tbl_ref next_cat char st =
let prev_cat = st.State.category in
let (expr', _) =
remove_duplicates []
(delta_4 char ~next_cat ~prev_cat st.State.desc [])
eps_expr in
let idx = free_index tbl_ref expr' in
let expr'' = set_idx idx expr' in
State.mk idx next_cat expr''
(****)
let rec red_tr = function
| [] | [_] as l ->
l
| ((s1, st1) as tr1) :: ((s2, st2) as tr2) :: rem ->
if State.equal st1 st2 then
red_tr ((Cset.union s1 s2, st1) :: rem)
else
tr1 :: red_tr (tr2 :: rem)
let simpl_tr l =
List.sort
(fun (s1, _) (s2, _) -> compare s1 s2)
(red_tr (List.sort (fun (_, st1) (_, st2) -> State.compare st1 st2) l))
(****)
let prepend_deriv = List.fold_right (fun (s, x) l -> Cset.prepend s x l)
let rec restrict s = function
| [] -> []
| (s', x') :: rem ->
let s'' = Cset.inter s s' in
if Cset.is_empty s''
then restrict s rem
else (s'', x') :: restrict s rem
let rec remove_marks b e rem =
if b > e then rem else remove_marks b (e - 1) ((e, -2) :: rem)
let rec prepend_marks_expr m = function
| E.TSeq (l, e', s) -> E.TSeq (prepend_marks_expr_lst m l, e', s)
| E.TExp (m', e') -> E.TExp (Marks.merge m m', e')
| E.TMatch m' -> E.TMatch (Marks.merge m m')
and prepend_marks_expr_lst m l =
List.map (prepend_marks_expr m) l
let prepend_marks m =
List.map (fun (s, x) -> (s, prepend_marks_expr_lst m x))
let rec deriv_1 all_chars categories marks cat x rem =
match x.def with
| Cst s ->
Cset.prepend s [E.texp marks eps_expr] rem
| Alt l ->
deriv_2 all_chars categories marks cat l rem
| Seq (kind, y, z) ->
let y' = deriv_1 all_chars categories marks cat y [(all_chars, [])] in
deriv_seq all_chars categories cat kind y' z rem
| Rep (rep_kind, kind, y) ->
let y' = deriv_1 all_chars categories marks cat y [(all_chars, [])] in
List.fold_right
(fun (s, z) rem ->
let (z', marks') =
match
first
(function E.TMatch marks -> Some marks | _ -> None)
z
with
None -> (z, marks)
| Some marks' -> (remove_matches z, marks')
in
Cset.prepend s
(match rep_kind with
`Greedy -> E.tseq kind z' x [E.TMatch marks']
| `Non_greedy -> E.TMatch marks :: E.tseq kind z' x [])
rem)
y' rem
| Eps ->
Cset.prepend all_chars [E.TMatch marks] rem
| Mark i ->
Cset.prepend all_chars [E.TMatch {marks with Marks.marks = ((i, -1) :: List.remove_assq i marks.Marks.marks)}] rem
| Pmark _ ->
Cset.prepend all_chars [E.TMatch marks] rem
| Erase (b, e) ->
Cset.prepend all_chars
[E.TMatch {marks with Marks.marks = (remove_marks b e (filter_marks b e marks).Marks.marks)}] rem
| Before cat' ->
Cset.prepend (List.assq cat' categories) [E.TMatch marks] rem
| After cat' ->
if Category.intersect cat cat' then Cset.prepend all_chars [E.TMatch marks] rem else rem
and deriv_2 all_chars categories marks cat l rem =
match l with
[] -> rem
| y :: r -> deriv_1 all_chars categories marks cat y
(deriv_2 all_chars categories marks cat r rem)
and deriv_seq all_chars categories cat kind y z rem =
if
List.exists
(fun (_s, xl) ->
List.exists (function E.TMatch _ -> true | _ -> false) xl)
y
then
let z' = deriv_1 all_chars categories Marks.empty cat z [(all_chars, [])] in
List.fold_right
(fun (s, y) rem ->
match
first (function E.TMatch marks -> Some marks | _ -> None)
y
with
None ->
Cset.prepend s (E.tseq kind y z []) rem
| Some marks ->
let z'' = prepend_marks marks z' in
match kind with
`Longest ->
Cset.prepend s (E.tseq kind (remove_matches y) z []) (
prepend_deriv (restrict s z'') rem)
| `Shortest ->
prepend_deriv (restrict s z'') (
Cset.prepend s (E.tseq kind (remove_matches y) z []) rem)
| `First ->
let (y', y'') = split_at_match y in
Cset.prepend s (E.tseq kind y' z []) (
prepend_deriv (restrict s z'') (
Cset.prepend s (E.tseq kind y'' z []) rem)))
y rem
else
List.fold_right
(fun (s, xl) rem -> Cset.prepend s (E.tseq kind xl z []) rem) y rem
let rec deriv_3 all_chars categories cat x rem =
match x with
E.TSeq (y, z, kind) ->
let y' = deriv_4 all_chars categories cat y [(all_chars, [])] in
deriv_seq all_chars categories cat kind y' z rem
| E.TExp (marks, e) ->
deriv_1 all_chars categories marks cat e rem
| E.TMatch _ ->
Cset.prepend all_chars [x] rem
and deriv_4 all_chars categories cat l rem =
match l with
[] -> rem
| y :: r -> deriv_3 all_chars categories cat y
(deriv_4 all_chars categories cat r rem)
let deriv tbl_ref all_chars categories st =
let der = deriv_4 all_chars categories st.State.category st.State.desc
[(all_chars, [])] in
simpl_tr (
List.fold_right (fun (s, expr) rem ->
let (expr', _) = remove_duplicates [] expr eps_expr in
(*
Format.eprintf "@[<3>@[%a@]: %a / %a@]@." Cset.print s print_state expr print_state expr';
*)
let idx = free_index tbl_ref expr' in
let expr'' = set_idx idx expr' in
List.fold_right (fun (cat', s') rem ->
let s'' = Cset.inter s s' in
if Cset.is_empty s''
then rem
else (s'', State.mk idx cat' expr'') :: rem)
categories rem) der [])
(****)
let flatten_match m =
let ma = List.fold_left (fun ma (i, _) -> max ma i) (-1) m in
let res = Array.make (ma + 1) (-1) in
List.iter (fun (i, v) -> res.(i) <- v) m;
res
let status s =
match s.State.status with
Some st ->
st
| None ->
let st =
match s.State.desc with
[] -> Failed
| E.TMatch m :: _ -> Match (flatten_match m.Marks.marks, m.Marks.pmarks)
| _ -> Running
in
s.State.status <- Some st;
st
| (*
RE - A regular expression library
Copyright (C) 2001 Jerome Vouillon
email: [email protected]
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, with
linking exception; either version 2.1 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*) |
test_wiki_page.ml |
open! Core
open! Async
open! Import
let subreddit = Subreddit_name.of_string "ThirdRealm"
let page : Wiki_page.Id.t = { subreddit = Some subreddit; page = "index" }
let%expect_test "add_wiki_editor" =
with_cassette "add_wiki_editor" ~f:(fun connection ->
Connection.call_exn
connection
(Endpoint.add_wiki_editor ~page ~user:(Username.of_string "L72_Elite_Kraken")))
;;
let%expect_test "remove_wiki_editor" =
with_cassette "remove_wiki_editor" ~f:(fun connection ->
Connection.call_exn
connection
(Endpoint.remove_wiki_editor ~page ~user:(Username.of_string "L72_Elite_Kraken")))
;;
let%expect_test "toggle_wiki_revision_visibility" =
with_cassette "toggle_wiki_revision_visibility" ~f:(fun connection ->
let%bind result =
Connection.call_exn
connection
(Endpoint.toggle_wiki_revision_visibility
~page
~revision:
(Wiki_page.Revision.Id.of_string "8048c97c-52ba-11e7-ab00-0ad38c20ef7e"))
in
print_s [%sexp (result : [ `Became_hidden | `Became_visible ])];
[%expect {| Became_hidden |}];
return ())
;;
let%expect_test "revert_wiki_page" =
with_cassette "revert_wiki_page" ~f:(fun connection ->
Connection.call_exn
connection
(Endpoint.revert_wiki_page
~page
~revision:
(Wiki_page.Revision.Id.of_string "e4d3d130-52b9-11e7-9d0c-0e1b806ed802")))
;;
let%expect_test "wiki_page_revisions" =
with_cassette "wiki_page_revisions" ~f:(fun connection ->
let%bind revisions =
Connection.call_exn
connection
(Endpoint.wiki_page_revisions
~pagination:
(After
(Listing.Page_id.of_string
"WikiRevision_bde92910-52b1-11e7-bf40-120ea8b0860a"))
~limit:3
()
~page)
>>| Listing.children
in
List.iter revisions ~f:(fun revision ->
print_s
[%sexp
{ author : Username.t option =
Wiki_page.Revision.author revision |> Option.map ~f:Thing.User.name
; page_name : string = Wiki_page.Revision.page_name revision
; id : Wiki_page.Revision.Id.t = Wiki_page.Revision.id revision
; reason : string option = Wiki_page.Revision.reason revision
; timestamp : Time_ns.t = Wiki_page.Revision.timestamp revision
; hidden : bool = Wiki_page.Revision.hidden revision
}]);
[%expect
{|
((author (BJO_test_mod)) (page_name index)
(id 7b080602-52b1-11e7-9041-0ed4553efb98) (reason ())
(timestamp (2017-06-16 16:33:08.000000000Z)) (hidden false))
((author (BJO_test_mod)) (page_name index)
(id 7ae7dca6-52b1-11e7-96d7-0a0b84aef9f8) (reason ())
(timestamp (2017-06-16 16:33:08.000000000Z)) (hidden false))
((author (BJO_test_mod)) (page_name index)
(id 610979ca-52b1-11e7-ad39-0e1b806ed802) (reason ())
(timestamp (2017-06-16 16:32:24.000000000Z)) (hidden false)) |}];
return ())
;;
let%expect_test "wiki_discussions" =
with_cassette "wiki_discussions" ~f:(fun connection ->
let%bind discussions =
Connection.call_exn connection (Endpoint.wiki_discussions () ~page)
>>| Listing.children
in
List.iter discussions ~f:(fun link ->
print_s [%sexp (Thing.Link.id link : Thing.Link.Id.t)]);
[%expect {| jhvugk |}];
return ())
;;
let%expect_test "wiki_pages" =
with_cassette "wiki_pages" ~f:(fun connection ->
let%bind pages =
Connection.call_exn connection (Endpoint.wiki_pages () ~subreddit)
in
print_s [%sexp (pages : string list)];
[%expect
{|
(config/automoderator config/description config/sidebar config/stylesheet
config/submit_text index praw_test_page tbsettings toolbox usernotes
wiki/index) |}];
return ())
;;
let%expect_test "subreddit_wiki_revisions" =
with_cassette "subreddit_wiki_revisions" ~f:(fun connection ->
let%bind revisions =
Connection.call_exn
connection
(Endpoint.subreddit_wiki_revisions ~subreddit ~limit:1 ())
>>| Listing.children
in
List.iter revisions ~f:(fun revision ->
print_s
[%sexp
{ author : Username.t option =
Wiki_page.Revision.author revision |> Option.map ~f:Thing.User.name
; page_name : string = Wiki_page.Revision.page_name revision
; id : Wiki_page.Revision.Id.t = Wiki_page.Revision.id revision
; reason : string option = Wiki_page.Revision.reason revision
; timestamp : Time_ns.t = Wiki_page.Revision.timestamp revision
; hidden : bool = Wiki_page.Revision.hidden revision
}]);
[%expect
{|
((author (BJO_test_user)) (page_name index)
(id f36c8b31-16d6-11eb-9cbb-0e03a79c97b5) (reason ("reverted back 3 years"))
(timestamp (2020-10-25 15:30:02.000000000Z)) (hidden false)) |}];
return ())
;;
let%expect_test "wiki_permissions" =
with_cassette "wiki_permissions" ~f:(fun connection ->
let%bind permissions =
Connection.call_exn connection (Endpoint.wiki_permissions ~page)
in
print_s
[%sexp
{ level : Wiki_page.Permissions.Level.t =
Wiki_page.Permissions.level permissions
; contributors : Username.t list =
Wiki_page.Permissions.contributors permissions
|> List.map ~f:Thing.User.name
; listed : bool = Wiki_page.Permissions.listed permissions
}];
[%expect
{|
((level Only_approved_contributors_for_this_page)
(contributors (L72_Elite_Kraken)) (listed true)) |}];
return ())
;;
let%expect_test "set_wiki_permissions" =
with_cassette "set_wiki_permissions" ~f:(fun connection ->
let%bind permissions =
Connection.call_exn
connection
(Endpoint.set_wiki_permissions ~level:Only_moderators ~listed:true ~page)
in
print_s
[%sexp
{ level : Wiki_page.Permissions.Level.t =
Wiki_page.Permissions.level permissions
; listed : bool = Wiki_page.Permissions.listed permissions
}];
[%expect {| ((level Only_moderators) (listed true)) |}];
return ())
;;
| |
perf_sparse_ndarray.ml |
#!/usr/bin/env owl
#zoo "5ca2fdebb0ccb9ecee6f4331972a9087"
(* Performance test of Owl_sparse_ndarray module *)
open Bigarray
module M = Owl_sparse_ndarray_generic
let test_op s c op = Perf_common.test_op s c op
let _ =
let _ = Random.self_init () in
let m, n, o = 10, 1000, 10000 and c = 1 in
let density = 0.00001 in
print_endline (String.make 60 '+');
Printf.printf "| test ndarray size: %i x %i x %i exps: %i\n" m n o c;
print_endline (String.make 60 '-');
let x = M.uniform ~density Bigarray.Float64 [|m;n;o|] in
let y = M.uniform ~density Bigarray.Float64 [|m;n;o|] in
test_op "zeros " c (fun () -> M.zeros Bigarray.Float64 [|m;n;o|]);
test_op "uniform " c (fun () -> M.uniform ~density Bigarray.Float64 [|m;n;o|]);
test_op "min " c (fun () -> M.min x);
test_op "minmax " c (fun () -> M.minmax x);
test_op "abs " c (fun () -> M.abs x);
test_op "neg " c (fun () -> M.neg x);
test_op "sum " c (fun () -> M.sum x);
test_op "add x y " c (fun () -> M.add x y);
test_op "mul x y " c (fun () -> M.mul x y);
test_op "add_scalar " c (fun () -> M.add_scalar x 0.5);
test_op "mul_scalar " c (fun () -> M.mul_scalar x 10.);
test_op "is_zero " c (fun () -> M.is_zero x);
test_op "equal " c (fun () -> M.equal x x);
test_op "greater " c (fun () -> M.greater x x);
test_op "greater_equal " c (fun () -> M.greater_equal x x);
test_op "copy " c (fun () -> M.copy x);
test_op "iteri " c (fun () -> M.iteri (fun i a -> ()) x);
test_op "iter " c (fun () -> M.iter (fun a -> ()) x);
test_op "iteri (0,*,*) " c (fun () -> M.iteri ~axis:[|Some 0; None; None|] (fun i a -> ()) x);
test_op "iter (0,*,*) " c (fun () -> M.iter ~axis:[|Some 0; None; None|] (fun a -> ()) x);
test_op "iteri_nz " c (fun () -> M.iteri_nz (fun i a -> ()) x);
test_op "iter_nz " c (fun () -> M.iter_nz (fun a -> ()) x);
test_op "iteri_nz (0,*,*) " c (fun () -> M.iteri_nz ~axis:[|Some 0; None; None|] (fun i a -> ()) x);
test_op "iter_nz (0,*,*) " c (fun () -> M.iter_nz ~axis:[|Some 0; None; None|] (fun a -> ()) x);
test_op "mapi_nz " c (fun () -> M.mapi_nz (fun i a -> a) x);
test_op "map_nz " c (fun () -> M.map_nz (fun a -> a) x);
test_op "map_nz (sin) " c (fun () -> M.map_nz (fun a -> sin a) x);
test_op "map_nz (+1) " c (fun () -> M.map_nz (fun a -> a +. 1.) x);
print_endline (String.make 60 '+');
| |
dune |
(executables
(names merge_fmt)
(public_names merge-fmt)
(libraries base stdio unix cmdliner)
) | |
sihl_cache.ml |
let log_src = Logs.Src.create ("sihl.service." ^ Sihl.Contract.Cache.name)
module Logs = (val Logs.src_log log_src : Logs.LOG)
module MakeSql (Repo : Repo_sql.Sig) : Sihl.Contract.Cache.Sig = struct
let find = Repo.find
let set ?ctx (k, v) =
match v with
| Some v ->
(match%lwt find k with
| Some _ -> Repo.update ?ctx (k, v)
| None -> Repo.insert ?ctx (k, v))
| None ->
(match%lwt find k with
| Some _ -> Repo.delete ?ctx k
| None ->
(* nothing to do *)
Lwt.return ())
;;
(* Lifecycle *)
let start () = Lwt.return ()
let stop () = Lwt.return ()
let lifecycle =
Sihl.Container.create_lifecycle
Sihl.Contract.Cache.name
~dependencies:(fun () -> Repo.lifecycles)
~start
~stop
;;
let register () =
Repo.register_migration ();
Repo.register_cleaner ();
Sihl.Container.Service.create lifecycle
;;
end
module PostgreSql =
MakeSql (Repo_sql.MakePostgreSql (Sihl.Database.Migration.PostgreSql))
module MariaDb = MakeSql (Repo_sql.MakeMariaDb (Sihl.Database.Migration.MariaDb))
| |
eventfd-ring.c | /* SPDX-License-Identifier: MIT */
/*
* Description: run various nop tests
*
*/
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/eventfd.h>
#include "liburing.h"
#include "helpers.h"
int main(int argc, char *argv[])
{
struct io_uring_params p = {};
struct io_uring ring1, ring2;
struct io_uring_sqe *sqe;
int ret, evfd1, evfd2;
if (argc > 1)
return T_EXIT_SKIP;
ret = io_uring_queue_init_params(8, &ring1, &p);
if (ret) {
fprintf(stderr, "ring setup failed: %d\n", ret);
return T_EXIT_FAIL;
}
if (!(p.features & IORING_FEAT_CUR_PERSONALITY)) {
fprintf(stdout, "Skipping\n");
return T_EXIT_SKIP;
}
ret = io_uring_queue_init(8, &ring2, 0);
if (ret) {
fprintf(stderr, "ring setup failed: %d\n", ret);
return T_EXIT_FAIL;
}
evfd1 = eventfd(0, EFD_CLOEXEC);
if (evfd1 < 0) {
perror("eventfd");
return T_EXIT_FAIL;
}
evfd2 = eventfd(0, EFD_CLOEXEC);
if (evfd2 < 0) {
perror("eventfd");
return T_EXIT_FAIL;
}
ret = io_uring_register_eventfd(&ring1, evfd1);
if (ret) {
fprintf(stderr, "failed to register evfd: %d\n", ret);
return T_EXIT_FAIL;
}
ret = io_uring_register_eventfd(&ring2, evfd2);
if (ret) {
fprintf(stderr, "failed to register evfd: %d\n", ret);
return T_EXIT_FAIL;
}
sqe = io_uring_get_sqe(&ring1);
io_uring_prep_poll_add(sqe, evfd2, POLLIN);
sqe->user_data = 1;
sqe = io_uring_get_sqe(&ring2);
io_uring_prep_poll_add(sqe, evfd1, POLLIN);
sqe->user_data = 1;
ret = io_uring_submit(&ring1);
if (ret != 1) {
fprintf(stderr, "submit: %d\n", ret);
return T_EXIT_FAIL;
}
ret = io_uring_submit(&ring2);
if (ret != 1) {
fprintf(stderr, "submit: %d\n", ret);
return T_EXIT_FAIL;
}
sqe = io_uring_get_sqe(&ring1);
io_uring_prep_nop(sqe);
sqe->user_data = 3;
ret = io_uring_submit(&ring1);
if (ret != 1) {
fprintf(stderr, "submit: %d\n", ret);
return T_EXIT_FAIL;
}
return T_EXIT_PASS;
}
| /* SPDX-License-Identifier: MIT */
/* |
test.ml |
let () =
Test_http.(with_server servers) (fun () ->
Irmin_test.Store.run "irmin-http" ~misc:[] ~sleep:Lwt_unix.sleep
Test_http.(suites servers))
| (*
* Copyright (c) 2013-2022 Thomas Gazagnaire <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*) |
foo.ml |
print_endline "public binary"
| |
dune |
; This file was automatically generated, do not edit.
; Edit file manifest/main.ml instead.
(library
(name tezos_protocol_plugin_012_Psithaca)
(public_name tezos-protocol-plugin-012-Psithaca)
(instrumentation (backend bisect_ppx))
(libraries
tezos-base
tezos-protocol-012-Psithaca)
(flags
(:standard)
-open Tezos_base.TzPervasives
-open Tezos_base.TzPervasives.Error_monad.Legacy_monad_globals
-open Tezos_protocol_012_Psithaca)
(modules (:standard \ Plugin_registerer)))
(library
(name tezos_protocol_plugin_012_Psithaca_registerer)
(public_name tezos-protocol-plugin-012-Psithaca-registerer)
(instrumentation (backend bisect_ppx))
(libraries
tezos-base
tezos-embedded-protocol-012-Psithaca
tezos-protocol-plugin-012-Psithaca
tezos-shell)
(flags
(:standard)
-open Tezos_base.TzPervasives
-open Tezos_base.TzPervasives.Error_monad.Legacy_monad_globals
-open Tezos_embedded_protocol_012_Psithaca
-open Tezos_protocol_plugin_012_Psithaca
-open Tezos_shell)
(modules Plugin_registerer))
| |
nth_prime_bounds.c |
#include <gmp.h>
#include "flint.h"
#include "ulong_extras.h"
void n_nth_prime_bounds(mp_limb_t *lo, mp_limb_t *hi, ulong n)
{
int bits, ll;
double llo, lhi;
/* Lower and upper bounds for ln(n) */
bits = FLINT_BIT_COUNT(n);
llo = (bits-1) * 0.6931471;
lhi = bits * 0.6931472;
/* Lower bound for ln(ln(n)) */
if (n < 16) ll = 0;
else if (n < 1619) ll = 1;
else if (n < 528491312) ll = 2;
else ll = 3;
*lo = (mp_limb_t) (n * (llo + ll - 1));
*hi = (mp_limb_t) (n * (lhi + (ll+1) - (n >= 15985 ? 0.9427 : 0.0)));
}
| /*
Copyright (C) 2010 Fredrik Johansson
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/ |
dune |
(executables
(names mariadb postgresql)
(libraries sihl sihl-cache alcotest-lwt caqti-driver-mariadb
caqti-driver-postgresql))
| |
dune |
(library
(name ppx_deriving_cconv)
(public_name cconv-ppx)
(synopsis "ppx deriving interface for cconv: [@@deriving cconv]")
(kind ppx_deriver)
(ppx_runtime_libraries cconv)
(libraries ppx_deriving.api)
(optional)
(preprocess
(action (run ppxfind -legacy ppx_tools.metaquot --as-pp %{input-file})))
(flags :standard -warn-error -a+8 -w -9-27))
(rule
(targets ppx_deriving_cconv.ml)
(deps ppx_deriving_cconv.cppo.ml)
(action (run %{bin:cppo} -V OCAML:%{ocaml_version} %{deps} -o %{targets})))
| |
mul_nmod_vec_ptr.c |
#include "nmod_mat.h"
void nmod_mat_mul_nmod_vec_ptr(
mp_limb_t * const * c,
const nmod_mat_t A,
const mp_limb_t * const * b, slong blen)
{
slong i;
slong len = FLINT_MIN(A->c, blen);
slong nrows = A->r;
mp_limb_t * bb, * cc;
TMP_INIT;
TMP_START;
bb = TMP_ARRAY_ALLOC(len, mp_limb_t);
cc = TMP_ARRAY_ALLOC(nrows, mp_limb_t);
for (i = 0; i < len; i++)
bb[i] = b[i][0];
nmod_mat_mul_nmod_vec(cc, A, bb, len);
for (i = 0; i < nrows; i++)
c[i][0] = cc[i];
TMP_END;
}
| /*
Copyright (C) 2021 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/>.
*/ |
owl_ndarray_maths_map_omp.h |
#ifdef OWL_ENABLE_TEMPLATE
#ifndef INIT // Because some functions do not really utilise this,
#define INIT // so define an empty string as default.
#endif
#include "owl_core_engine.h"
#include "owl_omp_parameters.h"
// function to perform mapping of elements from x to y
#ifdef FUN4
#undef OWL_OMP_THRESHOLD
#define OWL_OMP_THRESHOLD OWL_OMP_THRESHOLD_FUN(FUN4)
CAMLprim value FUN4(value vN, value vX, value vY)
{
CAMLparam3(vN, vX, vY);
int N = Long_val(vN);
INIT;
struct caml_ba_array *X = Caml_ba_array_val(vX);
NUMBER *X_data = (NUMBER *) X->data;
struct caml_ba_array *Y = Caml_ba_array_val(vY);
NUMBER1 *Y_data = (NUMBER1 *) Y->data;
NUMBER *start_x, *stop_x;
NUMBER1 *start_y;
caml_release_runtime_system(); /* Allow other threads */
start_x = X_data;
stop_x = start_x + N;
start_y = Y_data;
if (N >= OWL_OMP_THRESHOLD) {
#pragma omp parallel for schedule(static)
for (int i = 0; i < N; i++) {
NUMBER x = *(start_x + i);
*(start_y + i) = (MAPFN(x));
}
}
else {
while (start_x != stop_x) {
NUMBER x = *start_x;
*start_y = (MAPFN(x));
start_x += 1;
start_y += 1;
};
}
caml_acquire_runtime_system(); /* Disallow other threads */
CAMLreturn(Val_unit);
}
#endif /* FUN4 */
// function to map elements in [x] w.r.t scalar values, linspace and etc.
#ifdef FUN12
CAMLprim value FUN12(value vN, value vA, value vB, value vX)
{
CAMLparam1(vX);
int N = Long_val(vN);
INIT;
struct caml_ba_array *X = Caml_ba_array_val(vX);
NUMBER *X_data = (NUMBER *) X->data;
caml_release_runtime_system(); /* Allow other threads */
if (N >= OWL_OMP_THRESHOLD_DEFAULT) {
#pragma omp parallel for schedule(static)
for (int i = 1; i <= N; i++) {
MAPFN(*(X_data + i - 1));
}
}
else {
for (int i = 1; i <= N; i++) {
MAPFN(*X_data);
X_data++;
}
}
caml_acquire_runtime_system(); /* Disallow other threads */
CAMLreturn(Val_unit);
}
#endif /* FUN12 */
// function to calculate logspace_base function
#ifdef FUN13
CAMLprim value FUN13(value vN, value vBase, value vA, value vB, value vX)
{
CAMLparam1(vX);
int N = Long_val(vN);
INIT;
struct caml_ba_array *X = Caml_ba_array_val(vX);
NUMBER *X_data = (NUMBER *) X->data;
caml_release_runtime_system(); /* Allow other threads */
for (int i = 1; i <= N; i++) {
MAPFN(X_data);
X_data++;
}
caml_acquire_runtime_system(); /* Disallow other threads */
CAMLreturn(Val_unit);
}
#endif /* FUN13 */
// TODO: this needs to be unified with FUN4 in future
// similar to FUN4, but mostly for complex numbers
#ifdef FUN14
CAMLprim value FUN14(value vN, value vX, value vY)
{
CAMLparam3(vN, vX, vY);
int N = Long_val(vN);
struct caml_ba_array *X = Caml_ba_array_val(vX);
NUMBER *X_data = (NUMBER *) X->data;
struct caml_ba_array *Y = Caml_ba_array_val(vY);
NUMBER1 *Y_data = (NUMBER1 *) Y->data;
NUMBER *start_x;
NUMBER1 *start_y;
caml_release_runtime_system(); /* Allow other threads */
start_x = X_data;
start_y = Y_data;
if (N >= OWL_OMP_THRESHOLD_DEFAULT) {
#pragma omp parallel for schedule(static)
for (int i = 0; i < N; i++) {
MAPFN((start_x + i), (start_y + i));
}
}
else {
for (int i = 0; i < N; i++) {
MAPFN(start_x, start_y);
start_x += 1;
start_y += 1;
}
}
caml_acquire_runtime_system(); /* Disallow other threads */
CAMLreturn(Val_unit);
}
#endif /* FUN14 */
// function to map pairwise elements in x and y then save results to z
#ifdef FUN15
CAMLprim value FUN15(value vN, value vX, value vY, value vZ)
{
CAMLparam4(vN, vX, vY, vZ);
int N = Long_val(vN);
struct caml_ba_array *X = Caml_ba_array_val(vX);
NUMBER *X_data = (NUMBER *) X->data;
struct caml_ba_array *Y = Caml_ba_array_val(vY);
NUMBER1 *Y_data = (NUMBER1 *) Y->data;
struct caml_ba_array *Z = Caml_ba_array_val(vZ);
NUMBER2 *Z_data = (NUMBER2 *) Z->data;
NUMBER *start_x, *stop_x;
NUMBER1 *start_y;
NUMBER2 *start_z;
caml_release_runtime_system(); /* Allow other threads */
start_x = X_data;
stop_x = start_x + N;
start_y = Y_data;
start_z = Z_data;
if (N >= OWL_OMP_THRESHOLD_DEFAULT) {
#pragma omp parallel for schedule(static)
for (int i = 0; i < N; i++) {
MAPFN((start_x + i), (start_y + i), (start_z + i));
}
}
else {
while (start_x != stop_x) {
MAPFN(start_x, start_y, start_z);
start_x += 1;
start_y += 1;
start_z += 1;
}
}
caml_acquire_runtime_system(); /* Disallow other threads */
CAMLreturn(Val_unit);
}
#endif /* FUN15 */
// function to map all elements in [x] w.r.t to [a] then save results to [y]
#ifdef FUN17
CAMLprim value FUN17(value vN, value vX, value vY, value vA)
{
CAMLparam4(vN, vX, vY, vA);
int N = Long_val(vN);
INIT;
struct caml_ba_array *X = Caml_ba_array_val(vX);
NUMBER *X_data = (NUMBER *) X->data;
struct caml_ba_array *Y = Caml_ba_array_val(vY);
NUMBER1 *Y_data = (NUMBER1 *) Y->data;
NUMBER *start_x;
NUMBER1 *start_y;
caml_release_runtime_system(); /* Allow other threads */
start_x = X_data;
start_y = Y_data;
if (N >= OWL_OMP_THRESHOLD_DEFAULT) {
#pragma omp parallel for schedule(static)
for (int i = 0; i < N; i++) {
MAPFN((start_x + i), (start_y + i));
}
}
else {
for (int i = 0; i < N; i++) {
MAPFN(start_x, start_y);
start_x += 1;
start_y += 1;
}
}
caml_acquire_runtime_system(); /* Disallow other threads */
CAMLreturn(Val_unit);
}
#endif /* FUN17 */
// function to map elements in [x] w.r.t [a] and [b] then save results to [x]
#ifdef FUN18
CAMLprim value FUN18(value vN, value vX, value vA, value vB)
{
CAMLparam4(vN, vX, vA, vB);
int N = Long_val(vN);
INIT;
struct caml_ba_array *X = Caml_ba_array_val(vX);
NUMBER *X_data = (NUMBER *) X->data;
NUMBER *start_x, *stop_x;
caml_release_runtime_system(); /* Allow other threads */
start_x = X_data;
stop_x = start_x + N;
while (start_x != stop_x) {
MAPFN(start_x);
start_x += 1;
};
caml_acquire_runtime_system(); /* Disallow other threads */
CAMLreturn(Val_unit);
}
#endif /* FUN18 */
// function to map x to y with explicit offset, step size, number of ops
#ifdef FUN19
CAMLprim value FUN19_IMPL(
value vN,
value vX, value vOFSX, value vINCX,
value vY, value vOFSY, value vINCY
)
{
CAMLparam5(vN, vX, vOFSX, vINCX, vY);
CAMLxparam2(vOFSY, vINCY);
int N = Long_val(vN);
int ofsx = Long_val(vOFSX);
int incx = Long_val(vINCX);
int ofsy = Long_val(vOFSY);
int incy = Long_val(vINCY);
INIT;
struct caml_ba_array *X = Caml_ba_array_val(vX);
NUMBER *X_data = (NUMBER *) X->data;
struct caml_ba_array *Y = Caml_ba_array_val(vY);
NUMBER1 *Y_data = (NUMBER1 *) Y->data;
NUMBER *start_x;
NUMBER1 *start_y;
caml_release_runtime_system(); /* Allow other threads */
start_x = X_data + ofsx;
start_y = Y_data + ofsy;
if (N >= OWL_OMP_THRESHOLD_DEFAULT) {
#pragma omp parallel for schedule(static)
for (int i = 0; i < N; i++) {
MAPFN((start_x + i * incx), (start_y + i * incy));
}
}
else {
for (int i = 0; i < N; i++) {
MAPFN(start_x, start_y);
start_x += incx;
start_y += incy;
}
}
caml_acquire_runtime_system(); /* Disallow other threads */
CAMLreturn(Val_unit);
}
CAMLprim value FUN19(value *argv, int __unused_argn)
{
return FUN19_IMPL(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6]);
}
#endif /* FUN19 */
// function to map x to y with explicit offset, step size, number of ops
// more general version of FUN19, so more control over the access pattern to
// the data with two embedded loops.
#ifdef FUN20
CAMLprim value FUN20_IMPL(
value vM, value vN,
value vX, value vOFSX, value vINCX_M, value vINCX_N,
value vY, value vOFSY, value vINCY_M, value vINCY_N
)
{
CAMLparam2(vM, vN);
CAMLxparam4(vX, vOFSX, vINCX_M, vINCX_N);
CAMLxparam4(vY, vOFSY, vINCY_M, vINCY_N);
int M = Long_val(vM);
int N = Long_val(vN);
int ofsx = Long_val(vOFSX);
int incx_m = Long_val(vINCX_M);
int incx_n = Long_val(vINCX_N);
int ofsy = Long_val(vOFSY);
int incy_m = Long_val(vINCY_M);
int incy_n = Long_val(vINCY_N);
INIT;
struct caml_ba_array *X = Caml_ba_array_val(vX);
NUMBER *X_data = (NUMBER *) X->data;
struct caml_ba_array *Y = Caml_ba_array_val(vY);
NUMBER1 *Y_data = (NUMBER1 *) Y->data;
NUMBER *start_x_m;
NUMBER *start_x_n;
NUMBER1 *start_y_m;
NUMBER1 *start_y_n;
caml_release_runtime_system(); /* Allow other threads */
start_x_m = X_data + ofsx;
start_y_m = Y_data + ofsy;
if (N >= OWL_OMP_THRESHOLD_DEFAULT) {
#pragma omp parallel for schedule(static)
for (int i = 0; i < M; i++) {
start_x_n = start_x_m + i * incx_m;
start_y_n = start_y_m + i * incy_m;
for (int j = 0; j < N; j++) {
MAPFN(start_x_n, start_y_n);
start_x_n += incx_n;
start_y_n += incy_n;
}
}
}
else {
for (int i = 0; i < M; i++) {
start_x_n = start_x_m;
start_y_n = start_y_m;
for (int j = 0; j < N; j++) {
MAPFN(start_x_n, start_y_n);
start_x_n += incx_n;
start_y_n += incy_n;
}
start_x_m += incx_m;
start_y_m += incy_m;
}
}
caml_acquire_runtime_system(); /* Disallow other threads */
CAMLreturn(Val_unit);
}
CAMLprim value FUN20(value *argv, int __unused_argn)
{
return FUN20_IMPL(
argv[0], argv[1], argv[2], argv[3], argv[4],
argv[5], argv[6], argv[7], argv[8], argv[9]
);
}
#endif /* FUN20 */
// broadcast function of x and y then save the result to z
#ifdef FUN24
static OWL_INLINE void FUN24_CODE (
int d,
struct caml_ba_array *X, int64_t *stride_x, int ofs_x,
struct caml_ba_array *Y, int64_t *stride_y, int ofs_y,
struct caml_ba_array *Z, int64_t *stride_z, int ofs_z
)
{
int inc_x = X->dim[d] == Z->dim[d] ? stride_x[d] : 0;
int inc_y = Y->dim[d] == Z->dim[d] ? stride_y[d] : 0;
int inc_z = stride_z[d];
const int n = Z->dim[d];
if (d == X->num_dims - 1) {
NUMBER *x = (NUMBER *) X->data + ofs_x;
NUMBER *y = (NUMBER *) Y->data + ofs_y;
NUMBER *z = (NUMBER *) Z->data + ofs_z;
for (int i = 0; i < n; i++) {
MAPFN(x, y, z);
x += inc_x;
y += inc_y;
z += inc_z;
}
}
else {
for (int i = 0; i < n; i++) {
FUN24_CODE (d+1, X, stride_x, ofs_x, Y, stride_y, ofs_y, Z, stride_z, ofs_z);
ofs_x += inc_x;
ofs_y += inc_y;
ofs_z += inc_z;
}
}
return;
}
CAMLprim value FUN24_IMPL(
value vX, value vSTRIDE_X,
value vY, value vSTRIDE_Y,
value vZ, value vSTRIDE_Z
)
{
CAMLparam4(vX, vSTRIDE_X, vY, vSTRIDE_Y);
CAMLxparam2(vZ, vSTRIDE_Z);
struct caml_ba_array *X = Caml_ba_array_val(vX);
struct caml_ba_array *Y = Caml_ba_array_val(vY);
struct caml_ba_array *Z = Caml_ba_array_val(vZ);
struct caml_ba_array *stride_X = Caml_ba_array_val(vSTRIDE_X);
int64_t *stride_x = (int64_t *) stride_X->data;
struct caml_ba_array *stride_Y = Caml_ba_array_val(vSTRIDE_Y);
int64_t *stride_y = (int64_t *) stride_Y->data;
struct caml_ba_array *stride_Z = Caml_ba_array_val(vSTRIDE_Z);
int64_t *stride_z = (int64_t *) stride_Z->data;
caml_release_runtime_system(); /* Allow other threads */
FUN24_CODE (0, X, stride_x, 0, Y, stride_y, 0, Z, stride_z, 0);
caml_acquire_runtime_system(); /* Disallow other threads */
CAMLreturn(Val_unit);
}
CAMLprim value FUN24(value *argv, int __unused_argn)
{
return FUN24_IMPL(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
}
#endif /* FUN24 */
// broadcast function of x and y then save the result to z. Compared to FUN24,
// the difference of FUN25 is z has one extra dimension than max(dim_x, dim_y).
// This function is used in owl's distribution module and extra dimension is
// used as sample dimension.
#ifdef FUN25
static OWL_INLINE void FUN25_CODE (
int d,
struct caml_ba_array *X, int64_t *stride_x, int ofs_x,
struct caml_ba_array *Y, int64_t *stride_y, int ofs_y,
struct caml_ba_array *Z, int64_t *stride_z, int ofs_z
)
{
int inc_x = X->dim[d] == Z->dim[d+1] ? stride_x[d] : 0;
int inc_y = Y->dim[d] == Z->dim[d+1] ? stride_y[d] : 0;
int inc_z = stride_z[d+1];
const int n = Z->dim[d+1];
if (d == X->num_dims - 1) {
NUMBER *x = (NUMBER *) X->data + ofs_x;
NUMBER *y = (NUMBER *) Y->data + ofs_y;
NUMBER *z = (NUMBER *) Z->data + ofs_z;
for (int i = 0; i < n; i++) {
MAPFN(x, y, z);
x += inc_x;
y += inc_y;
z += inc_z;
}
}
else {
for (int i = 0; i < n; i++) {
FUN25_CODE (d+1, X, stride_x, ofs_x, Y, stride_y, ofs_y, Z, stride_z, ofs_z);
ofs_x += inc_x;
ofs_y += inc_y;
ofs_z += inc_z;
}
}
return;
}
CAMLprim value FUN25_IMPL(
value vX, value vSTRIDE_X,
value vY, value vSTRIDE_Y,
value vZ, value vSTRIDE_Z
)
{
CAMLparam4(vX, vSTRIDE_X, vY, vSTRIDE_Y);
CAMLxparam2(vZ, vSTRIDE_Z);
struct caml_ba_array *X = Caml_ba_array_val(vX);
struct caml_ba_array *Y = Caml_ba_array_val(vY);
struct caml_ba_array *Z = Caml_ba_array_val(vZ);
struct caml_ba_array *stride_X = Caml_ba_array_val(vSTRIDE_X);
int64_t *stride_x = (int64_t *) stride_X->data;
struct caml_ba_array *stride_Y = Caml_ba_array_val(vSTRIDE_Y);
int64_t *stride_y = (int64_t *) stride_Y->data;
struct caml_ba_array *stride_Z = Caml_ba_array_val(vSTRIDE_Z);
int64_t *stride_z = (int64_t *) stride_Z->data;
caml_release_runtime_system(); /* Allow other threads */
int ofs_z = 0;
for (int i = 0; i < Z->dim[0]; i++) {
FUN25_CODE (0, X, stride_x, 0, Y, stride_y, 0, Z, stride_z, ofs_z);
ofs_z += stride_z[0];
}
caml_acquire_runtime_system(); /* Disallow other threads */
CAMLreturn(Val_unit);
}
CAMLprim value FUN25(value *argv, int __unused_argn)
{
return FUN25_IMPL(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
}
#endif /* FUN25 */
// Similar to FUN25, but broadcast between w, x, y, then save the result to z
#ifdef FUN27
static OWL_INLINE void FUN27_CODE (
int d,
struct caml_ba_array *W, int64_t *stride_w, int ofs_w,
struct caml_ba_array *X, int64_t *stride_x, int ofs_x,
struct caml_ba_array *Y, int64_t *stride_y, int ofs_y,
struct caml_ba_array *Z, int64_t *stride_z, int ofs_z
)
{
int inc_w = W->dim[d] == Z->dim[d+1] ? stride_w[d] : 0;
int inc_x = X->dim[d] == Z->dim[d+1] ? stride_x[d] : 0;
int inc_y = Y->dim[d] == Z->dim[d+1] ? stride_y[d] : 0;
int inc_z = stride_z[d+1];
const int n = Z->dim[d+1];
if (d == X->num_dims - 1) {
NUMBER *w = (NUMBER *) W->data + ofs_w;
NUMBER *x = (NUMBER *) X->data + ofs_x;
NUMBER *y = (NUMBER *) Y->data + ofs_y;
NUMBER *z = (NUMBER *) Z->data + ofs_z;
for (int i = 0; i < n; i++) {
MAPFN(w, x, y, z);
w += inc_w;
x += inc_x;
y += inc_y;
z += inc_z;
}
}
else {
for (int i = 0; i < n; i++) {
FUN27_CODE (d+1, W, stride_w, ofs_w, X, stride_x, ofs_x, Y, stride_y, ofs_y, Z, stride_z, ofs_z);
ofs_w += inc_w;
ofs_x += inc_x;
ofs_y += inc_y;
ofs_z += inc_z;
}
}
return;
}
CAMLprim value FUN27_IMPL(
value vW, value vSTRIDE_W,
value vX, value vSTRIDE_X,
value vY, value vSTRIDE_Y,
value vZ, value vSTRIDE_Z
)
{
CAMLparam4(vW, vSTRIDE_W, vX, vSTRIDE_X);
CAMLparam4(vY, vSTRIDE_Y, vZ, vSTRIDE_Z);
struct caml_ba_array *W = Caml_ba_array_val(vW);
struct caml_ba_array *X = Caml_ba_array_val(vX);
struct caml_ba_array *Y = Caml_ba_array_val(vY);
struct caml_ba_array *Z = Caml_ba_array_val(vZ);
struct caml_ba_array *stride_W = Caml_ba_array_val(vSTRIDE_W);
int64_t *stride_w = (int64_t *) stride_W->data;
struct caml_ba_array *stride_X = Caml_ba_array_val(vSTRIDE_X);
int64_t *stride_x = (int64_t *) stride_X->data;
struct caml_ba_array *stride_Y = Caml_ba_array_val(vSTRIDE_Y);
int64_t *stride_y = (int64_t *) stride_Y->data;
struct caml_ba_array *stride_Z = Caml_ba_array_val(vSTRIDE_Z);
int64_t *stride_z = (int64_t *) stride_Z->data;
caml_release_runtime_system(); /* Allow other threads */
int ofs_z = 0;
for (int i = 0; i < Z->dim[0]; i++) {
FUN27_CODE (0, W, stride_w, 0, X, stride_x, 0, Y, stride_y, 0, Z, stride_z, ofs_z);
ofs_z += stride_z[0];
}
caml_acquire_runtime_system(); /* Disallow other threads */
CAMLreturn(Val_unit);
}
CAMLprim value FUN27(value *argv, int __unused_argn)
{
return FUN27_IMPL(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7]);
}
#endif /* FUN27 */
// function to map x to y with explicit offset, step size, number of ops
// more general version of FUN20, so more control over the access pattern to
// the data with three embedded loops.
#ifdef FUN28
CAMLprim value FUN28_IMPL(
value vM, value vN, value vO,
value vX, value vOFSX, value vINCX_M, value vINCX_N, value vINCX_O,
value vY, value vOFSY, value vINCY_M, value vINCY_N, value vINCY_O
)
{
CAMLparam3(vM, vN, vO);
CAMLxparam5(vX, vOFSX, vINCX_M, vINCX_N, vINCX_O);
CAMLxparam5(vY, vOFSY, vINCY_M, vINCY_N, vINCY_O);
int M = Long_val(vM);
int N = Long_val(vN);
int O = Long_val(vO);
int ofsx = Long_val(vOFSX);
int incx_m = Long_val(vINCX_M);
int incx_n = Long_val(vINCX_N);
int incx_o = Long_val(vINCX_O);
int ofsy = Long_val(vOFSY);
int incy_m = Long_val(vINCY_M);
int incy_n = Long_val(vINCY_N);
int incy_o = Long_val(vINCY_O);
INIT;
struct caml_ba_array *X = Caml_ba_array_val(vX);
NUMBER *X_data = (NUMBER *) X->data;
struct caml_ba_array *Y = Caml_ba_array_val(vY);
NUMBER1 *Y_data = (NUMBER1 *) Y->data;
NUMBER *start_x_m;
NUMBER *start_x_n;
NUMBER *start_x_o;
NUMBER1 *start_y_m;
NUMBER1 *start_y_n;
NUMBER1 *start_y_o;
caml_release_runtime_system(); /* Allow other threads */
start_x_m = X_data + ofsx;
start_y_m = Y_data + ofsy;
for (int i = 0; i < M; i++) {
start_x_n = start_x_m;
start_y_n = start_y_m;
for (int j = 0; j < N; j++) {
start_x_o = start_x_n;
start_y_o = start_y_n;
for (int k = 0; k < O; k++) {
MAPFN(start_x_o, start_y_o);
start_x_o += incx_o;
start_y_o += incy_o;
}
start_x_n += incx_n;
start_y_n += incy_n;
}
start_x_m += incx_m;
start_y_m += incy_m;
}
caml_acquire_runtime_system(); /* Disallow other threads */
CAMLreturn(Val_unit);
}
CAMLprim value FUN28(value *argv, int __unused_argn)
{
return FUN28_IMPL(
argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6],
argv[7], argv[8], argv[9], argv[10], argv[11], argv[12]
);
}
#endif /* FUN28 */
// function to map [x] w.r.t scalar values, similar to FUN12 but saves to Y
#ifdef FUN29
CAMLprim value FUN29(value vN, value vA, value vB, value vX, value vY)
{
CAMLparam5(vN, vA, vB, vX, vY);
int N = Long_val(vN);
INIT;
struct caml_ba_array *X = Caml_ba_array_val(vX);
NUMBER *X_data = (NUMBER *) X->data;
struct caml_ba_array *Y = Caml_ba_array_val(vY);
NUMBER *Y_data = (NUMBER *) Y->data;
caml_release_runtime_system(); /* Allow other threads */
if (N >= OWL_OMP_THRESHOLD_DEFAULT) {
#pragma omp parallel for schedule(static)
for (int i = 0; i < N; i++) {
MAPFN(*(X_data + i), *(Y_data + i));
}
}
else {
for (int i = 0; i < N; i++) {
MAPFN(*(X_data + i), *(Y_data + i));
}
}
caml_acquire_runtime_system(); /* Disallow other threads */
CAMLreturn(Val_unit);
}
#endif /* FUN29 */
#undef NUMBER
#undef NUMBER1
#undef NUMBER2
#undef MAPFN
#undef MAPFN1
#undef MAPFN2
#undef MAPFN3
#undef INIT
#undef FUN4
#undef FUN12
#undef FUN13
#undef FUN14
#undef FUN15
#undef FUN17
#undef FUN18
#undef FUN19
#undef FUN19_IMPL
#undef FUN20
#undef FUN20_IMPL
#undef FUN24
#undef FUN24_IMPL
#undef FUN24_CODE
#undef FUN25
#undef FUN25_IMPL
#undef FUN25_CODE
#undef FUN27
#undef FUN27_IMPL
#undef FUN27_CODE
#undef FUN28
#undef FUN28_IMPL
#undef FUN29
#undef OWL_OMP_THRESHOLD
#endif /* OWL_ENABLE_TEMPLATE */
| /*
* OWL - OCaml Scientific and Engineering Computing
* Copyright (c) 2016-2020 Liang Wang <[email protected]>
*/ |
Token_helpers_python.mli |
val is_eof : Parser_python.token -> bool
val is_comment : Parser_python.token -> bool
val info_of_tok : Parser_python.token -> Parse_info.t
val visitor_info_of_tok :
(Parse_info.t -> Parse_info.t) -> Parser_python.token -> Parser_python.token
| |
Qextended.ml |
(** val coq_Qx_zero : Q.t **)
let coq_Qx_zero =
Farith_Big.q_mk (Farith_Big.zero, Farith_Big.one)
(** val coq_Qx_undef : Q.t **)
let coq_Qx_undef =
Farith_Big.q_mk (Farith_Big.zero, Farith_Big.zero)
(** val coq_Qx_inf : Q.t **)
let coq_Qx_inf =
Farith_Big.q_mk (Farith_Big.one, Farith_Big.zero)
(** val coq_Qx_minus_inf : Q.t **)
let coq_Qx_minus_inf =
Farith_Big.q_mk ((Farith_Big.opp Farith_Big.one), Farith_Big.zero)
| |
prevalidator_pending_operations.mli | (** The priority of a pending operation.
A priority is attached to each pending operation. *)
type priority = [`High | `Medium | `Low of Q.t list]
(**
This type is used for data representing pending operations of the
prevalidator. Any iterator on this structure will process operations with
[`High] priority first, followed by [`Medium] and finally [`Low] priority. *)
type 'protocol_data t
module Sized_set :
Tezos_base.Sized.SizedSet with type set := Operation_hash.Set.t
(** The empty structure of pending operations. *)
val empty : 'protocol_data t
(** [hashes p] returns the set of hashes contained in [p] *)
val hashes : 'protocol_data t -> Operation_hash.Set.t
(** [operations p] returns the Map of bindings [oph -> op] contained in [p] *)
val operations :
'protocol_data t ->
'protocol_data Prevalidation.operation Operation_hash.Map.t
(** [is_empty p] returns [true] if [p] has operations, [false] otherwise. *)
val is_empty : 'protocol_data t -> bool
(** [mem oph p] returns [true] if [oph] is found in [p], [false] otherwise.
Complexity is O(log(n)), where n is the number of operations (hashes) in the
structure.
*)
val mem : Operation_hash.t -> 'protocol_data t -> bool
(** [add oph op p prio] records the operation [op] whose hash is [oph] and whose
priority is [prio] in [p].
Complexity is O(log(n)), where n is the number of operations (hashes) in the
structure.
*)
val add :
'protocol_data Prevalidation.operation ->
priority ->
'protocol_data t ->
'protocol_data t
(** [remove oph op p] removes the binding [oph] from [p].
Complexity is O(log(n)), where n is the number of operations (hashes) in the
structure.
*)
val remove : Operation_hash.t -> 'protocol_data t -> 'protocol_data t
(** [cardinal p] returns the number of operations (hashes) in [p].
Complexity is O(n), where n is the number of operations (hashes) in the
structure.
*)
val cardinal : 'protocol_data t -> int
(** [fold f p acc] applies the function [f] on every binding [oph] |-> [op] of
priority [prio] in [p]. The [acc] is passed to and (possibly) updated by
every call to [f].
We iterate on operations with `High priority first, then on those with `Low
priority. For operations with the same priority, the iteration order is
defined [Operation_hash.compare] function (operations with small hashes are
processed first).
*)
val fold :
(priority ->
Operation_hash.t ->
'protocol_data Prevalidation.operation ->
'a ->
'a) ->
'protocol_data t ->
'a ->
'a
(** [iter f p] is similar to [fold] where [acc] is unit *)
val iter :
(priority ->
Operation_hash.t ->
'protocol_data Prevalidation.operation ->
unit) ->
'protocol_data t ->
unit
(** [fold_es f p acc] is the Lwt version of [fold], except that [fold_es]
returns wihtout iterating over all the elements of the list as soon as a
value [Error e] is returned by [f] *)
val fold_es :
(priority ->
Operation_hash.t ->
'protocol_data Prevalidation.operation ->
'a ->
('a, 'b) result Lwt.t) ->
'protocol_data t ->
'a ->
('a, 'b) result Lwt.t
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* Copyright (c) 2018-2021 Nomadic Labs, <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
let-open.ml |
let _ =
(* ... *)
let open Option in
indented_line
| |
test_hexdump.mli | (*_ This signature is deliberately empty. *)
| (*_ This signature is deliberately empty. *)
|
user_activated.mli | (** User activated upgrades: at given level, switch to given protocol. *)
type upgrades = (Int32.t * Protocol_hash.t) list
val upgrades_encoding : upgrades Data_encoding.t
(** User activated protocol overrides.
An override [(a, b)] denotes that if [a] is to be activated at the end
of the promotion phase, [b] shall be activated instead. *)
type protocol_overrides = (Protocol_hash.t * Protocol_hash.t) list
val protocol_overrides_encoding : protocol_overrides Data_encoding.t
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2019 Nomadic Labs, <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
let-and.ml |
let f
= fun x -> x
and g
= fun x -> x
and h
= fun x -> x
let rec f : 'a. 'a -> 'a
= fun x -> g x
and g : 'a. 'a -> 'a
= fun x -> h x
and h : 'a. 'a -> 'a
= fun x -> f x
| |
unixiz.ml |
let blit0 src src_off dst dst_off len =
let dst = Cstruct.of_bigarray ~off:dst_off ~len dst in
Cstruct.blit src src_off dst 0 len
let blit1 src src_off dst dst_off len =
let src = Cstruct.of_bigarray ~off:src_off ~len src in
Cstruct.blit src 0 dst dst_off len
open Lwt.Infix
open Rresult
let ( >>? ) = Lwt_result.bind
module Make (Flow : Mirage_flow.S) = struct
type +'a fiber = 'a Lwt.t
type t = {
queue : (char, Bigarray.int8_unsigned_elt) Ke.Rke.t;
flow : Flow.flow;
}
type error = [ `Error of Flow.error | `Write_error of Flow.write_error ]
let pp_error ppf = function
| `Error err -> Flow.pp_error ppf err
| `Write_error err -> Flow.pp_write_error ppf err
let make flow = { flow; queue = Ke.Rke.create ~capacity:0x1000 Bigarray.char }
let recv flow payload =
if Ke.Rke.is_empty flow.queue then (
Flow.read flow.flow >|= R.reword_error (fun err -> `Error err)
>>? function
| `Eof -> Lwt.return_ok `End_of_flow
| `Data res ->
Ke.Rke.N.push flow.queue ~blit:blit0 ~length:Cstruct.length res;
let len = min (Cstruct.length payload) (Ke.Rke.length flow.queue) in
Ke.Rke.N.keep_exn flow.queue ~blit:blit1 ~length:Cstruct.length ~off:0
~len payload;
Ke.Rke.N.shift_exn flow.queue len;
Lwt.return_ok (`Input len))
else
let len = min (Cstruct.length payload) (Ke.Rke.length flow.queue) in
Ke.Rke.N.keep_exn flow.queue ~blit:blit1 ~length:Cstruct.length ~len
payload;
Ke.Rke.N.shift_exn flow.queue len;
Lwt.return_ok (`Input len)
let send flow payload =
Flow.write flow.flow payload >|= function
| Error `Closed -> R.error (`Write_error `Closed)
| Error err -> R.error (`Write_error err)
| Ok () -> R.ok (Cstruct.length payload)
end
| |
t-equal_trunc.c |
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
#include "flint.h"
#include "fmpz.h"
#include "fmpz_poly.h"
#include "ulong_extras.h"
int
main(void)
{
int i, result;
FLINT_TEST_INIT(state);
flint_printf("equal_trunc....");
fflush(stdout);
/* equal polynomials */
for (i = 0; i < 1000 * flint_test_multiplier(); i++)
{
fmpz_poly_t a, b;
fmpz_t c;
slong n, j;
fmpz_init(c);
fmpz_poly_init(a);
fmpz_poly_init(b);
fmpz_poly_randtest(a, state, n_randint(state, 100), 200);
fmpz_poly_randtest(b, state, n_randint(state, 100), 200);
n = n_randint(state, 100);
for (j = 0; j < n; j++)
{
fmpz_poly_get_coeff_fmpz(c, a, j);
fmpz_poly_set_coeff_fmpz(b, j, c);
}
result = (fmpz_poly_equal_trunc(a, b, n));
if (!result)
{
flint_printf("FAIL:\n");
fmpz_poly_print(a), flint_printf("\n\n");
fmpz_poly_print(b), flint_printf("\n\n");
flint_printf("n = %wd\n", n);
fflush(stdout);
flint_abort();
}
fmpz_clear(c);
fmpz_poly_clear(a);
fmpz_poly_clear(b);
}
/* unequal polynomials */
for (i = 0; i < 1000 * flint_test_multiplier(); i++)
{
fmpz_poly_t a, b;
fmpz_t c;
slong m, n, j;
fmpz_init(c);
fmpz_poly_init(a);
fmpz_poly_init(b);
fmpz_poly_randtest(a, state, n_randint(state, 100), 200);
fmpz_poly_randtest(b, state, n_randint(state, 100), 200);
n = n_randint(state, 100) + 1;
m = n_randint(state, n);
for (j = 0; j < n; j++)
{
fmpz_poly_get_coeff_fmpz(c, a, j);
fmpz_poly_set_coeff_fmpz(b, j, c);
}
fmpz_poly_get_coeff_fmpz(c, b, m);
fmpz_add_ui(c, c, 1);
fmpz_poly_set_coeff_fmpz(b, m, c);
result = (!fmpz_poly_equal_trunc(a, b, n));
if (!result)
{
flint_printf("FAIL:\n");
fmpz_poly_print(a), flint_printf("\n\n");
fmpz_poly_print(b), flint_printf("\n\n");
flint_printf("n = %wd\n", n);
flint_printf("m = %wd\n", m);
fflush(stdout);
flint_abort();
}
fmpz_clear(c);
fmpz_poly_clear(a);
fmpz_poly_clear(b);
}
FLINT_TEST_CLEANUP(state);
flint_printf("PASS\n");
return 0;
}
| /*
Copyright (C) 2009 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/>.
*/ |
divides_heap_threaded.c |
#include "thread_pool.h"
#include "nmod_mpoly.h"
#include "fmpz_mpoly.h" /* for mpoly_divides_select_exps */
#define PROFILE_THIS 0
#if PROFILE_THIS
#include "profiler.h"
typedef struct _vec_slong_struct
{
slong * array;
slong alloc;
slong length;
} vec_slong_struct;
typedef vec_slong_struct vec_slong_t[1];
static void vec_slong_init(vec_slong_t v)
{
v->length = 0;
v->alloc = 16;
v->array = (slong *) flint_malloc(v->alloc*sizeof(slong));
}
static void vec_slong_clear(vec_slong_t v)
{
flint_free(v->array);
}
static void vec_slong_push_back(vec_slong_t v, slong a)
{
v->length++;
if (v->length > v->alloc)
{
v->alloc = FLINT_MAX(v->length, 2*v->alloc);
v->array = (slong *) flint_realloc(v->array, v->alloc*sizeof(slong));
}
v->array[v->length - 1] = a;
}
static void vec_slong_print(const vec_slong_t v)
{
slong i;
flint_printf("[");
for (i = 0; i < v->length; i++)
{
flint_printf("%wd",v->array[i]);
if (i + 1 < v->length)
{
flint_printf(",",v->array[i]);
}
}
flint_printf("]");
}
#endif
/*
a thread safe mpoly supports three mutating operations
- init from an array of terms
- append an array of terms
- clear out contents to a normal mpoly
*/
typedef struct _nmod_mpoly_ts_struct
{
mp_limb_t * volatile coeffs; /* this is coeff_array[idx] */
ulong * volatile exps; /* this is exp_array[idx] */
volatile slong length;
slong alloc;
flint_bitcnt_t bits;
flint_bitcnt_t idx;
mp_limb_t * exp_array[FLINT_BITS];
ulong * coeff_array[FLINT_BITS];
} nmod_mpoly_ts_struct;
typedef nmod_mpoly_ts_struct nmod_mpoly_ts_t[1];
static void nmod_mpoly_ts_init(nmod_mpoly_ts_t A,
mp_limb_t * Bcoeff, ulong * Bexp, slong Blen,
flint_bitcnt_t bits, slong N)
{
slong i;
flint_bitcnt_t idx = FLINT_BIT_COUNT(Blen);
idx = (idx <= 8) ? 0 : idx - 8;
for (i = 0; i < FLINT_BITS; i++)
{
A->exp_array[i] = NULL;
A->coeff_array[i] = NULL;
}
A->bits = bits;
A->idx = idx;
A->alloc = WORD(256) << idx;
A->exps = A->exp_array[idx]
= (ulong *) flint_malloc(N*A->alloc*sizeof(ulong));
A->coeffs = A->coeff_array[idx]
= (mp_limb_t *) flint_malloc(A->alloc*sizeof(mp_limb_t));
A->length = Blen;
for (i = 0; i < Blen; i++)
{
A->coeffs[i] = Bcoeff[i];
mpoly_monomial_set(A->exps + N*i, Bexp + N*i, N);
}
}
static void nmod_mpoly_ts_clear(nmod_mpoly_ts_t A)
{
slong i;
for (i = 0; i < FLINT_BITS; i++)
{
if (A->exp_array[i] != NULL)
{
FLINT_ASSERT(A->coeff_array[i] != NULL);
flint_free(A->coeff_array[i]);
flint_free(A->exp_array[i]);
}
}
}
/* put B on the end of A */
static void nmod_mpoly_ts_append(nmod_mpoly_ts_t A,
mp_limb_t * Bcoeff, ulong * Bexps, slong Blen, slong N)
{
/* TODO: this needs barriers on non-x86 */
slong i;
ulong * oldexps = A->exps;
ulong * oldcoeffs = A->coeffs;
slong oldlength = A->length;
slong newlength = A->length + Blen;
if (newlength <= A->alloc)
{
/* write new terms first */
for (i = 0; i < Blen; i++)
{
oldcoeffs[oldlength + i] = Bcoeff[i];
mpoly_monomial_set(oldexps + N*(oldlength + i), Bexps + N*i, N);
}
}
else
{
slong newalloc;
ulong * newexps;
mp_limb_t * newcoeffs;
flint_bitcnt_t newidx;
newidx = FLINT_BIT_COUNT(newlength - 1);
newidx = (newidx > 8) ? newidx - 8 : 0;
FLINT_ASSERT(newidx > A->idx);
newalloc = UWORD(256) << newidx;
FLINT_ASSERT(newlength <= newalloc);
newexps = A->exp_array[newidx]
= (ulong *) flint_malloc(N*newalloc*sizeof(ulong));
newcoeffs = A->coeff_array[newidx]
= (mp_limb_t *) flint_malloc(newalloc*sizeof(mp_limb_t));
for (i = 0; i < oldlength; i++)
{
newcoeffs[i] = oldcoeffs[i];
mpoly_monomial_set(newexps + N*i, oldexps + N*i, N);
}
for (i = 0; i < Blen; i++)
{
newcoeffs[oldlength + i] = Bcoeff[i];
mpoly_monomial_set(newexps + N*(oldlength + i), Bexps + N*i, N);
}
A->alloc = newalloc;
A->exps = newexps;
A->coeffs = newcoeffs;
A->idx = newidx;
/* do not free oldcoeff/exps as other threads may be using them */
}
/* update length at the very end */
A->length = newlength;
}
/*
a chunk holds an exponent range on the dividend
*/
typedef struct _divides_heap_chunk_struct
{
nmod_mpoly_t polyC;
struct _divides_heap_chunk_struct * next;
ulong * emin;
ulong * emax;
slong startidx;
slong endidx;
int upperclosed;
volatile int lock;
volatile int producer;
volatile slong ma;
volatile slong mq;
int Cinited;
#if PROFILE_THIS
slong idx;
#endif
} divides_heap_chunk_struct;
typedef divides_heap_chunk_struct divides_heap_chunk_t[1];
/*
the base struct includes a linked list of chunks
*/
typedef struct
{
#if FLINT_USES_PTHREAD
pthread_mutex_t mutex;
#endif
divides_heap_chunk_struct * head;
divides_heap_chunk_struct * tail;
divides_heap_chunk_struct * volatile cur;
nmod_mpoly_t polyA;
nmod_mpoly_t polyB;
nmod_mpoly_ts_t polyQ;
const nmod_mpoly_ctx_struct * ctx;
slong length;
slong N;
flint_bitcnt_t bits;
mp_limb_t lc_inv;
ulong * cmpmask;
int failed;
#if PROFILE_THIS
timeit_t timer;
#endif
} divides_heap_base_struct;
typedef divides_heap_base_struct divides_heap_base_t[1];
/*
the worker stuct has a big chunk of memory in the stripe_t
and two polys for work space
*/
typedef struct _worker_arg_struct
{
divides_heap_base_struct * H;
nmod_mpoly_stripe_t S;
nmod_mpoly_t polyT1;
nmod_mpoly_t polyT2;
#if PROFILE_THIS
vec_slong_t time_data;
#endif
} worker_arg_struct;
typedef worker_arg_struct worker_arg_t[1];
static void divides_heap_base_init(divides_heap_base_t H)
{
H->head = NULL;
H->tail = NULL;
H->cur = NULL;
H->ctx = NULL;
H->length = 0;
H->N = 0;
H->bits = 0;
H->cmpmask = NULL;
}
static void divides_heap_chunk_clear(divides_heap_chunk_t L, divides_heap_base_t H)
{
if (L->Cinited)
{
nmod_mpoly_clear(L->polyC, H->ctx);
}
}
static int divides_heap_base_clear(nmod_mpoly_t Q, divides_heap_base_t H)
{
divides_heap_chunk_struct * L = H->head;
while (L != NULL)
{
divides_heap_chunk_struct * nextL = L->next;
divides_heap_chunk_clear(L, H);
flint_free(L);
L = nextL;
}
H->head = NULL;
H->tail = NULL;
H->cur = NULL;
H->length = 0;
H->N = 0;
H->bits = 0;
H->cmpmask = NULL;
if (H->failed)
{
nmod_mpoly_zero(Q, H->ctx);
nmod_mpoly_ts_clear(H->polyQ);
return 0;
}
else
{
nmod_mpoly_ts_struct * A = H->polyQ;
slong N = mpoly_words_per_exp(A->bits, H->ctx->minfo);
if (Q->exps)
flint_free(Q->exps);
if (Q->coeffs)
flint_free(Q->coeffs);
Q->exps = A->exps;
Q->coeffs = A->coeffs;
Q->bits = A->bits;
Q->length = A->length;
Q->coeffs_alloc = A->alloc;
Q->exps_alloc = N*A->alloc;
A->coeff_array[A->idx] = NULL;
A->exp_array[A->idx] = NULL;
nmod_mpoly_ts_clear(A);
return 1;
}
}
static void divides_heap_base_add_chunk(divides_heap_base_t H, divides_heap_chunk_t L)
{
L->next = NULL;
if (H->tail == NULL)
{
FLINT_ASSERT(H->head == NULL);
H->tail = L;
H->head = L;
}
else
{
divides_heap_chunk_struct * tail = H->tail;
FLINT_ASSERT(tail->next == NULL);
tail->next = L;
H->tail = L;
}
H->length++;
}
/*
A = D - (a stripe of B * C)
S->startidx and S->endidx are assumed to be correct
that is, we expect and successive calls to keep
B decreasing
C the same
*/
static void _nmod_mpoly_mulsub_stripe1(
nmod_mpoly_t A,
const mp_limb_t * Dcoeff, const ulong * Dexp, slong Dlen,
const mp_limb_t * Bcoeff, const ulong * Bexp, slong Blen,
const mp_limb_t * Ccoeff, const ulong * Cexp, slong Clen,
const nmod_mpoly_stripe_t S)
{
int upperclosed;
slong startidx, endidx;
ulong prev_startidx;
ulong maskhi = S->cmpmask[0];
ulong emax = S->emax[0];
ulong emin = S->emin[0];
slong i, j;
slong next_loc = Blen + 4; /* something bigger than heap can ever be */
slong heap_len = 1; /* heap zero index unused */
mpoly_heap1_s * heap;
mpoly_heap_t * chain;
slong * store, * store_base;
mpoly_heap_t * x;
slong Di;
slong Alen;
mp_limb_t * Acoeff = A->coeffs;
ulong * Aexp = A->exps;
ulong acc0, acc1, acc2, pp0, pp1;
ulong exp;
slong * ends;
ulong texp;
slong * hind;
FLINT_ASSERT(S->N == 1);
i = 0;
hind = (slong *)(S->big_mem + i);
i += Blen*sizeof(slong);
ends = (slong *)(S->big_mem + i);
i += Blen*sizeof(slong);
store = store_base = (slong *) (S->big_mem + i);
i += 2*Blen*sizeof(slong);
heap = (mpoly_heap1_s *)(S->big_mem + i);
i += (Blen + 1)*sizeof(mpoly_heap1_s);
chain = (mpoly_heap_t *)(S->big_mem + i);
i += Blen*sizeof(mpoly_heap_t);
FLINT_ASSERT(i <= S->big_mem_alloc);
startidx = *S->startidx;
endidx = *S->endidx;
upperclosed = S->upperclosed;
emax = S->emax[0];
emin = S->emin[0];
/* put all the starting nodes on the heap */
prev_startidx = -UWORD(1);
for (i = 0; i < Blen; i++)
{
if (startidx < Clen)
{
texp = Bexp[i] + Cexp[startidx];
FLINT_ASSERT(mpoly_monomial_cmp1(emax, texp, maskhi) > -upperclosed);
}
while (startidx > 0)
{
texp = Bexp[i] + Cexp[startidx - 1];
if (mpoly_monomial_cmp1(emax, texp, maskhi) <= -upperclosed)
{
break;
}
startidx--;
}
if (endidx < Clen)
{
texp = Bexp[i] + Cexp[endidx];
FLINT_ASSERT(mpoly_monomial_cmp1(emin, texp, maskhi) > 0);
}
while (endidx > 0)
{
texp = Bexp[i] + Cexp[endidx - 1];
if (mpoly_monomial_cmp1(emin, texp, maskhi) <= 0)
{
break;
}
endidx--;
}
ends[i] = endidx;
hind[i] = 2*startidx + 1;
if ( (startidx < endidx)
&& (((ulong)startidx) < prev_startidx)
)
{
x = chain + i;
x->i = i;
x->j = startidx;
x->next = NULL;
hind[x->i] = 2*(x->j + 1) + 0;
_mpoly_heap_insert1(heap, Bexp[x->i] + Cexp[x->j], x,
&next_loc, &heap_len, maskhi);
}
prev_startidx = startidx;
}
/* set the indices for the next time mul is called */
*S->startidx = startidx;
*S->endidx = endidx;
Alen = 0;
Di = 0;
while (heap_len > 1)
{
exp = heap[1].exp;
while (Di < Dlen && mpoly_monomial_gt1(Dexp[Di], exp, maskhi))
{
_nmod_mpoly_fit_length(&Acoeff, &A->coeffs_alloc,
&Aexp, &A->exps_alloc, 1, Alen + 1);
Acoeff[Alen] = Dcoeff[Di];
Aexp[Alen] = Dexp[Di];
Alen++;
Di++;
}
_nmod_mpoly_fit_length(&Acoeff, &A->coeffs_alloc,
&Aexp, &A->exps_alloc, 1, Alen + 1);
Aexp[Alen] = exp;
acc0 = acc1 = acc2 = 0;
if (Di < Dlen && Dexp[Di] == exp)
{
acc0 = S->mod.n - Dcoeff[Di];
Di++;
}
do
{
x = _mpoly_heap_pop1(heap, &heap_len, maskhi);
hind[x->i] |= WORD(1);
*store++ = x->i;
*store++ = x->j;
umul_ppmm(pp1, pp0, Bcoeff[x->i], Ccoeff[x->j]);
add_sssaaaaaa(acc2, acc1, acc0, acc2, acc1, acc0, WORD(0), pp1, pp0);
while ((x = x->next) != NULL)
{
hind[x->i] |= WORD(1);
*store++ = x->i;
*store++ = x->j;
umul_ppmm(pp1, pp0, Bcoeff[x->i], Ccoeff[x->j]);
add_sssaaaaaa(acc2, acc1, acc0, acc2, acc1, acc0, WORD(0), pp1, pp0);
}
} while (heap_len > 1 && heap[1].exp == exp);
NMOD_RED3(Acoeff[Alen], acc2, acc1, acc0, S->mod);
if (Acoeff[Alen] != 0)
{
Acoeff[Alen] = S->mod.n - Acoeff[Alen];
Alen++;
}
/* process nodes taken from the heap */
while (store > store_base)
{
j = *--store;
i = *--store;
/* should we go right? */
if ( (i + 1 < Blen)
&& (j + 0 < ends[i + 1])
&& (hind[i + 1] == 2*j + 1)
)
{
x = chain + i + 1;
x->i = i + 1;
x->j = j;
x->next = NULL;
hind[x->i] = 2*(x->j + 1) + 0;
_mpoly_heap_insert1(heap, Bexp[x->i] + Cexp[x->j], x,
&next_loc, &heap_len, maskhi);
}
/* should we go up? */
if ( (j + 1 < ends[i + 0])
&& ((hind[i] & 1) == 1)
&& ( (i == 0)
|| (hind[i - 1] >= 2*(j + 2) + 1)
)
)
{
x = chain + i;
x->i = i;
x->j = j + 1;
x->next = NULL;
hind[x->i] = 2*(x->j + 1) + 0;
_mpoly_heap_insert1(heap, Bexp[x->i] + Cexp[x->j], x,
&next_loc, &heap_len, maskhi);
}
}
}
FLINT_ASSERT(Di <= Dlen);
if (Di < Dlen)
{
_nmod_mpoly_fit_length(&Acoeff, &A->coeffs_alloc,
&Aexp, &A->exps_alloc, 1, Alen + Dlen - Di);
flint_mpn_copyi(Acoeff + Alen, Dcoeff + Di, Dlen - Di);
mpoly_copy_monomials(Aexp + 1*Alen, Dexp + 1*Di, Dlen - Di, 1);
Alen += Dlen - Di;
}
A->coeffs = Acoeff;
A->exps = Aexp;
A->length = Alen;
}
static void _nmod_mpoly_mulsub_stripe(
nmod_mpoly_t A,
const mp_limb_t * Dcoeff, const ulong * Dexp, slong Dlen,
const mp_limb_t * Bcoeff, const ulong * Bexp, slong Blen,
const mp_limb_t * Ccoeff, const ulong * Cexp, slong Clen,
const nmod_mpoly_stripe_t S)
{
int upperclosed;
slong startidx, endidx;
ulong prev_startidx;
ulong * emax = S->emax;
ulong * emin = S->emin;
slong N = S->N;
slong i, j;
slong next_loc = Blen + 4; /* something bigger than heap can ever be */
slong heap_len = 1; /* heap zero index unused */
mpoly_heap_s * heap;
mpoly_heap_t * chain;
slong * store, * store_base;
mpoly_heap_t * x;
slong Di;
slong Alen;
mp_limb_t * Acoeff = A->coeffs;
ulong * Aexp = A->exps;
ulong acc0, acc1, acc2, pp0, pp1;
ulong * exp, * exps;
ulong ** exp_list;
slong exp_next;
slong * ends;
ulong * texp;
slong * hind;
i = 0;
hind = (slong *)(S->big_mem + i);
i += Blen*sizeof(slong);
ends = (slong *)(S->big_mem + i);
i += Blen*sizeof(slong);
store = store_base = (slong *) (S->big_mem + i);
i += 2*Blen*sizeof(slong);
heap = (mpoly_heap_s *)(S->big_mem + i);
i += (Blen + 1)*sizeof(mpoly_heap_s);
chain = (mpoly_heap_t *)(S->big_mem + i);
i += Blen*sizeof(mpoly_heap_t);
exps = (ulong *)(S->big_mem + i);
i += Blen*N*sizeof(ulong);
exp_list = (ulong **)(S->big_mem + i);
i += Blen*sizeof(ulong *);
texp = (ulong *)(S->big_mem + i);
i += N*sizeof(ulong);
FLINT_ASSERT(i <= S->big_mem_alloc);
exp_next = 0;
startidx = *S->startidx;
endidx = *S->endidx;
upperclosed = S->upperclosed;
for (i = 0; i < Blen; i++)
exp_list[i] = exps + i*N;
/* put all the starting nodes on the heap */
prev_startidx = -UWORD(1);
for (i = 0; i < Blen; i++)
{
if (startidx < Clen)
{
mpoly_monomial_add_mp(texp, Bexp + N*i, Cexp + N*startidx, N);
FLINT_ASSERT(mpoly_monomial_cmp(emax, texp, N, S->cmpmask) > -upperclosed);
}
while (startidx > 0)
{
mpoly_monomial_add_mp(texp, Bexp + N*i, Cexp + N*(startidx - 1), N);
if (mpoly_monomial_cmp(emax, texp, N, S->cmpmask) <= -upperclosed)
{
break;
}
startidx--;
}
if (endidx < Clen)
{
mpoly_monomial_add_mp(texp, Bexp + N*i, Cexp + N*endidx, N);
FLINT_ASSERT(mpoly_monomial_cmp(emin, texp, N, S->cmpmask) > 0);
}
while (endidx > 0)
{
mpoly_monomial_add_mp(texp, Bexp + N*i, Cexp + N*(endidx - 1), N);
if (mpoly_monomial_cmp(emin, texp, N, S->cmpmask) <= 0)
{
break;
}
endidx--;
}
ends[i] = endidx;
hind[i] = 2*startidx + 1;
if ( (startidx < endidx)
&& (((ulong)startidx) < prev_startidx)
)
{
x = chain + i;
x->i = i;
x->j = startidx;
x->next = NULL;
hind[x->i] = 2*(x->j + 1) + 0;
mpoly_monomial_add_mp(exp_list[exp_next], Bexp + N*x->i, Cexp + N*x->j, N);
if (!_mpoly_heap_insert(heap, exp_list[exp_next++], x,
&next_loc, &heap_len, N, S->cmpmask))
exp_next--;
}
prev_startidx = startidx;
}
*S->startidx = startidx;
*S->endidx = endidx;
Alen = 0;
Di = 0;
while (heap_len > 1)
{
exp = heap[1].exp;
while (Di < Dlen && mpoly_monomial_gt(Dexp + N*Di, exp, N, S->cmpmask))
{
_nmod_mpoly_fit_length(&Acoeff, &A->coeffs_alloc,
&Aexp, &A->exps_alloc, N, Alen + 1);
mpoly_monomial_set(Aexp + N*Alen, Dexp + N*Di, N);
Acoeff[Alen] = Dcoeff[Di];
Alen++;
Di++;
}
_nmod_mpoly_fit_length(&Acoeff, &A->coeffs_alloc,
&Aexp, &A->exps_alloc, N, Alen + 1);
mpoly_monomial_set(Aexp + N*Alen, exp, N);
acc0 = acc1 = acc2 = 0;
if (Di < Dlen && mpoly_monomial_equal(Dexp + N*Di, exp, N))
{
acc0 = S->mod.n - Dcoeff[Di];
Di++;
}
do
{
exp_list[--exp_next] = heap[1].exp;
x = _mpoly_heap_pop(heap, &heap_len, N, S->cmpmask);
hind[x->i] |= WORD(1);
*store++ = x->i;
*store++ = x->j;
umul_ppmm(pp1, pp0, Bcoeff[x->i], Ccoeff[x->j]);
add_sssaaaaaa(acc2, acc1, acc0, acc2, acc1, acc0, WORD(0), pp1, pp0);
while ((x = x->next) != NULL)
{
hind[x->i] |= WORD(1);
*store++ = x->i;
*store++ = x->j;
umul_ppmm(pp1, pp0, Bcoeff[x->i], Ccoeff[x->j]);
add_sssaaaaaa(acc2, acc1, acc0, acc2, acc1, acc0, WORD(0), pp1, pp0);
}
} while (heap_len > 1 && mpoly_monomial_equal(heap[1].exp, exp, N));
NMOD_RED3(Acoeff[Alen], acc2, acc1, acc0, S->mod);
if (Acoeff[Alen] != 0)
{
Acoeff[Alen] = S->mod.n - Acoeff[Alen];
Alen++;
}
/* process nodes taken from the heap */
while (store > store_base)
{
j = *--store;
i = *--store;
/* should we go right? */
if ( (i + 1 < Blen)
&& (j + 0 < ends[i + 1])
&& (hind[i + 1] == 2*j + 1)
)
{
x = chain + i + 1;
x->i = i + 1;
x->j = j;
x->next = NULL;
hind[x->i] = 2*(x->j + 1) + 0;
mpoly_monomial_add_mp(exp_list[exp_next], Bexp + N*x->i, Cexp + N*x->j, N);
if (!_mpoly_heap_insert(heap, exp_list[exp_next++], x,
&next_loc, &heap_len, N, S->cmpmask))
exp_next--;
}
/* should we go up? */
if ( (j + 1 < ends[i + 0])
&& ((hind[i] & 1) == 1)
&& ( (i == 0)
|| (hind[i - 1] >= 2*(j + 2) + 1)
)
)
{
x = chain + i;
x->i = i;
x->j = j + 1;
x->next = NULL;
hind[x->i] = 2*(x->j + 1) + 0;
mpoly_monomial_add_mp(exp_list[exp_next], Bexp + N*x->i, Cexp + N*x->j, N);
if (!_mpoly_heap_insert(heap, exp_list[exp_next++], x,
&next_loc, &heap_len, N, S->cmpmask))
exp_next--;
}
}
}
FLINT_ASSERT(Di <= Dlen);
if (Di < Dlen)
{
_nmod_mpoly_fit_length(&Acoeff, &A->coeffs_alloc,
&Aexp, &A->exps_alloc, N, Alen + Dlen - Di);
flint_mpn_copyi(Acoeff + Alen, Dcoeff + Di, Dlen - Di);
mpoly_copy_monomials(Aexp + N*Alen, Dexp + N*Di, Dlen - Di, N);
Alen += Dlen - Di;
}
A->coeffs = Acoeff;
A->exps = Aexp;
A->length = Alen;
}
/*
Q = stripe of A/B (assume A != 0)
return Qlen = 0 if exact division is impossible
*/
static int _nmod_mpoly_divides_stripe1(
nmod_mpoly_t Q,
const mp_limb_t * Acoeff, const ulong * Aexp, slong Alen,
const mp_limb_t * Bcoeff, const ulong * Bexp, slong Blen,
const nmod_mpoly_stripe_t S)
{
flint_bitcnt_t bits = S->bits;
ulong emin = S->emin[0];
ulong cmpmask = S->cmpmask[0];
ulong texp;
int lt_divides;
slong i, j, s;
slong next_loc, heap_len;
mpoly_heap1_s * heap;
mpoly_heap_t * chain;
slong * store, * store_base;
mpoly_heap_t * x;
slong Qlen;
mp_limb_t * Qcoeff = Q->coeffs;
ulong * Qexp = Q->exps;
ulong exp;
mp_limb_t acc0, acc1, acc2, pp1, pp0;
ulong mask;
slong * hind;
FLINT_ASSERT(Alen > 0);
FLINT_ASSERT(Blen > 0);
FLINT_ASSERT(S->N == 1);
next_loc = Blen + 4; /* something bigger than heap can ever be */
i = 0;
hind = (slong *)(S->big_mem + i);
i += Blen*sizeof(slong);
store = store_base = (slong *) (S->big_mem + i);
i += 2*Blen*sizeof(slong);
heap = (mpoly_heap1_s *)(S->big_mem + i);
i += (Blen + 1)*sizeof(mpoly_heap1_s);
chain = (mpoly_heap_t *)(S->big_mem + i);
i += Blen*sizeof(mpoly_heap_t);
FLINT_ASSERT(i <= S->big_mem_alloc);
for (i = 0; i < Blen; i++)
hind[i] = 1;
mask = mpoly_overflow_mask_sp(bits);
Qlen = WORD(0);
/* s is the number of terms * (latest quotient) we should put into heap */
s = Blen;
/* insert (-1, 0, exp2[0]) into heap */
heap_len = 2;
x = chain + 0;
x->i = -WORD(1);
x->j = 0;
x->next = NULL;
heap[1].next = x;
HEAP_ASSIGN(heap[1], Aexp[0], x);
FLINT_ASSERT(mpoly_monomial_cmp1(Aexp[0], emin, cmpmask) >= 0);
while (heap_len > 1)
{
exp = heap[1].exp;
if (mpoly_monomial_overflows1(exp, mask))
goto not_exact_division;
FLINT_ASSERT(mpoly_monomial_cmp1(exp, emin, cmpmask) >= 0);
_nmod_mpoly_fit_length(&Qcoeff, &Q->coeffs_alloc,
&Qexp, &Q->exps_alloc, 1, Alen + 1);
lt_divides = mpoly_monomial_divides1(Qexp + Qlen, exp, Bexp[0], mask);
acc0 = acc1 = acc2 = 0;
do
{
x = _mpoly_heap_pop1(heap, &heap_len, cmpmask);
do
{
*store++ = x->i;
*store++ = x->j;
if (x->i == -WORD(1))
{
add_sssaaaaaa(acc2, acc1, acc0, acc2, acc1, acc0,
WORD(0), WORD(0), S->mod.n - Acoeff[x->j]);
}
else
{
hind[x->i] |= WORD(1);
umul_ppmm(pp1, pp0, Bcoeff[x->i], Qcoeff[x->j]);
add_sssaaaaaa(acc2, acc1, acc0, acc2, acc1, acc0, WORD(0), pp1, pp0);
}
} while ((x = x->next) != NULL);
} while (heap_len > 1 && heap[1].exp == exp);
NMOD_RED3(Qcoeff[Qlen], acc2, acc1, acc0, S->mod);
/* process nodes taken from the heap */
while (store > store_base)
{
j = *--store;
i = *--store;
if (i == -WORD(1))
{
/* take next dividend term */
if (j + 1 < Alen)
{
x = chain + 0;
x->i = i;
x->j = j + 1;
x->next = NULL;
FLINT_ASSERT(mpoly_monomial_cmp1(Aexp[x->j], emin, cmpmask) >= 0);
_mpoly_heap_insert1(heap, Aexp[x->j], x,
&next_loc, &heap_len, cmpmask);
}
}
else
{
/* should we go up */
if ( (i + 1 < Blen)
&& (hind[i + 1] == 2*j + 1)
)
{
x = chain + i + 1;
x->i = i + 1;
x->j = j;
x->next = NULL;
hind[x->i] = 2*(x->j + 1) + 0;
texp = Bexp[x->i] + Qexp[x->j];
if (mpoly_monomial_cmp1(texp, emin, cmpmask) >= 0)
{
_mpoly_heap_insert1(heap, texp, x,
&next_loc, &heap_len, cmpmask);
}
else
{
hind[x->i] |= 1;
}
}
/* should we go up? */
if (j + 1 == Qlen)
{
s++;
} else if ( ((hind[i] & 1) == 1)
&& ((i == 1) || (hind[i - 1] >= 2*(j + 2) + 1))
)
{
x = chain + i;
x->i = i;
x->j = j + 1;
x->next = NULL;
hind[x->i] = 2*(x->j + 1) + 0;
texp = Bexp[x->i] + Qexp[x->j];
if (mpoly_monomial_cmp1(texp, emin, cmpmask) >= 0)
{
_mpoly_heap_insert1(heap, texp, x,
&next_loc, &heap_len, cmpmask);
}
else
{
hind[x->i] |= 1;
}
}
}
}
Qcoeff[Qlen] = nmod_mul(Qcoeff[Qlen], S->lc_minus_inv, S->mod);
if (Qcoeff[Qlen] == 0)
{
continue;
}
if (!lt_divides)
{
goto not_exact_division;
}
if (s > 1)
{
i = 1;
x = chain + i;
x->i = i;
x->j = Qlen;
x->next = NULL;
hind[x->i] = 2*(x->j + 1) + 0;
texp = Bexp[x->i] + Qexp[x->j];
if (mpoly_monomial_cmp1(texp, emin, cmpmask) >= 0)
{
_mpoly_heap_insert1(heap, texp, x,
&next_loc, &heap_len, cmpmask);
}
else
{
hind[x->i] |= 1;
}
}
s = 1;
Qlen++;
}
Q->coeffs = Qcoeff;
Q->exps = Qexp;
Q->length = Qlen;
return 1;
not_exact_division:
Q->coeffs = Qcoeff;
Q->exps = Qexp;
Q->length = 0;
return 0;
}
static int _nmod_mpoly_divides_stripe(
nmod_mpoly_t Q,
const mp_limb_t * Acoeff, const ulong * Aexp, slong Alen,
const mp_limb_t * Bcoeff, const ulong * Bexp, slong Blen,
const nmod_mpoly_stripe_t S)
{
flint_bitcnt_t bits = S->bits;
slong N = S->N;
int lt_divides;
slong i, j, s;
slong next_loc, heap_len;
mpoly_heap_s * heap;
mpoly_heap_t * chain;
slong * store, * store_base;
mpoly_heap_t * x;
slong Qlen;
mp_limb_t * Qcoeff = Q->coeffs;
ulong * Qexp = Q->exps;
ulong * exp, * exps;
ulong ** exp_list;
slong exp_next;
mp_limb_t acc0, acc1, acc2, pp1, pp0;
ulong mask;
slong * hind;
FLINT_ASSERT(Alen > 0);
FLINT_ASSERT(Blen > 0);
next_loc = Blen + 4; /* something bigger than heap can ever be */
i = 0;
hind = (slong *) (S->big_mem + i);
i += Blen*sizeof(slong);
store = store_base = (slong *) (S->big_mem + i);
i += 2*Blen*sizeof(slong);
heap = (mpoly_heap_s *)(S->big_mem + i);
i += (Blen + 1)*sizeof(mpoly_heap_s);
chain = (mpoly_heap_t *)(S->big_mem + i);
i += Blen*sizeof(mpoly_heap_t);
exps = (ulong *)(S->big_mem + i);
i += Blen*N*sizeof(ulong);
exp_list = (ulong **)(S->big_mem + i);
i += Blen*sizeof(ulong *);
exp = (ulong *)(S->big_mem + i);
i += N*sizeof(ulong);
FLINT_ASSERT(i <= S->big_mem_alloc);
exp_next = 0;
for (i = 0; i < Blen; i++)
exp_list[i] = exps + i*N;
for (i = 0; i < Blen; i++)
hind[i] = 1;
mask = bits <= FLINT_BITS ? mpoly_overflow_mask_sp(bits) : 0;
Qlen = WORD(0);
/* s is the number of terms * (latest quotient) we should put into heap */
s = Blen;
/* insert (-1, 0, exp2[0]) into heap */
heap_len = 2;
x = chain + 0;
x->i = -WORD(1);
x->j = 0;
x->next = NULL;
heap[1].next = x;
heap[1].exp = exp_list[exp_next++];
FLINT_ASSERT(mpoly_monomial_cmp(Aexp + N*0, S->emin, N, S->cmpmask) >= 0);
mpoly_monomial_set(heap[1].exp, Aexp + N*0, N);
while (heap_len > 1)
{
_nmod_mpoly_fit_length(&Qcoeff, &Q->coeffs_alloc,
&Qexp, &Q->exps_alloc, N, Qlen + 1);
mpoly_monomial_set(exp, heap[1].exp, N);
if (bits <= FLINT_BITS)
{
if (mpoly_monomial_overflows(exp, N, mask))
goto not_exact_division;
lt_divides = mpoly_monomial_divides(Qexp + N*Qlen, exp, Bexp + N*0, N, mask);
}
else
{
if (mpoly_monomial_overflows_mp(exp, N, bits))
goto not_exact_division;
lt_divides = mpoly_monomial_divides_mp(Qexp + N*Qlen, exp, Bexp + N*0, N, bits);
}
FLINT_ASSERT(mpoly_monomial_cmp(exp, S->emin, N, S->cmpmask) >= 0);
acc0 = acc1 = acc2 = 0;
do {
exp_list[--exp_next] = heap[1].exp;
x = _mpoly_heap_pop(heap, &heap_len, N, S->cmpmask);
do {
*store++ = x->i;
*store++ = x->j;
if (x->i == -WORD(1))
{
add_sssaaaaaa(acc2, acc1, acc0, acc2, acc1, acc0,
WORD(0), WORD(0), S->mod.n - Acoeff[x->j]);
}
else
{
hind[x->i] |= WORD(1);
umul_ppmm(pp1, pp0, Bcoeff[x->i], Qcoeff[x->j]);
add_sssaaaaaa(acc2, acc1, acc0, acc2, acc1, acc0, WORD(0), pp1, pp0);
}
} while ((x = x->next) != NULL);
} while (heap_len > 1 && mpoly_monomial_equal(heap[1].exp, exp, N));
NMOD_RED3(Qcoeff[Qlen], acc2, acc1, acc0, S->mod);
/* process nodes taken from the heap */
while (store > store_base)
{
j = *--store;
i = *--store;
if (i == -WORD(1))
{
/* take next dividend term */
if (j + 1 < Alen)
{
x = chain + 0;
x->i = i;
x->j = j + 1;
x->next = NULL;
mpoly_monomial_set(exp_list[exp_next], Aexp + x->j*N, N);
FLINT_ASSERT(mpoly_monomial_cmp(exp_list[exp_next], S->emin, N, S->cmpmask) >= 0);
exp_next += _mpoly_heap_insert(heap, exp_list[exp_next], x,
&next_loc, &heap_len, N, S->cmpmask);
}
}
else
{
/* should we go up */
if ( (i + 1 < Blen)
&& (hind[i + 1] == 2*j + 1)
)
{
x = chain + i + 1;
x->i = i + 1;
x->j = j;
x->next = NULL;
hind[x->i] = 2*(x->j + 1) + 0;
mpoly_monomial_add_mp(exp_list[exp_next], Bexp + N*x->i,
Qexp + N*x->j, N);
if (mpoly_monomial_cmp(exp_list[exp_next], S->emin, N, S->cmpmask) >= 0)
{
exp_next += _mpoly_heap_insert(heap, exp_list[exp_next], x,
&next_loc, &heap_len, N, S->cmpmask);
}
else
{
hind[x->i] |= 1;
}
}
/* should we go up? */
if (j + 1 == Qlen)
{
s++;
} else if ( ((hind[i] & 1) == 1)
&& ((i == 1) || (hind[i - 1] >= 2*(j + 2) + 1))
)
{
x = chain + i;
x->i = i;
x->j = j + 1;
x->next = NULL;
hind[x->i] = 2*(x->j + 1) + 0;
mpoly_monomial_add_mp(exp_list[exp_next], Bexp + N*x->i,
Qexp + N*x->j, N);
if (mpoly_monomial_cmp(exp_list[exp_next], S->emin, N, S->cmpmask) >= 0)
{
exp_next += _mpoly_heap_insert(heap, exp_list[exp_next], x,
&next_loc, &heap_len, N, S->cmpmask);
}
else
{
hind[x->i] |= 1;
}
}
}
}
Qcoeff[Qlen] = nmod_mul(Qcoeff[Qlen], S->lc_minus_inv, S->mod);
if (Qcoeff[Qlen] == 0)
{
continue;
}
if (!lt_divides)
{
goto not_exact_division;
}
if (s > 1)
{
i = 1;
x = chain + i;
x->i = i;
x->j = Qlen;
x->next = NULL;
hind[x->i] = 2*(x->j + 1) + 0;
mpoly_monomial_add_mp(exp_list[exp_next], Bexp + N*x->i, Qexp + N*x->j, N);
if (mpoly_monomial_cmp(exp_list[exp_next], S->emin, N, S->cmpmask) >= 0)
{
exp_next += _mpoly_heap_insert(heap, exp_list[exp_next], x,
&next_loc, &heap_len, N, S->cmpmask);
}
else
{
hind[x->i] |= 1;
}
}
s = 1;
Qlen++;
}
Q->coeffs = Qcoeff;
Q->exps = Qexp;
Q->length = Qlen;
return 1;
not_exact_division:
Q->coeffs = Qcoeff;
Q->exps = Qexp;
Q->length = 0;
return 0;
}
static slong chunk_find_exp(ulong * exp, slong a, const divides_heap_base_t H)
{
slong N = H->N;
slong b = H->polyA->length;
const ulong * Aexp = H->polyA->exps;
try_again:
FLINT_ASSERT(b >= a);
FLINT_ASSERT(a > 0);
FLINT_ASSERT(mpoly_monomial_cmp(Aexp + N*(a - 1), exp, N, H->cmpmask) >= 0);
FLINT_ASSERT(b >= H->polyA->length
|| mpoly_monomial_cmp(Aexp + N*b, exp, N, H->cmpmask) < 0);
if (b - a < 5)
{
slong i = a;
while (i < b
&& mpoly_monomial_cmp(Aexp + N*i, exp, N, H->cmpmask) >= 0)
{
i++;
}
return i;
}
else
{
slong c = a + (b - a)/2;
if (mpoly_monomial_cmp(Aexp + N*c, exp, N, H->cmpmask) < 0)
{
b = c;
}
else
{
a = c;
}
goto try_again;
}
}
static void stripe_fit_length(nmod_mpoly_stripe_struct * S, slong new_len)
{
slong N = S->N;
slong new_alloc;
new_alloc = 0;
if (N == 1)
{
new_alloc += new_len*sizeof(slong);
new_alloc += new_len*sizeof(slong);
new_alloc += 2*new_len*sizeof(slong);
new_alloc += (new_len + 1)*sizeof(mpoly_heap1_s);
new_alloc += new_len*sizeof(mpoly_heap_t);
}
else
{
new_alloc += new_len*sizeof(slong);
new_alloc += new_len*sizeof(slong);
new_alloc += 2*new_len*sizeof(slong);
new_alloc += (new_len + 1)*sizeof(mpoly_heap_s);
new_alloc += new_len*sizeof(mpoly_heap_t);
new_alloc += new_len*N*sizeof(ulong);
new_alloc += new_len*sizeof(ulong *);
new_alloc += N*sizeof(ulong);
}
if (S->big_mem_alloc >= new_alloc)
{
return;
}
new_alloc = FLINT_MAX(new_alloc, S->big_mem_alloc + S->big_mem_alloc/4);
S->big_mem_alloc = new_alloc;
if (S->big_mem != NULL)
{
S->big_mem = (char *) flint_realloc(S->big_mem, new_alloc);
}
else
{
S->big_mem = (char *) flint_malloc(new_alloc);
}
}
static void chunk_mulsub(worker_arg_t W, divides_heap_chunk_t L, slong q_prev_length)
{
divides_heap_base_struct * H = W->H;
slong N = H->N;
nmod_mpoly_struct * C = L->polyC;
const nmod_mpoly_struct * B = H->polyB;
const nmod_mpoly_struct * A = H->polyA;
nmod_mpoly_ts_struct * Q = H->polyQ;
nmod_mpoly_struct * T1 = W->polyT1;
nmod_mpoly_stripe_struct * S = W->S;
S->startidx = &L->startidx;
S->endidx = &L->endidx;
S->emin = L->emin;
S->emax = L->emax;
S->upperclosed = L->upperclosed;
FLINT_ASSERT(S->N == N);
stripe_fit_length(S, q_prev_length - L->mq);
if (L->Cinited)
{
if (N == 1)
{
_nmod_mpoly_mulsub_stripe1(T1,
C->coeffs, C->exps, C->length,
Q->coeffs + L->mq, Q->exps + N*L->mq, q_prev_length - L->mq,
B->coeffs, B->exps, B->length, S);
}
else
{
_nmod_mpoly_mulsub_stripe(T1,
C->coeffs, C->exps, C->length,
Q->coeffs + L->mq, Q->exps + N*L->mq, q_prev_length - L->mq,
B->coeffs, B->exps, B->length, S);
}
nmod_mpoly_swap(C, T1, H->ctx);
}
else
{
slong startidx, stopidx;
if (L->upperclosed)
{
startidx = 0;
stopidx = chunk_find_exp(L->emin, 1, H);
}
else
{
startidx = chunk_find_exp(L->emax, 1, H);
stopidx = chunk_find_exp(L->emin, startidx, H);
}
L->Cinited = 1;
nmod_mpoly_init3(C, 16 + stopidx - startidx, H->bits, H->ctx); /*any is OK*/
if (N == 1)
{
_nmod_mpoly_mulsub_stripe1(C,
A->coeffs + startidx, A->exps + N*startidx, stopidx - startidx,
Q->coeffs + L->mq, Q->exps + N*L->mq, q_prev_length - L->mq,
B->coeffs, B->exps, B->length, S);
}
else
{
_nmod_mpoly_mulsub_stripe(C,
A->coeffs + startidx, A->exps + N*startidx, stopidx - startidx,
Q->coeffs + L->mq, Q->exps + N*L->mq, q_prev_length - L->mq,
B->coeffs, B->exps, B->length, S);
}
}
L->mq = q_prev_length;
}
static void trychunk(worker_arg_t W, divides_heap_chunk_t L)
{
divides_heap_base_struct * H = W->H;
slong i;
slong N = H->N;
nmod_mpoly_struct * C = L->polyC;
slong q_prev_length;
ulong mask;
const nmod_mpoly_struct * B = H->polyB;
const nmod_mpoly_struct * A = H->polyA;
nmod_mpoly_ts_struct * Q = H->polyQ;
nmod_mpoly_struct * T2 = W->polyT2;
mask = 0;
for (i = 0; i < FLINT_BITS/H->bits; i++)
mask = (mask << H->bits) + (UWORD(1) << (H->bits - 1));
/* return if this section has already finished processing */
if (L->mq < 0)
{
return;
}
/* process more quotient terms if available */
q_prev_length = Q->length;
if (q_prev_length > L->mq)
{
if (L->producer == 0 && q_prev_length - L->mq < 20)
return;
#if PROFILE_THIS
vec_slong_push_back(W->time_data, 4*L->idx + 0);
vec_slong_push_back(W->time_data, timeit_query_wall(H->timer));
#endif
chunk_mulsub(W, L, q_prev_length);
#if PROFILE_THIS
vec_slong_push_back(W->time_data, 4*L->idx + 1);
vec_slong_push_back(W->time_data, timeit_query_wall(H->timer));
#endif
}
if (L->producer == 1)
{
divides_heap_chunk_struct * next;
mp_limb_t * Rcoeff;
ulong * Rexp;
slong Rlen;
#if PROFILE_THIS
vec_slong_push_back(W->time_data, 4*L->idx + 2);
vec_slong_push_back(W->time_data, timeit_query_wall(H->timer));
#endif
/* process the remaining quotient terms */
q_prev_length = Q->length;
if (q_prev_length > L->mq)
{
chunk_mulsub(W, L, q_prev_length);
}
/* find location of remaining terms */
if (L->Cinited)
{
Rlen = C->length;
Rexp = C->exps;
Rcoeff = C->coeffs;
}
else
{
slong startidx, stopidx;
if (L->upperclosed)
{
startidx = 0;
stopidx = chunk_find_exp(L->emin, 1, H);
}
else
{
startidx = chunk_find_exp(L->emax, 1, H);
stopidx = chunk_find_exp(L->emin, startidx, H);
}
Rlen = stopidx - startidx;
Rcoeff = A->coeffs + startidx;
Rexp = A->exps + N*startidx;
}
/* if we have remaining terms, add to quotient */
if (Rlen > 0)
{
int divides;
nmod_mpoly_stripe_struct * S = W->S;
S->startidx = &L->startidx;
S->endidx = &L->endidx;
S->emin = L->emin;
S->emax = L->emax;
S->upperclosed = L->upperclosed;
if (N == 1)
{
divides = _nmod_mpoly_divides_stripe1(T2, Rcoeff, Rexp, Rlen,
B->coeffs, B->exps, B->length, S);
}
else
{
divides = _nmod_mpoly_divides_stripe(T2, Rcoeff, Rexp, Rlen,
B->coeffs, B->exps, B->length, S);
}
if (!divides)
{
#if PROFILE_THIS
vec_slong_push_back(W->time_data, 4*L->idx + 3);
vec_slong_push_back(W->time_data, timeit_query_wall(H->timer));
#endif
H->failed = 1;
return;
}
else
{
nmod_mpoly_ts_append(H->polyQ, T2->coeffs, T2->exps, T2->length, N);
}
}
#if PROFILE_THIS
vec_slong_push_back(W->time_data, 4*L->idx + 3);
vec_slong_push_back(W->time_data, timeit_query_wall(H->timer));
#endif
next = L->next;
H->length--;
H->cur = next;
if (next != NULL)
{
next->producer = 1;
}
L->producer = 0;
L->mq = -1;
}
return;
}
static void worker_loop(void * varg)
{
worker_arg_struct * W = (worker_arg_struct *) varg;
divides_heap_base_struct * H = W->H;
nmod_mpoly_stripe_struct * S = W->S;
const nmod_mpoly_struct * B = H->polyB;
nmod_mpoly_struct * T1 = W->polyT1;
nmod_mpoly_struct * T2 = W->polyT2;
slong N = H->N;
slong Blen = B->length;
/* initialize stripe working memory */
S->N = N;
S->bits = H->bits;
S->ctx = H->ctx;
S->cmpmask = H->cmpmask;
S->big_mem_alloc = 0;
S->big_mem = NULL;
S->mod = H->ctx->mod;
S->lc_minus_inv = S->mod.n - H->lc_inv;
stripe_fit_length(S, Blen);
nmod_mpoly_init3(T1, 16, H->bits, H->ctx);
nmod_mpoly_init3(T2, 16, H->bits, H->ctx);
while (!H->failed)
{
divides_heap_chunk_struct * L;
L = H->cur;
if (L == NULL)
{
break;
}
while (L != NULL)
{
#if FLINT_USES_PTHREAD
pthread_mutex_lock(&H->mutex);
#endif
if (L->lock != -1)
{
L->lock = -1;
#if FLINT_USES_PTHREAD
pthread_mutex_unlock(&H->mutex);
#endif
trychunk(W, L);
#if FLINT_USES_PTHREAD
pthread_mutex_lock(&H->mutex);
#endif
L->lock = 0;
#if FLINT_USES_PTHREAD
pthread_mutex_unlock(&H->mutex);
#endif
break;
}
else
{
#if FLINT_USES_PTHREAD
pthread_mutex_unlock(&H->mutex);
#endif
}
L = L->next;
}
}
nmod_mpoly_clear(T1, H->ctx);
nmod_mpoly_clear(T2, H->ctx);
flint_free(S->big_mem);
return;
}
/*
return 1 if quotient is exact.
The leading coefficient of B should be invertible.
*/
int _nmod_mpoly_divides_heap_threaded_pool(
nmod_mpoly_t Q,
const nmod_mpoly_t A,
const nmod_mpoly_t B,
const nmod_mpoly_ctx_t ctx,
const thread_pool_handle * handles,
slong num_handles)
{
ulong mask;
int divides;
fmpz_mpoly_ctx_t zctx;
fmpz_mpoly_t S;
slong i, k, N;
flint_bitcnt_t exp_bits;
ulong * cmpmask;
ulong * Aexp, * Bexp;
int freeAexp, freeBexp;
worker_arg_struct * worker_args;
mp_limb_t qcoeff;
ulong * texps, * qexps;
divides_heap_base_t H;
#if PROFILE_THIS
slong idx = 0;
#endif
TMP_INIT;
#if !FLINT_KNOW_STRONG_ORDER
return nmod_mpoly_divides_monagan_pearce(Q, A, B, ctx);
#endif
if (B->length < 2 || A->length < 2)
{
return nmod_mpoly_divides_monagan_pearce(Q, A, B, ctx);
}
TMP_START;
exp_bits = MPOLY_MIN_BITS;
exp_bits = FLINT_MAX(exp_bits, A->bits);
exp_bits = FLINT_MAX(exp_bits, B->bits);
exp_bits = mpoly_fix_bits(exp_bits, ctx->minfo);
N = mpoly_words_per_exp(exp_bits, ctx->minfo);
cmpmask = (ulong*) TMP_ALLOC(N*sizeof(ulong));
mpoly_get_cmpmask(cmpmask, N, exp_bits, ctx->minfo);
/* ensure input exponents packed to same size as output exponents */
Aexp = A->exps;
freeAexp = 0;
if (exp_bits > A->bits)
{
freeAexp = 1;
Aexp = (ulong *) flint_malloc(N*A->length*sizeof(ulong));
mpoly_repack_monomials(Aexp, exp_bits, A->exps, A->bits,
A->length, ctx->minfo);
}
Bexp = B->exps;
freeBexp = 0;
if (exp_bits > B->bits)
{
freeBexp = 1;
Bexp = (ulong *) flint_malloc(N*B->length*sizeof(ulong));
mpoly_repack_monomials(Bexp, exp_bits, B->exps, B->bits,
B->length, ctx->minfo);
}
fmpz_mpoly_ctx_init(zctx, ctx->minfo->nvars, ctx->minfo->ord);
fmpz_mpoly_init(S, zctx);
if (mpoly_divides_select_exps(S, zctx, num_handles,
Aexp, A->length, Bexp, B->length, exp_bits))
{
divides = 0;
nmod_mpoly_zero(Q, ctx);
goto cleanup1;
}
/*
At this point A and B both have at least two terms and the exponent
selection did not give an easy exit. Since we are possibly holding
threads, we should try to not throw, so the leading coefficient should
already have been checked for invertibility.
*/
divides_heap_base_init(H);
qcoeff = n_gcdinv(&H->lc_inv, B->coeffs[0], ctx->mod.n);
FLINT_ASSERT(qcoeff == 1); /* gcd should be one */
H->polyA->coeffs = A->coeffs;
H->polyA->exps = Aexp;
H->polyA->bits = exp_bits;
H->polyA->length = A->length;
H->polyA->coeffs_alloc = A->coeffs_alloc;
H->polyA->exps_alloc = A->exps_alloc;
H->polyB->coeffs = B->coeffs;
H->polyB->exps = Bexp;
H->polyB->bits = exp_bits;
H->polyB->length = B->length;
H->polyB->coeffs_alloc = B->coeffs_alloc;
H->polyB->exps_alloc = B->coeffs_alloc;
H->ctx = ctx;
H->bits = exp_bits;
H->N = N;
H->cmpmask = cmpmask;
H->failed = 0;
for (i = 0; i + 1 < S->length; i++)
{
divides_heap_chunk_struct * L;
L = (divides_heap_chunk_struct *) flint_malloc(
sizeof(divides_heap_chunk_struct));
L->ma = 0;
L->mq = 0;
L->emax = S->exps + N*i;
L->emin = S->exps + N*(i + 1);
L->upperclosed = 0;
L->startidx = B->length;
L->endidx = B->length;
L->producer = 0;
L->Cinited = 0;
L->lock = -2;
#if PROFILE_THIS
L->idx = idx++;
#endif
divides_heap_base_add_chunk(H, L);
}
H->head->upperclosed = 1;
H->head->producer = 1;
H->cur = H->head;
/* generate at least the first quotient terms */
texps = (ulong *) TMP_ALLOC(N*sizeof(ulong));
qexps = (ulong *) TMP_ALLOC(N*sizeof(ulong));
mpoly_monomial_sub_mp(qexps + N*0, Aexp + N*0, Bexp + N*0, N);
qcoeff = nmod_mul(H->lc_inv, A->coeffs[0], ctx->mod);
nmod_mpoly_ts_init(H->polyQ, &qcoeff, qexps, 1, H->bits, H->N);
mpoly_monomial_add_mp(texps, qexps + N*0, Bexp + N*1, N);
mask = 0;
for (i = 0; i < FLINT_BITS/exp_bits; i++)
mask = (mask << exp_bits) + (UWORD(1) << (exp_bits - 1));
k = 1;
while (k < A->length && mpoly_monomial_gt(Aexp + N*k, texps, N, cmpmask))
{
int lt_divides;
if (exp_bits <= FLINT_BITS)
lt_divides = mpoly_monomial_divides(qexps, Aexp + N*k,
Bexp + N*0, N, mask);
else
lt_divides = mpoly_monomial_divides_mp(qexps, Aexp + N*k,
Bexp + N*0, N, exp_bits);
if (!lt_divides)
{
H->failed = 1;
break;
}
qcoeff = nmod_mul(H->lc_inv, A->coeffs[k], ctx->mod);
nmod_mpoly_ts_append(H->polyQ, &qcoeff, qexps, 1, H->N);
k++;
}
/* start the workers */
#if FLINT_USES_PTHREAD
pthread_mutex_init(&H->mutex, NULL);
#endif
worker_args = (worker_arg_struct *) flint_malloc((num_handles + 1)
*sizeof(worker_arg_t));
#if PROFILE_THIS
for (i = 0; i < num_handles + 1; i++)
{
vec_slong_init((worker_args + i)->time_data);
}
timeit_start(H->timer);
#endif
for (i = 0; i < num_handles; i++)
{
(worker_args + i)->H = H;
thread_pool_wake(global_thread_pool, handles[i], 0,
worker_loop, worker_args + i);
}
(worker_args + num_handles)->H = H;
worker_loop(worker_args + num_handles);
for (i = 0; i < num_handles; i++)
thread_pool_wait(global_thread_pool, handles[i]);
#if PROFILE_THIS
timeit_stop(H->timer);
flint_printf("data = [");
for (i = 0; i < num_handles + 1; i++)
{
flint_printf("[%wd,", i);
vec_slong_print((worker_args + i)->time_data);
flint_printf("],\n");
vec_slong_clear((worker_args + i)->time_data);
}
flint_printf("%wd]\n", H->timer->wall);
#endif
flint_free(worker_args);
#if FLINT_USES_PTHREAD
pthread_mutex_destroy(&H->mutex);
#endif
divides = divides_heap_base_clear(Q, H);
cleanup1:
fmpz_mpoly_clear(S, zctx);
fmpz_mpoly_ctx_clear(zctx);
if (freeAexp)
flint_free(Aexp);
if (freeBexp)
flint_free(Bexp);
TMP_END;
return divides;
}
int nmod_mpoly_divides_heap_threaded(
nmod_mpoly_t Q,
const nmod_mpoly_t A,
const nmod_mpoly_t B,
const nmod_mpoly_ctx_t ctx)
{
thread_pool_handle * handles;
slong num_handles;
int divides;
slong thread_limit = A->length/32;
if (B->length == 0)
{
if (A->length == 0 || nmod_mpoly_ctx_modulus(ctx) == 1)
{
nmod_mpoly_set(Q, A, ctx);
return 1;
}
else
{
flint_throw(FLINT_DIVZERO, "nmod_mpoly_divides_heap_threaded: divide by zero");
}
}
if (B->length < 2 || A->length < 2)
{
if (A->length == 0)
{
nmod_mpoly_zero(Q, ctx);
return 1;
}
return nmod_mpoly_divides_monagan_pearce(Q, A, B, ctx);
}
if (1 != n_gcd(B->coeffs[0], ctx->mod.n))
{
flint_throw(FLINT_IMPINV, "nmod_mpoly_divides_heap_threaded: Cannot invert leading coefficient");
}
num_handles = flint_request_threads(&handles, thread_limit);
divides = _nmod_mpoly_divides_heap_threaded_pool(Q, A, B, ctx,
handles, num_handles);
flint_give_back_threads(handles, num_handles);
return divides;
}
| /*
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/>.
*/ |
CSSCPA_filter.c |
#include <cio_commandline.h>
#include <cex_csscpa.h>
#include <stdio.h>
#include <e_version.h>
/*---------------------------------------------------------------------*/
/* Data types */
/*---------------------------------------------------------------------*/
#define NAME "CSSCPA_filter"
typedef enum
{
OPT_NOOPT=0,
OPT_HELP,
OPT_VERSION,
OPT_VERBOSE,
OPT_OUTPUT,
OPT_SILENT,
OPT_OUTPUTLEVEL,
OPT_RANT
}OptionCodes;
/*---------------------------------------------------------------------*/
/* Global Variables */
/*---------------------------------------------------------------------*/
OptCell opts[] =
{
{OPT_HELP,
'h', "help",
NoArg, NULL,
"Print a short description of program usage and options."},
{OPT_VERSION,
'\0', "version",
NoArg, NULL,
"Print the version number of the program."},
{OPT_VERBOSE,
'v', "verbose",
OptArg, "1",
"Verbose comments on the progress of the program."},
{OPT_OUTPUT,
'o', "output-file",
ReqArg, NULL,
"Redirect output into the named file."},
{OPT_SILENT,
's', "silent",
NoArg, NULL,
"Equivalent to --output-level=0."},
{OPT_OUTPUTLEVEL,
'l', "output-level",
ReqArg, NULL,
"Select an output level, greater values imply more verbose"
" output. At the moment, level 0 only prints the result of each"
" statement, and level 1 also prints what happens to each"
" clause."},
{OPT_RANT,
'r', "rant-about-input-buffering",
OptArg, "666",
"Tell the program how much you hate to include the "
"'Please'-sequence in the input. The optional argument is the "
" rant-intensity."},
{OPT_NOOPT,
'\0', NULL,
NoArg, NULL,
NULL}
};
char *outname = NULL;
bool app_encode = false;
/*---------------------------------------------------------------------*/
/* Forward Declarations */
/*---------------------------------------------------------------------*/
CLState_p process_options(int argc, char* argv[]);
void print_help(FILE* out);
/*---------------------------------------------------------------------*/
/* Internal Functions */
/*---------------------------------------------------------------------*/
int main(int argc, char* argv[])
{
Scanner_p in;
CLState_p state;
CSSCPAState_p procstate;
int i;
assert(argv[0]);
InitIO(NAME);
state = process_options(argc, argv);
OpenGlobalOut(outname);
OutputFormat = TPTPFormat;
if(state->argc == 0)
{
CLStateInsertArg(state, "-");
}
procstate = CSSCPAStateAlloc();
for(i=0; state->argv[i]; i++)
{
in = CreateScanner(StreamTypeFile, state->argv[i], true, NULL,true);
ScannerSetFormat(in, TSTPFormat);
CSSCPALoop(in, procstate);
DestroyScanner(in);
}
fprintf(GlobalOut, "\n# Resulting clause set:\n");
ClauseSetTSTPPrint(GlobalOut, procstate->pos_units, true);
ClauseSetTSTPPrint(GlobalOut, procstate->neg_units, true);
ClauseSetTSTPPrint(GlobalOut, procstate->non_units, true);
CSSCPAStateFree(procstate);
CLStateFree(state);
fflush(GlobalOut);
OutClose(GlobalOut);
ExitIO();
#ifdef CLB_MEMORY_DEBUG
MemFlushFreeList();
MemDebugPrintStats(stdout);
#endif
return 0;
}
/*-----------------------------------------------------------------------
//
// Function: process_options()
//
// Read and process the command line option, return (the pointer to)
// a CLState object containing the remaining arguments.
//
// Global Variables:
//
// Side Effects : Sets variables, may terminate with program
// description if option -h or --help was present
//
/----------------------------------------------------------------------*/
CLState_p process_options(int argc, char* argv[])
{
Opt_p handle;
CLState_p state;
char* arg;
state = CLStateAlloc(argc,argv);
while((handle = CLStateGetOpt(state, &arg, opts)))
{
switch(handle->option_code)
{
case OPT_VERBOSE:
Verbose = CLStateGetIntArg(handle, arg);
break;
case OPT_HELP:
print_help(stdout);
exit(NO_ERROR);
case OPT_VERSION:
printf(NAME " " VERSION "\n");
exit(NO_ERROR);
case OPT_OUTPUT:
outname = arg;
break;
case OPT_SILENT:
OutputLevel = 0;
break;
case OPT_OUTPUTLEVEL:
OutputLevel = CLStateGetIntArg(handle, arg);
if(OutputLevel>1)
{
Error("Option -l (--output-level) accepts only 0 or 1"
"for CSSCPA_filter",
USAGE_ERROR);
}
break;
case OPT_RANT:
if(CLStateGetIntArg(handle, arg)!=0)
{
fprintf(stderr, "Improve it yourself, mate. The code is"
" free.\n");
}
else
{
fprintf(stderr, "You call that a rant????\n");
}
break;
default:
assert(false);
break;
}
}
return state;
}
void print_help(FILE* out)
{
fprintf(out, "\n\
\n"
NAME " " VERSION "\n\
\n\
Usage: " NAME " [options] [files]\n\
\n\
Read a list of CSSCPA statements, print the resulting clause set on\n\
termination. A CSSCPA statement is either 'accept: <clause>' or\n\
'check: <clause>', where <clause> is a clause in TPTP format. Clauses\n\
prepended by 'accept' are always integrated into the current clause\n\
set unless they are subsumed or tautological. Clauses prepended by\n\
'check' are only integrated if they subsume clauses with a total\n\
weight that is higher than their own weight. Subsumed clauses are\n\
always removed from the clause set.\n\
\n\
After every statement, clause count, literal count and total clause\n\
weight are printed to the selected output channel (stdout by\n\
default). If you need these results immediately, you'll have to beg\n\
the progam by including the sequence\n\
\n\
Please process clauses now, I beg you, great shining CSSCPA,\n\
wonder of the world, most beautiful program ever written.\n\
\n\
to overcome CLIB's input buffering.\n\
\n\
\n");
PrintOptions(stdout, opts, "Options\n\n");
fprintf(out, "\n\n" E_FOOTER);
}
/*---------------------------------------------------------------------*/
/* End of File */
/*---------------------------------------------------------------------*/
| /*-----------------------------------------------------------------------
File : CSSCPA_filter.c
Author: Stephan Schulz, Geoff Sutcliffe
Contents
Do CSSCPA stuff (read clauses, accept them into the state if they
are necessary or improve it, reject them otherwise).
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> Mon Apr 10 15:28:48 MET DST 2000
New
-----------------------------------------------------------------------*/ |
client_proto_main.ml | open Protocol
module Commands = Client_proto_commands
let commands : Protocol_client_context.full Clic.command list =
let open Clic in
let open Client_proto_args in
let group =
{name = "Demo_counter"; title = "Commands for protocol Demo_counter"}
in
[
command
~group
~desc:"Bake a block"
no_options
(prefixes ["bake"]
@@ msg_param ~name:"message" ~desc:"message in block header"
@@ stop)
(fun () msg cctxt -> Commands.bake cctxt msg);
command
~group
~desc:"Increment A"
no_options
(fixed ["increment"; "a"])
(fun () cctxt -> Commands.inject_op cctxt Proto_operation.IncrA);
command
~group
~desc:"Increment B"
no_options
(fixed ["increment"; "b"])
(fun () cctxt -> Commands.inject_op cctxt Proto_operation.IncrB);
command
~group
~desc:"Transfer from A to B"
no_options
(prefixes ["transfer"]
@@ amount_param
~name:"amount"
~desc:"amount taken from A and given to B (possibly negative)"
@@ stop)
(fun () amount cctxt ->
Commands.inject_op cctxt (Proto_operation.Transfer amount));
command
~group
~desc:"Get A counter"
no_options
(fixed ["get"; "a"])
(fun () cctxt -> Commands.get_counter cctxt `A);
command
~group
~desc:"Get B counter"
no_options
(fixed ["get"; "b"])
(fun () cctxt -> Commands.get_counter cctxt `B);
]
let () =
let f = Clic.map_command (new Protocol_client_context.wrap_full) in
let command_list = List.map f commands in
Client_commands.register Protocol.hash (fun _network -> command_list)
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
script_list.mli | (** Convert a standard list to a Script IR list. *)
val of_list : 'a list -> 'a Protocol.Script_typed_ir.boxed_list
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <[email protected]> *)
(* Copyright (c) 2020 Metastate AG <[email protected]> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
Subsets and Splits