filename
stringlengths
3
67
data
stringlengths
0
58.3M
license
stringlengths
0
19.5k
parany.ml
module A = Array module Chan = Domainslib.Chan module Ht = Hashtbl module IntMap = Map.Make(Int) module Sem = Semaphore.Binary exception End_of_input module DLS = struct let write_lock = Sem.make true (* apparently, null_f is required to avoid the weak type variable problem *) type 'a store = { null_f: (unit -> 'a); values: ('a IntMap.t) ref } let create (null_f: unit -> 'a): 'a store = { null_f; values = ref IntMap.empty } let set (s: 'a store) (v: 'a): unit = let my_id = (Domain.self () :> int) in Sem.acquire write_lock; (* <critical_section> *) s.values := IntMap.add my_id v !(s.values); Sem.release write_lock (* </critical_section> *) let get s = IntMap.find (Domain.self () :> int) !(s.values) end let id2rank = DLS.create (fun () -> -1) (* only workers are supposed to call this *) let get_rank () = DLS.get id2rank let worker_loop jobs results work = let rec loop () = match Chan.recv jobs with | [||] -> (* signal muxer thread *) Chan.send results [||] | arr -> begin let res = Array.map work arr in Chan.send results res; loop () end in loop () let demuxer_loop nprocs jobs csize demux = let rec loop () = let to_send = ref [] in try for _i = 1 to csize do to_send := (demux ()) :: !to_send done; let xs = Array.of_list (List.rev !to_send) in Chan.send jobs xs; loop () with End_of_input -> begin if !to_send <> [] then begin let xs = Array.of_list (List.rev !to_send) in Chan.send jobs xs end; for _i = 1 to nprocs do (* signal each worker *) Chan.send jobs [||] done end in loop () let muxer_loop nprocs results mux = let finished = ref 0 in let rec loop () = match Chan.recv results with | [||] -> (* one worker finished *) begin incr finished; if !finished = nprocs then () else loop () end | xs -> begin Array.iter mux xs; loop () end in loop () (* demux and index items *) let idemux (demux: unit -> 'a) = let demux_count = ref 0 in function () -> let res = (!demux_count, demux ()) in incr demux_count; res (* work, ignoring item index *) let iwork (work: 'a -> 'b) ((i, x): int * 'a): int * 'b = (i, work x) (* mux items in the right order *) let imux (mux: 'b -> unit) = let mux_count = ref 0 in (* weak type variable avoidance *) let wait_list = Ht.create 11 in function (i, res) -> if !mux_count = i then begin (* unpile as much as possible *) mux res; incr mux_count; if Ht.length wait_list > 0 then try while true do let next = Ht.find wait_list !mux_count in Ht.remove wait_list !mux_count; mux next; incr mux_count done with Not_found -> () (* no more or index hole *) end else (* put somewhere into the pile *) Ht.add wait_list i res let run ?(preserve = false) ?(csize = 1) (nprocs: int) ~demux ~work ~mux = if nprocs <= 1 then (* no overhead sequential version *) try while true do mux (work (demux ())) done with End_of_input -> () else begin if preserve then (* nprocs workers + demuxer thread + muxer thread *) let jobs = Chan.make_bounded (50 * nprocs) in let results = Chan.make_bounded (50 * nprocs) in (* launch the workers *) let workers = Array.init nprocs (fun rank -> Domain.spawn (fun () -> DLS.set id2rank rank; worker_loop jobs results (iwork work) ) ) in (* launch the demuxer *) let demuxer = Domain.spawn (fun () -> demuxer_loop nprocs jobs csize (idemux demux) ) in (* use the current thread to collect results (muxer) *) muxer_loop nprocs results (imux mux); (* wait all threads *) Domain.join demuxer; Array.iter Domain.join workers else (* WARNING: serious code duplication below... *) (* nprocs workers + demuxer thread + muxer thread *) let jobs = Chan.make_bounded (50 * nprocs) in let results = Chan.make_bounded (50 * nprocs) in (* launch the workers *) let workers = Array.init nprocs (fun rank -> Domain.spawn (fun () -> DLS.set id2rank rank; worker_loop jobs results work ) ) in (* launch the demuxer *) let demuxer = Domain.spawn (fun () -> demuxer_loop nprocs jobs csize demux ) in (* use the current thread to collect results (muxer) *) muxer_loop nprocs results mux; (* wait all threads *) Domain.join demuxer; Array.iter Domain.join workers end (* Wrapper for near-compatibility with Parmap *) module Parmap = struct let tail_rec_map f l = List.rev (List.rev_map f l) let tail_rec_mapi f l = let i = ref 0 in let res = List.rev_map (fun x -> let j = !i in let y = f j x in incr i; y ) l in List.rev res let parmap ?(preserve = false) ?(csize = 1) ncores f l = if ncores <= 1 then tail_rec_map f l else let input = ref l in let demux () = match !input with | [] -> raise End_of_input | x :: xs -> (input := xs; x) in let output = ref [] in let mux x = output := x :: !output in (* parallel work *) run ~preserve ~csize ncores ~demux ~work:f ~mux; if preserve then List.rev !output else !output let parmapi ?(preserve = false) ?(csize = 1) ncores f l = if ncores <= 1 then tail_rec_mapi f l else let input = ref l in let i = ref 0 in let demux () = match !input with | [] -> raise End_of_input | x :: xs -> begin let j = !i in input := xs; let res = (j, x) in incr i; res end in let output = ref [] in let f' (i, x) = f i x in let mux x = output := x :: !output in (* parallel work *) run ~preserve ~csize ncores ~demux ~work:f' ~mux; if preserve then List.rev !output else !output let pariter ?(preserve = false) ?(csize = 1) ncores f l = if ncores <= 1 then List.iter f l else let input = ref l in let demux () = match !input with | [] -> raise End_of_input | x :: xs -> (input := xs; x) in (* parallel work *) run ~preserve ~csize ncores ~demux ~work:f ~mux:ignore let parfold ?(preserve = false) ?(csize = 1) ncores f g init_acc l = if ncores <= 1 then List.fold_left (fun acc x -> g acc (f x)) init_acc l else let input = ref l in let demux () = match !input with | [] -> raise End_of_input | x :: xs -> (input := xs; x) in let output = ref init_acc in let mux x = output := g !output x in (* parallel work *) run ~preserve ~csize ncores ~demux ~work:f ~mux; !output (* preserves array input order *) let array_parmap ncores f init_acc a = let n = A.length a in let res = A.make n init_acc in run ~preserve:false (* input-order is preserved explicitely below *) ~csize:1 ncores ~demux:( let in_count = ref 0 in fun () -> if !in_count = n then raise End_of_input else let i = !in_count in incr in_count; i) ~work:(fun i -> (i, f (A.unsafe_get a i))) ~mux:(fun (i, y) -> A.unsafe_set res i y); res end
dune
(library (name opam_client) (public_name opam-client) (synopsis "OCaml Package Manager client and CLI library") (modules (:standard \ opamMain get_git_version)) (libraries opam-state opam-solver opam-repository re base64 cmdliner (select opamBase64Compat.ml from (!dose3.opam -> opamBase64Compat.ml.6) (dose3.dose_src_ext_vendor -> opamBase64Compat.ml.6) ( -> opamBase64Compat.ml.5)) (select opamBase64Compat.mli from (!dose3.opam -> opamBase64Compat.mli.6) (dose3.dose_src_ext_vendor -> opamBase64Compat.mli.6) ( -> opamBase64Compat.mli.5))) (flags (:standard (:include ../ocaml-flags-standard.sexp) (:include ../ocaml-flags-configure.sexp) (:include ../ocaml-context-flags.sexp))) (wrapped false)) (rule (with-stdout-to opamBase64Compat.ml.6 (run echo ""))) (rule (with-stdout-to opamBase64Compat.mli.6 (run echo ""))) (executable (name opamMain) ; This name needs to be updated in doc/man/dune if changed (public_name opam) (package opam) (modules opamMain) (flags (:standard (:include ../ocaml-flags-standard.sexp) (:include ../ocaml-flags-configure.sexp) (:include ../ocaml-context-flags.sexp) (:include linking.sexp))) (libraries opam-client (select link-opam-manifest from (opam-client.manifest -> pull-manifest) ( -> dummy) ))) (rule (with-stdout-to dummy (echo ""))) (rule (targets pull-manifest) (deps (:obj ../manifest/opam-manifest.o)) (action (progn (system "cp %{obj} opam-manifest.o 2> %{null} || copy %{obj} opam-manifest.o") (with-stdout-to %{targets} (echo ""))))) (rule (targets git-sha) (deps (universe)) (action (ignore-stderr (with-stdout-to %{targets} (system "git rev-parse --quiet --verify HEAD || echo ."))))) (rule (targets git-describe) (deps (universe)) (action (ignore-stderr (with-stdout-to %{targets} (system "git describe --exact HEAD || echo [dev]"))))) (rule (targets no-git-version) (mode fallback) (action (copy git-sha %{targets}))) (rule (with-stdout-to get_git_version.ml (echo "print_string @@ \ let v = \"%{read-lines:no-git-version}\" in \ let w = \"%{read-lines:git-describe}\" in \ if v = \"\" || v = \".\" || w <> \"[dev]\" then \ \"let version = None\" \ else \ \"let version = Some \\\"\" ^ v ^ \"\\\"\""))) (rule (with-stdout-to opamGitVersion.ml (run ocaml %{dep:get_git_version.ml}))) (rule (targets linking.sexp) (mode fallback) (action (with-stdout-to %{targets} (echo "()"))))
script_int_repr.ml
type n = Natural_tag type z = Integer_tag type 't num = Z.t let compare x y = Z.compare x y let zero = Z.zero let zero_n = Z.zero let to_string x = Z.to_string x let of_string s = try Some (Z.of_string s) with _ -> None let of_int32 n = Z.of_int64 @@ Int64.of_int32 n let to_int64 x = try Some (Z.to_int64 x) with _ -> None let of_int64 n = Z.of_int64 n let to_int x = try Some (Z.to_int x) with _ -> None let of_int n = Z.of_int n let of_zint x = x let to_zint x = x let add x y = Z.add x y let sub x y = Z.sub x y let mul x y = Z.mul x y let ediv x y = try let (q, r) = Z.ediv_rem x y in Some (q, r) with _ -> None let add_n = add let mul_n = mul let ediv_n = ediv let abs x = Z.abs x let is_nat x = if Compare.Z.(x < Z.zero) then None else Some x let neg x = Z.neg x let int x = x let shift_left x y = if Compare.Int.(Z.compare y (Z.of_int 256) > 0) then None else let y = Z.to_int y in Some (Z.shift_left x y) let shift_right x y = if Compare.Int.(Z.compare y (Z.of_int 256) > 0) then None else let y = Z.to_int y in Some (Z.shift_right x y) let shift_left_n = shift_left let shift_right_n = shift_right let logor x y = Z.logor x y let logxor x y = Z.logxor x y let logand x y = Z.logand x y let lognot x = Z.lognot x
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
Parse_solidity_tree_sitter.ml
open Common module CST = Tree_sitter_solidity.CST module PI = Parse_info module H = Parse_tree_sitter_helpers open AST_generic module G = AST_generic module H2 = AST_generic_helpers (*****************************************************************************) (* Prelude *) (*****************************************************************************) (* Solidity parser using tree-sitter-lang/semgrep-solidity and converting * directly to AST_generic.ml * *) (*****************************************************************************) (* Helpers *) (*****************************************************************************) type env = unit H.env let token = H.token let str = H.str let fb = PI.unsafe_fake_bracket let fake s = PI.unsafe_fake_info s let map_trailing_comma env v = match v with | Some tok -> (* "," *) token env tok |> ignore | None -> () let tuple_hole_expr _env tok = OtherExpr (("TupleHole", tok), []) |> G.e let tuple_hole_pat _env tok = PatUnderscore tok |> G.p let stmt_of_def_or_dir = function | Left3 def -> DefStmt def |> G.s | Right3 dir -> DirectiveStmt dir |> G.s | Middle3 ellipsis_tok -> G.exprstmt (G.e (Ellipsis ellipsis_tok)) (*****************************************************************************) (* Boilerplate converter *) (*****************************************************************************) (* This was started by copying tree-sitter-lang/semgrep-solidity/Boilerplate.ml *) let map_uint (env : env) (x : CST.uint) = match x with | `Uint tok -> (* "uint" *) str env tok | `Uint8 tok -> (* "uint8" *) str env tok | `Uint16 tok -> (* "uint16" *) str env tok | `Uint24 tok -> (* "uint24" *) str env tok | `Uint32 tok -> (* "uint32" *) str env tok | `Uint40 tok -> (* "uint40" *) str env tok | `Uint48 tok -> (* "uint48" *) str env tok | `Uint56 tok -> (* "uint56" *) str env tok | `Uint64 tok -> (* "uint64" *) str env tok | `Uint72 tok -> (* "uint72" *) str env tok | `Uint80 tok -> (* "uint80" *) str env tok | `Uint88 tok -> (* "uint88" *) str env tok | `Uint96 tok -> (* "uint96" *) str env tok | `Uint104 tok -> (* "uint104" *) str env tok | `Uint112 tok -> (* "uint112" *) str env tok | `Uint120 tok -> (* "uint120" *) str env tok | `Uint128 tok -> (* "uint128" *) str env tok | `Uint136 tok -> (* "uint136" *) str env tok | `Uint144 tok -> (* "uint144" *) str env tok | `Uint152 tok -> (* "uint152" *) str env tok | `Uint160 tok -> (* "uint160" *) str env tok | `Uint168 tok -> (* "uint168" *) str env tok | `Uint176 tok -> (* "uint176" *) str env tok | `Uint184 tok -> (* "uint184" *) str env tok | `Uint192 tok -> (* "uint192" *) str env tok | `Uint200 tok -> (* "uint200" *) str env tok | `Uint208 tok -> (* "uint208" *) str env tok | `Uint216 tok -> (* "uint216" *) str env tok | `Uint224 tok -> (* "uint224" *) str env tok | `Uint232 tok -> (* "uint232" *) str env tok | `Uint240 tok -> (* "uint240" *) str env tok | `Uint248 tok -> (* "uint248" *) str env tok | `Uint256 tok -> (* "uint256" *) str env tok let map_number_unit (env : env) (x : CST.number_unit) = match x with | `Wei tok -> (* "wei" *) str env tok | `Szabo tok -> (* "szabo" *) str env tok | `Finney tok -> (* "finney" *) str env tok | `Gwei tok -> (* "gwei" *) str env tok | `Ether tok -> (* "ether" *) str env tok | `Seconds tok -> (* "seconds" *) str env tok | `Minutes tok -> (* "minutes" *) str env tok | `Hours tok -> (* "hours" *) str env tok | `Days tok -> (* "days" *) str env tok | `Weeks tok -> (* "weeks" *) str env tok | `Years tok -> (* "years" *) str env tok let map_state_mutability (env : env) (x : CST.state_mutability) : attribute = match x with (* less: Const? *) | `Pure tok -> (* "pure" *) str env tok |> G.unhandled_keywordattr | `View tok -> (* "view" *) str env tok |> G.unhandled_keywordattr | `Paya tok -> (* "payable" *) str env tok |> G.unhandled_keywordattr let map_yul_or_literal_boolean (env : env) x : bool wrap = match x with | `True tok -> (* "true" *) (true, token env tok) | `False tok -> (* "false" *) (false, token env tok) let map_solidity_version_comparison_operator (env : env) (x : CST.solidity_version_comparison_operator) : operator wrap = match x with | `LTEQ tok -> (* "<=" *) (LtE, token env tok) | `LT tok -> (* "<" *) (Lt, token env tok) | `HAT tok -> (* "^" *) (BitXor, token env tok) | `GT tok -> (* ">" *) (Gt, token env tok) | `GTEQ tok -> (* ">=" *) (GtE, token env tok) | `TILDE tok -> (* "~" *) (BitNot, token env tok) | `EQ tok -> (* "=" *) (Eq, token env tok) let map_storage_location (env : env) (x : CST.storage_location) : attribute = match x with | `Memory tok -> (* "memory" *) str env tok |> G.unhandled_keywordattr | `Stor tok -> (* "storage" *) str env tok |> G.unhandled_keywordattr | `Call tok -> (* "calldata" *) str env tok |> G.unhandled_keywordattr let map_visibility (env : env) (x : CST.visibility) : attribute = match x with | `Public tok -> let x = (* "public" *) token env tok in G.attr Public x | `Inte tok -> let x = (* "internal" *) token env tok in G.attr Static x | `Priv tok -> let x = (* "private" *) token env tok in G.attr Private x | `Exte tok -> let x = (* "external" *) token env tok in G.attr Extern x let map_yul_evm_builtin (env : env) (x : CST.yul_evm_builtin) = match x with | `Stop tok -> (* "stop" *) str env tok | `Add tok -> (* "add" *) str env tok | `Sub tok -> (* "sub" *) str env tok | `Mul tok -> (* "mul" *) str env tok | `Div tok -> (* "div" *) str env tok | `Sdiv tok -> (* "sdiv" *) str env tok | `Mod tok -> (* "mod" *) str env tok | `Smod tok -> (* "smod" *) str env tok | `Exp tok -> (* "exp" *) str env tok | `Not tok -> (* "not" *) str env tok | `Lt tok -> (* "lt" *) str env tok | `Gt tok -> (* "gt" *) str env tok | `Slt tok -> (* "slt" *) str env tok | `Sgt tok -> (* "sgt" *) str env tok | `Eq tok -> (* "eq" *) str env tok | `Iszero tok -> (* "iszero" *) str env tok | `And tok -> (* "and" *) str env tok | `Or tok -> (* "or" *) str env tok | `Xor tok -> (* "xor" *) str env tok | `Byte tok -> (* "byte" *) str env tok | `Shl tok -> (* "shl" *) str env tok | `Shr tok -> (* "shr" *) str env tok | `Sar tok -> (* "sar" *) str env tok | `Addmod tok -> (* "addmod" *) str env tok | `Mulmod tok -> (* "mulmod" *) str env tok | `Sign tok -> (* "signextend" *) str env tok | `Keccak256 tok -> (* "keccak256" *) str env tok | `Pop tok -> (* "pop" *) str env tok | `Mload tok -> (* "mload" *) str env tok | `Mstore tok -> (* "mstore" *) str env tok | `Mstore8 tok -> (* "mstore8" *) str env tok | `Sload tok -> (* "sload" *) str env tok | `Sstore tok -> (* "sstore" *) str env tok | `Msize tok -> (* "msize" *) str env tok | `Gas tok -> (* "gas" *) str env tok | `Addr tok -> (* "address" *) str env tok | `Bala tok -> (* "balance" *) str env tok | `Self_e34af40 tok -> (* "selfbalance" *) str env tok | `Caller tok -> (* "caller" *) str env tok | `Call_17bffc7 tok -> (* "callvalue" *) str env tok | `Call_b766e35 tok -> (* "calldataload" *) str env tok | `Call_ee2b8b2 tok -> (* "calldatasize" *) str env tok | `Call_9211e8b tok -> (* "calldatacopy" *) str env tok | `Extc_8cf31ff tok -> (* "extcodesize" *) str env tok | `Extc_097e5c5 tok -> (* "extcodecopy" *) str env tok | `Retu_6316777 tok -> (* "returndatasize" *) str env tok | `Retu_0c570b4 tok -> (* "returndatacopy" *) str env tok | `Extc_d7340e7 tok -> (* "extcodehash" *) str env tok | `Create tok -> (* "create" *) str env tok | `Create2 tok -> (* "create2" *) str env tok | `Call_53b9e96 tok -> (* "call" *) str env tok | `Call_bebd5bc tok -> (* "callcode" *) str env tok | `Dele tok -> (* "delegatecall" *) str env tok | `Stat tok -> (* "staticcall" *) str env tok | `Ret tok -> (* "return" *) str env tok | `Revert tok -> (* "revert" *) str env tok | `Self_482b767 tok -> (* "selfdestruct" *) str env tok | `Inva tok -> (* "invalid" *) str env tok | `Log0 tok -> (* "log0" *) str env tok | `Log1 tok -> (* "log1" *) str env tok | `Log2 tok -> (* "log2" *) str env tok | `Log3 tok -> (* "log3" *) str env tok | `Log4 tok -> (* "log4" *) str env tok | `Chai tok -> (* "chainid" *) str env tok | `Origin tok -> (* "origin" *) str env tok | `Gasp tok -> (* "gasprice" *) str env tok | `Bloc tok -> (* "blockhash" *) str env tok | `Coin tok -> (* "coinbase" *) str env tok | `Time tok -> (* "timestamp" *) str env tok | `Num tok -> (* "number" *) str env tok | `Diff tok -> (* "difficulty" *) str env tok | `Gasl tok -> (* "gaslimit" *) str env tok let map_bytes_ (env : env) (x : CST.bytes_) = match x with | `Byte tok -> (* "byte" *) str env tok | `Bytes tok -> (* "bytes" *) str env tok | `Bytes1 tok -> (* "bytes1" *) str env tok | `Bytes2 tok -> (* "bytes2" *) str env tok | `Bytes3 tok -> (* "bytes3" *) str env tok | `Bytes4 tok -> (* "bytes4" *) str env tok | `Bytes5 tok -> (* "bytes5" *) str env tok | `Bytes6 tok -> (* "bytes6" *) str env tok | `Bytes7 tok -> (* "bytes7" *) str env tok | `Bytes8 tok -> (* "bytes8" *) str env tok | `Bytes9 tok -> (* "bytes9" *) str env tok | `Bytes10 tok -> (* "bytes10" *) str env tok | `Bytes11 tok -> (* "bytes11" *) str env tok | `Bytes12 tok -> (* "bytes12" *) str env tok | `Bytes13 tok -> (* "bytes13" *) str env tok | `Bytes14 tok -> (* "bytes14" *) str env tok | `Bytes15 tok -> (* "bytes15" *) str env tok | `Bytes16 tok -> (* "bytes16" *) str env tok | `Bytes17 tok -> (* "bytes17" *) str env tok | `Bytes18 tok -> (* "bytes18" *) str env tok | `Bytes19 tok -> (* "bytes19" *) str env tok | `Bytes20 tok -> (* "bytes20" *) str env tok | `Bytes21 tok -> (* "bytes21" *) str env tok | `Bytes22 tok -> (* "bytes22" *) str env tok | `Bytes23 tok -> (* "bytes23" *) str env tok | `Bytes24 tok -> (* "bytes24" *) str env tok | `Bytes25 tok -> (* "bytes25" *) str env tok | `Bytes26 tok -> (* "bytes26" *) str env tok | `Bytes27 tok -> (* "bytes27" *) str env tok | `Bytes28 tok -> (* "bytes28" *) str env tok | `Bytes29 tok -> (* "bytes29" *) str env tok | `Bytes30 tok -> (* "bytes30" *) str env tok | `Bytes31 tok -> (* "bytes31" *) str env tok | `Bytes32 tok -> (* "bytes32" *) str env tok let map_anon_choice_PLUSPLUS_e498e28 (env : env) (x : CST.anon_choice_PLUSPLUS_e498e28) = match x with | `PLUSPLUS tok -> (* "++" *) (Incr, token env tok) | `DASHDASH tok -> (* "--" *) (Decr, token env tok) let map_int_ (env : env) (x : CST.int_) = match x with | `Int tok -> (* "int" *) str env tok | `Int8 tok -> (* "int8" *) str env tok | `Int16 tok -> (* "int16" *) str env tok | `Int24 tok -> (* "int24" *) str env tok | `Int32 tok -> (* "int32" *) str env tok | `Int40 tok -> (* "int40" *) str env tok | `Int48 tok -> (* "int48" *) str env tok | `Int56 tok -> (* "int56" *) str env tok | `Int64 tok -> (* "int64" *) str env tok | `Int72 tok -> (* "int72" *) str env tok | `Int80 tok -> (* "int80" *) str env tok | `Int88 tok -> (* "int88" *) str env tok | `Int96 tok -> (* "int96" *) str env tok | `Int104 tok -> (* "int104" *) str env tok | `Int112 tok -> (* "int112" *) str env tok | `Int120 tok -> (* "int120" *) str env tok | `Int128 tok -> (* "int128" *) str env tok | `Int136 tok -> (* "int136" *) str env tok | `Int144 tok -> (* "int144" *) str env tok | `Int152 tok -> (* "int152" *) str env tok | `Int160 tok -> (* "int160" *) str env tok | `Int168 tok -> (* "int168" *) str env tok | `Int176 tok -> (* "int176" *) str env tok | `Int184 tok -> (* "int184" *) str env tok | `Int192 tok -> (* "int192" *) str env tok | `Int200 tok -> (* "int200" *) str env tok | `Int208 tok -> (* "int208" *) str env tok | `Int216 tok -> (* "int216" *) str env tok | `Int224 tok -> (* "int224" *) str env tok | `Int232 tok -> (* "int232" *) str env tok | `Int240 tok -> (* "int240" *) str env tok | `Int248 tok -> (* "int248" *) str env tok | `Int256 tok -> (* "int256" *) str env tok let map_identifier_path (env : env) ((v1, v2) : CST.identifier_path) : name = let v1 = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v1 in let v2 = Common.map (fun (v1, v2) -> let _v1 = (* "." *) token env v1 in let v2 = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v2 in v2) v2 in H2.name_of_ids (v1 :: v2) let map_yul_path (env : env) ((v1, v2) : CST.yul_path) : name = let v1 = (* pattern [a-zA-Z$_]+ *) str env v1 in let v2 = Common.map (fun (v1, v2) -> let _v1 = (* "." *) token env v1 in let v2 = (* pattern [a-zA-Z$_]+ *) str env v2 in v2) v2 in H2.name_of_ids (v1 :: v2) let map_anon_yul_id_rep_COMMA_yul_id_opt_COMMA_477546e (env : env) ((v1, v2, v3) : CST.anon_yul_id_rep_COMMA_yul_id_opt_COMMA_477546e) : ident list = let v1 = (* pattern [a-zA-Z$_]+ *) str env v1 in let v2 = Common.map (fun (v1, v2) -> let _v1 = (* "," *) token env v1 in let v2 = (* pattern [a-zA-Z$_]+ *) str env v2 in v2) v2 in let _v3 = map_trailing_comma env v3 in v1 :: v2 (* TODO: in the grammar there is a PREC.USER_TYPE which makes every * primary expression to switch to this instead of a simple identifier, * so take care! *) let map_user_defined_type (env : env) ((v1, v2) : CST.user_defined_type) : name = let v1 = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v1 in let v2 = Common.map (fun (v1, v2) -> let _v1 = (* "." *) token env v1 in let v2 = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v2 in v2) v2 in let ids = v1 :: v2 in let n = H2.name_of_ids ids in (* actually not always a type, so better to just return the name instead * of TyN n |> G.t *) n let map_import_declaration (env : env) ((v1, v2) : CST.import_declaration) = let v1 = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v1 in let v2 = match v2 with | Some (v1, v2) -> let _v1 = (* "as" *) token env v1 in let v2 = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v2 in Some (v2, G.empty_id_info ()) | None -> None in (v1, v2) let map_decimal_number (env : env) (x : CST.decimal_number) = match x with | `Pat_585ba4d tok -> let s, t = (* pattern \d+(\.\d+)?([eE](-)?\d+)? *) str env tok in (float_of_string_opt s, t) | `Pat_ac20a0c tok -> let s, t = (* pattern \.\d+([eE](-)?\d+)? *) str env tok in (float_of_string_opt s, t) let map_pragma_version_constraint (env : env) ((v1, v2) : CST.pragma_version_constraint) : any list = let v1 = match v1 with | Some x -> let op, t = map_solidity_version_comparison_operator env x in [ E (IdSpecial (Op op, t) |> G.e) ] | None -> [] in let v2 = (* pattern \d+(.\d+(.\d+)?)? *) str env v2 in v1 @ [ Str (fb v2) ] let map_fixed (env : env) (x : CST.fixed) = match x with | `Fixed tok -> (* "fixed" *) str env tok | `Pat_f2662db tok -> (* pattern fixed([0-9]+)x([0-9]+) *) str env tok let map_anon_rep_opt___hex_digit_c87bea1 (env : env) (xs : CST.anon_rep_opt___hex_digit_c87bea1) : string wrap list = Common.map (fun (v1, v2) -> let _v1 = match v1 with | Some tok -> (* "_" *) [ token env tok ] | None -> [] in let v2 = (* pattern ([a-fA-F0-9][a-fA-F0-9]) *) str env v2 in v2) xs let map_ufixed (env : env) (x : CST.ufixed) = match x with | `Ufixed tok -> (* "ufixed" *) str env tok | `Pat_accdbe2 tok -> (* pattern ufixed([0-9]+)x([0-9]+) *) str env tok let map_double_quoted_unicode_char (env : env) (x : CST.double_quoted_unicode_char) = str env x let map_single_quoted_unicode_char (env : env) (x : CST.single_quoted_unicode_char) = str env x let map_string_ (env : env) (x : CST.string_) : string wrap bracket = match x with | `DQUOT_rep_choice_str_imme_elt_inside_double_quote_DQUOT (v1, v2, v3) -> let l = (* "\"" *) token env v1 in let xs = Common.map (fun x -> match x with | `Str_imme_elt_inside_double_quote tok -> (* pattern "[^\"\\\\\\n]+|\\\\\\r?\\n" *) str env tok | `Esc_seq tok -> (* escape_sequence *) str env tok) v2 in let r = (* "\"" *) token env v3 in G.string_ (l, xs, r) | `SQUOT_rep_choice_str_imme_elt_inside_quote_SQUOT (v1, v2, v3) -> let l = (* "'" *) token env v1 in let xs = Common.map (fun x -> match x with | `Str_imme_elt_inside_quote tok -> (* pattern "[^'\\\\\\n]+|\\\\\\r?\\n" *) str env tok | `Esc_seq tok -> (* escape_sequence *) str env tok) v2 in let r = (* "'" *) token env v3 in G.string_ (l, xs, r) let map_primitive_type (env : env) (x : CST.primitive_type) : type_ = match x with | `Addr_opt_paya (v1, v2) -> let v1 = (* "address" *) str env v1 in let v2 = match v2 with | Some tok -> (* "payable" *) [ str env tok ] | None -> [] in let n = H2.name_of_ids (v1 :: v2) in G.TyN n |> G.t | `Bool tok -> let x = (* "bool" *) str env tok in G.ty_builtin x | `Str tok -> let x = (* "string" *) str env tok in G.ty_builtin x | `Var tok -> let x = (* "var" *) str env tok in G.ty_builtin x | `Int x -> let x = map_int_ env x in G.ty_builtin x | `Uint x -> let x = map_uint env x in G.ty_builtin x | `Bytes x -> let x = map_bytes_ env x in G.ty_builtin x | `Fixed x -> let x = map_fixed env x in G.ty_builtin x | `Ufixed x -> let x = map_ufixed env x in G.ty_builtin x let map_user_defined_type_definition (env : env) ((v1, v2, v3, v4, v5) : CST.user_defined_type_definition) : definition = let _ttype = (* "type" *) token env v1 in let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v2 in let _tis = (* "is" *) token env v3 in let ty = map_primitive_type env v4 in let _sc = (* ";" *) token env v5 in let ent = G.basic_entity id in let def = { tbody = AliasType (* or NewType? *) ty } in (ent, TypeDef def) let map_enum_declaration (env : env) ((v1, v2, v3, v4, v5) : CST.enum_declaration) : definition = let _enumkwd = (* "enum" *) token env v1 in let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v2 in let _lb = (* "{" *) token env v3 in let elems = match v4 with | Some x -> map_anon_yul_id_rep_COMMA_yul_id_opt_COMMA_477546e env x | None -> [] in let _rb = (* "}" *) token env v5 in let ent = G.basic_entity id in let ors = elems |> Common.map (fun id -> OrEnum (id, None)) in let def = { tbody = OrType ors } in (ent, TypeDef def) let map_override_specifier (env : env) ((v1, v2) : CST.override_specifier) = let toverride = (* "override" *) token env v1 in let names = match v2 with | Some (v1, v2, v3, v4, v5) -> let lp = (* "(" *) token env v1 in let n = map_user_defined_type env v2 in let xs = Common.map (fun (v1, v2) -> let _tcomma = (* "," *) token env v1 in let n = map_user_defined_type env v2 in n) v3 in let _v4 = map_trailing_comma env v4 in let rp = (* ")" *) token env v5 in Some (lp, n :: xs, rp) | None -> None in match names with | None -> G.attr Override toverride | Some (_l, xs, _r) -> OtherAttribute ( ("OverrideWithNames", toverride), xs |> Common.map (fun x -> E (N x |> G.e)) ) let map_hex_number (env : env) (x : CST.hex_number) = let s, t = str env x in (int_of_string_opt s, t) let map_hex_string_literal (env : env) (xs : CST.hex_string_literal) : (tok * string wrap bracket) list = Common.map (fun (v1, v2) -> let v1 = (* "hex" *) token env v1 in let v2 = match v2 with | `DQUOT_opt_hex_digit_rep_opt___hex_digit_DQUOT (v1, v2, v3) -> let l = (* "\"" *) token env v1 in let xs = match v2 with | Some (v1, v2) -> let v1 = (* pattern ([a-fA-F0-9][a-fA-F0-9]) *) str env v1 in let v2 = map_anon_rep_opt___hex_digit_c87bea1 env v2 in v1 :: v2 | None -> [] in let r = (* "\"" *) token env v3 in G.string_ (l, xs, r) | `SQUOT_opt_hex_digit_rep_opt___hex_digit_SQUOT (v1, v2, v3) -> let l = (* "'" *) token env v1 in let xs = match v2 with | Some (v1, v2) -> let v1 = (* pattern ([a-fA-F0-9][a-fA-F0-9]) *) str env v1 in let v2 = map_anon_rep_opt___hex_digit_c87bea1 env v2 in v1 :: v2 | None -> [] in let r = (* "'" *) token env v3 in G.string_ (l, xs, r) in (v1, v2)) xs let map_unicode_string_literal (env : env) (xs : CST.unicode_string_literal) : (tok * string wrap bracket) list = Common.map (fun (v1, v2) -> let v1 = (* "unicode" *) token env v1 in let v2 = match v2 with | `DQUOT_rep_double_quoted_unic_char_DQUOT (v1, v2, v3) -> let l = (* "\"" *) token env v1 in let xs = Common.map (map_double_quoted_unicode_char env) v2 in let r = (* "\"" *) token env v3 in G.string_ (l, xs, r) | `SQUOT_rep_single_quoted_unic_char_SQUOT (v1, v2, v3) -> let l = (* "'" *) token env v1 in let xs = Common.map (map_single_quoted_unicode_char env) v2 in let r = (* "'" *) token env v3 in G.string_ (l, xs, r) in (v1, v2)) xs let map_yul_string_literal (env : env) (x : CST.yul_string_literal) = map_string_ env x let map_import_clause (env : env) (x : CST.import_clause) = match x with | `Single_import (v1, v2) -> ( let v1 = match v1 with | `STAR tok -> Left ((* "*" *) token env tok) | `Id tok -> Right ((* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env tok) in let alias_opt = Option.map (fun (v1, v2) -> let _v1 = (* "as" *) token env v1 in let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v2 in (id, G.empty_id_info ())) v2 in fun timport modname -> match (v1, alias_opt) with | Left tstar, None -> [ ImportAll (timport, modname, tstar) |> G.d ] | Left _tstar, Some alias -> [ ImportAs (timport, modname, Some alias) |> G.d ] | Right id, alias_opt -> [ ImportFrom (timport, modname, [ (id, alias_opt) ]) |> G.d ]) | `Mult_import (v1, v2, v3) -> let _lb = (* "{" *) token env v1 in let xs = match v2 with | Some (v1, v2, v3) -> let v1 = map_import_declaration env v1 in let v2 = Common.map (fun (v1, v2) -> let _v1 = (* "," *) token env v1 in let v2 = map_import_declaration env v2 in v2) v2 in let _v3 = map_trailing_comma env v3 in v1 :: v2 | None -> [] in let _rb = (* "}" *) token env v3 in fun timport modname -> xs |> Common.map (fun (id, aliasopt) -> ImportFrom (timport, modname, [ (id, aliasopt) ]) |> G.d) let map_mapping_key (env : env) (x : CST.mapping_key) : type_ = match x with | `Prim_type x -> map_primitive_type env x | `User_defi_type x -> let n = map_user_defined_type env x in TyN n |> G.t let map_yul_literal (env : env) (x : CST.yul_literal) : literal = match x with | `Yul_deci_num tok -> (* pattern 0|([1-9][0-9]*\ ) *) let s, t = str env tok in Int (Common2.int_of_string_c_octal_opt s, t) | `Yul_str_lit x -> let x = map_yul_string_literal env x in String x | `Yul_hex_num tok -> let s, t = (* pattern 0x[0-9A-Fa-f]* *) str env tok in Int (int_of_string_opt s, t) | `Yul_bool x -> let b = map_yul_or_literal_boolean env x in Bool b let map_from_clause (env : env) ((v1, v2) : CST.from_clause) : string wrap bracket = let _v1 = (* "from" *) token env v1 in let v2 = map_yul_string_literal env v2 in v2 let map_source_import (env : env) ((v1, v2) : CST.source_import) = let v1 = map_yul_string_literal env v1 in let v2 = match v2 with | Some (v1, v2) -> let _v1 = (* "as" *) token env v1 in let v2 = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v2 in Some (v2, G.empty_id_info ()) | None -> None in (v1, v2) let map_string_literal (env : env) (xs : CST.string_literal) = Common.map (map_yul_string_literal env) xs let rec map_yul_expression (env : env) (x : CST.yul_expression) : expr = match x with | `Yul_path x -> let n = map_yul_path env x in N n |> G.e | `Yul_func_call x -> map_yul_function_call env x | `Yul_lit x -> let x = map_yul_literal env x in L x |> G.e and map_yul_function_call (env : env) (x : CST.yul_function_call) = match x with | `Choice_yul_id_LPAR_opt_yul_exp_rep_COMMA_yul_exp_opt_COMMA_RPAR (v1, v2, v3, v4) -> let operand = match v1 with | `Yul_id tok -> let id = (* pattern [a-zA-Z$_]+ *) str env tok in N (H2.name_of_id id) |> G.e | `Yul_evm_buil x -> let id = map_yul_evm_builtin env x in (* TODO: IdSpecial (Builtin ?) *) N (H2.name_of_id id) |> G.e in let lp = (* "(" *) token env v2 in let args = match v3 with | Some (v1, v2, v3) -> let v1 = map_yul_expression env v1 in let v2 = Common.map (fun (v1, v2) -> let _v1 = (* "," *) token env v1 in let v2 = map_yul_expression env v2 in v2) v2 in let _v3 = map_trailing_comma env v3 in v1 :: v2 | None -> [] in let rp = (* ")" *) token env v4 in let args = args |> Common.map G.arg in Call (operand, (lp, args, rp)) |> G.e | `Yul_evm_buil x -> let id = map_yul_evm_builtin env x in N (H2.name_of_id id) |> G.e let map_literal (env : env) (x : CST.literal) : expr = match x with | `Str_lit x -> ( let xs = map_string_literal env x in match xs with | [] -> raise Impossible | [ x ] -> L (String x) |> G.e (* TODO: concat them in a single String? *) | xs -> (* like in c_to_generic.ml *) let operand = G.IdSpecial (G.ConcatString G.SequenceConcat, fake " ") |> G.e in G.Call ( operand, fb (xs |> Common.map (fun x -> G.Arg (G.L (G.String x) |> G.e))) ) |> G.e) | `Num_lit (v1, v2) -> let lit = match v1 with | `Deci_num x -> let fopt, t = map_decimal_number env x in Float (fopt, t) | `Hex_num x -> let iopt, t = map_hex_number env x in Int (iopt, t) in let res = L lit |> G.e in let res = match v2 with | Some x -> let s, t = map_number_unit env x in OtherExpr (("UnitLiteral", t), [ Str (fb (s, t)); E res ]) |> G.e | None -> res in res | `Bool_lit x -> let x = map_yul_or_literal_boolean env x in L (Bool x) |> G.e | `Hex_str_lit x -> ( let xs = map_hex_string_literal env x in match xs with | [] -> raise Impossible | (tok_hex, _) :: _ -> OtherExpr ( ("HexString", tok_hex), xs |> Common.map (fun (thex, str) -> [ Tk thex; Str str ]) |> List.flatten ) |> G.e) | `Unic_str_lit x -> ( let xs = map_unicode_string_literal env x in match xs with | [] -> raise Impossible | (tok_unicode, _) :: _ -> OtherExpr ( ("UnicodeString", tok_unicode), xs |> Common.map (fun (tk, str) -> [ Tk tk; Str str ]) |> List.flatten ) |> G.e) let map_yul_variable_declaration (env : env) (x : CST.yul_variable_declaration) : definition = match x with | `Let_yul_id_opt_COLONEQ_yul_exp (v1, v2, v3) -> let _letkwd = (* "let" *) token env v1 in let id = (* pattern [a-zA-Z$_]+ *) str env v2 in let eopt = match v3 with | Some (v1, v2) -> let _v1 = (* ":=" *) token env v1 in let v2 = map_yul_expression env v2 in Some v2 | None -> None in let ent = G.basic_entity id in let vdef = { vinit = eopt; vtype = None } in (ent, VarDef vdef) | `Let_choice_yul_id_rep_COMMA_yul_id_opt_COMMA_opt_COLONEQ_yul_func_call (v1, v2, v3) -> let _letkwd = (* "let" *) token env v1 in let lp, ids, rp = match v2 with | `Yul_id_rep_COMMA_yul_id_opt_COMMA x -> fb (map_anon_yul_id_rep_COMMA_yul_id_opt_COMMA_477546e env x) | `LPAR_yul_id_rep_COMMA_yul_id_opt_COMMA_RPAR (v1, v2, v3, v4, v5) -> let lp = (* "(" *) token env v1 in let v2 = (* pattern [a-zA-Z$_]+ *) str env v2 in let v3 = Common.map (fun (v1, v2) -> let _v1 = (* "," *) token env v1 in let v2 = (* pattern [a-zA-Z$_]+ *) str env v2 in v2) v3 in let _v4 = map_trailing_comma env v4 in let rp = (* ")" *) token env v5 in (lp, v2 :: v3, rp) in let eopt = match v3 with | Some (v1, v2) -> let _v1 = (* ":=" *) token env v1 in let v2 = map_yul_function_call env v2 in Some v2 | None -> None in (* TODO: if eopt is None we could return a list of defs *) let pat = PatTuple (lp, ids |> Common.map (fun id -> PatId (id, G.empty_id_info ())), rp) |> G.p in let ent = { name = EPattern pat; attrs = []; tparams = [] } in let def = { vinit = eopt; vtype = None } in (ent, VarDef def) let map_yul_assignment_operator (env : env) (x : CST.yul_assignment_operator) = match x with | `COLONEQ tok -> (* ":=" *) token env tok | `COLON_EQ (v1, v2) -> let v1 = (* ":" *) token env v1 in let v2 = (* "=" *) token env v2 in PI.combine_infos v1 [ v2 ] let map_yul_assignment (env : env) (x : CST.yul_assignment) : expr = match x with | `Yul_path_yul_assign_op_yul_exp (v1, v2, v3) -> let n = map_yul_path env v1 in let teq = map_yul_assignment_operator env v2 in let e = map_yul_expression env v3 in Assign (N n |> G.e, teq, e) |> G.e | `Yul_path_rep_COMMA_yul_path_opt_COMMA_opt_yul_assign_op_yul_func_call (v1, v2, v3, v4) -> let v1 = map_yul_path env v1 in let v2 = Common.map (fun (v1, v2) -> let _v1 = (* "," *) token env v1 in let v2 = map_yul_path env v2 in v2) v2 in let _v3 = map_trailing_comma env v3 in let names = v1 :: v2 in let single_or_tuple = match names with | [] -> raise Impossible | [ x ] -> N x |> G.e | xs -> Container (Tuple, fb (xs |> Common.map (fun n -> N n |> G.e))) |> G.e in let res = match v4 with | Some (v1, v2) -> let teq = map_yul_assignment_operator env v1 in let e = map_yul_function_call env v2 in Assign (single_or_tuple, teq, e) |> G.e | None -> (* TODO: what is 'a, b' alone? a tuple? *) single_or_tuple in res let map_solidity_pragma_token (env : env) ((v1, v2) : CST.solidity_pragma_token) : ident * any list = let tsol = (* "solidity" *) str env v1 in let anys = Common.map (fun (v1, v2) -> let v1 = map_pragma_version_constraint env v1 in let v2 = match v2 with | Some x -> ( match x with | `BARBAR tok -> (* "||" *) [ Tk (token env tok) ] | `DASH tok -> (* "-" *) [ Tk (token env tok) ]) | None -> [] in v1 @ v2) v2 in (tsol, List.flatten anys) let map_pragma_value (env : env) (x : CST.pragma_value) = let t = token (* pattern [^;]+ *) env x in [ Tk t ] let map_any_pragma_token (env : env) ((v1, v2) : CST.any_pragma_token) : ident * any list = let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v1 in let anys = map_pragma_value env v2 in (id, anys) let map_directive (env : env) (x : CST.directive) : directive list = match x with | `Pragma_dire (v1, v2, v3) -> let tpragma = (* "pragma" *) token env v1 in let id, anys = match v2 with | `Soli_pragma_tok x -> map_solidity_pragma_token env x | `Any_pragma_tok x -> map_any_pragma_token env x in let sc = (* ";" *) token env v3 in [ Pragma (id, [ Tk tpragma ] @ anys @ [ Tk sc ]) |> G.d ] | `Import_dire (v1, v2, v3) -> let timport = (* "import" *) token env v1 in let res = match v2 with | `Source_import x -> let (_, str, _), aliasopt = map_source_import env x in [ ImportAs (timport, FileName str, aliasopt) |> G.d ] | `Import_clause_from_clause (v1, v2) -> let f = map_import_clause env v1 in let _, str, _ = map_from_clause env v2 in f timport (FileName str) in let _sc = (* ";" *) token env v3 in res let rec map_anon_choice_exp_5650be1 (env : env) (x : CST.anon_choice_exp_5650be1) : argument = match x with | `Exp x -> map_expression env x |> G.arg (* TODO: what is this argument? a list of keyword args? *) | `LCURL_opt_id_COLON_exp_rep_COMMA_id_COLON_exp_opt_COMMA_RCURL (v1, v2, v3) -> let lb = (* "{" *) token env v1 in let xs = match v2 with | Some x -> map_anon_yul_id_COLON_exp_rep_COMMA_yul_id_COLON_exp_opt_COMMA_c2b7c35 env x | None -> [] in let _rb = (* "}" *) token env v3 in OtherArg ( ("ArgIds", lb), xs |> Common.map (fun (id, tcol, e) -> [ I id; Tk tcol; E e ]) |> List.flatten ) and map_anon_yul_id_COLON_exp_rep_COMMA_yul_id_COLON_exp_opt_COMMA_c2b7c35 (env : env) ((v1, v2, v3, v4, v5) : CST.anon_yul_id_COLON_exp_rep_COMMA_yul_id_COLON_exp_opt_COMMA_c2b7c35) = let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v1 in let tcol = (* ":" *) token env v2 in let e = map_expression env v3 in let rest = Common.map (fun (v1, v2, v3, v4) -> let _v1 = (* "," *) token env v1 in let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v2 in let tcol = (* ":" *) token env v3 in let e = map_expression env v4 in (id, tcol, e)) v4 in let _v5 = map_trailing_comma env v5 in (id, tcol, e) :: rest and map_array_access (env : env) ((v1, v2, v3, v4) : CST.array_access) : expr = let e = map_expression env v1 in let lb = (* "[" *) token env v2 in let idx_opt = Option.map (map_expression env) v3 in let rb = (* "]" *) token env v4 in match idx_opt with | Some idx -> ArrayAccess (e, (lb, idx, rb)) |> G.e | None -> OtherExpr (("ArrayAccessEmpty", lb), [ E e; Tk lb; Tk rb ]) |> G.e and map_binary_expression (env : env) (x : CST.binary_expression) : expr = match x with | `Exp_AMPAMP_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* "&&" *) token env v2 in let v3 = map_expression env v3 in G.opcall (And, v2) [ v1; v3 ] | `Exp_BARBAR_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* "||" *) token env v2 in let v3 = map_expression env v3 in G.opcall (Or, v2) [ v1; v3 ] | `Exp_GTGT_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* ">>" *) token env v2 in let v3 = map_expression env v3 in G.opcall (LSR, v2) [ v1; v3 ] | `Exp_GTGTGT_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* ">>>" *) token env v2 in let v3 = map_expression env v3 in G.opcall (ASR, v2) [ v1; v3 ] | `Exp_LTLT_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* "<<" *) token env v2 in let v3 = map_expression env v3 in G.opcall (LSL, v2) [ v1; v3 ] | `Exp_AMP_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* "&" *) token env v2 in let v3 = map_expression env v3 in G.opcall (BitAnd, v2) [ v1; v3 ] | `Exp_HAT_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* "^" *) token env v2 in let v3 = map_expression env v3 in G.opcall (BitXor, v2) [ v1; v3 ] | `Exp_BAR_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* "|" *) token env v2 in let v3 = map_expression env v3 in G.opcall (BitOr, v2) [ v1; v3 ] | `Exp_PLUS_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* "+" *) token env v2 in let v3 = map_expression env v3 in G.opcall (Plus, v2) [ v1; v3 ] | `Exp_DASH_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* "-" *) token env v2 in let v3 = map_expression env v3 in G.opcall (Minus, v2) [ v1; v3 ] | `Exp_STAR_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* "*" *) token env v2 in let v3 = map_expression env v3 in G.opcall (Mult, v2) [ v1; v3 ] | `Exp_SLASH_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* "/" *) token env v2 in let v3 = map_expression env v3 in G.opcall (Div, v2) [ v1; v3 ] | `Exp_PERC_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* "%" *) token env v2 in let v3 = map_expression env v3 in G.opcall (Mod, v2) [ v1; v3 ] | `Exp_STARSTAR_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* "**" *) token env v2 in let v3 = map_expression env v3 in G.opcall (Pow, v2) [ v1; v3 ] | `Exp_LT_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* "<" *) token env v2 in let v3 = map_expression env v3 in G.opcall (Lt, v2) [ v1; v3 ] | `Exp_LTEQ_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* "<=" *) token env v2 in let v3 = map_expression env v3 in G.opcall (LtE, v2) [ v1; v3 ] | `Exp_EQEQ_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* "==" *) token env v2 in let v3 = map_expression env v3 in (* TODO: or PhysEq? *) G.opcall (Eq, v2) [ v1; v3 ] | `Exp_BANGEQ_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* "!=" *) token env v2 in let v3 = map_expression env v3 in G.opcall (NotEq, v2) [ v1; v3 ] | `Exp_BANGEQEQ_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* "!==" *) token env v2 in let v3 = map_expression env v3 in G.opcall (NotPhysEq, v2) [ v1; v3 ] | `Exp_GTEQ_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* ">=" *) token env v2 in let v3 = map_expression env v3 in G.opcall (GtE, v2) [ v1; v3 ] | `Exp_GT_exp (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = (* ">" *) token env v2 in let v3 = map_expression env v3 in G.opcall (Gt, v2) [ v1; v3 ] and map_call_arguments (env : env) ((v1, v2, v3) : CST.call_arguments) : arguments = let lp = (* "(" *) token env v1 in let args = match v2 with | Some (v1, v2, v3) -> let v1 = map_anon_choice_exp_5650be1 env v1 in let v2 = Common.map (fun (v1, v2) -> let _v1 = (* "," *) token env v1 in let v2 = map_anon_choice_exp_5650be1 env v2 in v2) v2 in let _v3 = map_trailing_comma env v3 in v1 :: v2 | None -> [] in let rp = (* ")" *) token env v3 in (lp, args, rp) and map_expression (env : env) (x : CST.expression) : expr = match x with | `Choice_bin_exp x -> ( match x with | `Bin_exp x -> map_binary_expression env x | `Un_exp x -> map_unary_expression env x | `Update_exp x -> map_update_expression env x | `Call_exp (v1, v2) -> let e = map_expression env v1 in let args = map_call_arguments env v2 in Call (e, args) |> G.e | `Paya_conv_exp (v1, v2) -> (* TODO: add to special? *) let id = (* "payable" *) str env v1 in let args = map_call_arguments env v2 in let n = N (H2.name_of_id id) |> G.e in Call (n, args) |> G.e | `Meta_type_exp (v1, v2, v3, v4) -> let ttype = (* "type" *) token env v1 in let lp = (* "(" *) token env v2 in let t = map_type_name env v3 in let rp = (* ")" *) token env v4 in let arg = ArgType t in let op = IdSpecial (Typeof, ttype) |> G.e in Call (op, (lp, [ arg ], rp)) |> G.e | `Prim_exp x -> map_primary_expression env x | `Struct_exp (v1, v2, v3, v4) -> let e = map_expression env v1 in let lb = (* "{" *) token env v2 in let flds = match v3 with | Some (v1, v2, v3, v4, v5) -> let fld_id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v1 in let _tcolon = (* ":" *) token env v2 in let e = map_expression env v3 in let xs = Common.map (fun (v1, v2, v3, v4) -> let _v1 = (* "," *) token env v1 in let fld_id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v2 in let _tcolon = (* ":" *) token env v3 in let e = map_expression env v4 in (fld_id, e)) v4 in let _v5 = map_trailing_comma env v5 in (fld_id, e) :: xs | None -> [] in let rb = (* "}" *) token env v4 in (* TODO? kind of New? or a With? *) let flds_any = flds |> Common.map (fun (fld_id, e) -> [ I fld_id; E e ]) |> List.flatten in OtherExpr (("StructExpr", lb), [ E e; Tk lb ] @ flds_any @ [ Tk rb ]) |> G.e | `Tern_exp (v1, v2, v3, v4, v5) -> let e1 = map_expression env v1 in let _question = (* "?" *) token env v2 in let e2 = map_expression env v3 in let _colon = (* ":" *) token env v4 in let e3 = map_expression env v5 in Conditional (e1, e2, e3) |> G.e | `Type_cast_exp (v1, v2, v3, v4) -> let t = map_primitive_type env v1 in let lp = (* "(" *) token env v2 in let e = map_expression env v3 in let _rp = (* ")" *) token env v4 in Cast (t, lp, e) |> G.e) | `Ellips tok -> Ellipsis ((* "..." *) token env tok) |> G.e | `Deep_ellips (v1, v2, v3) -> let l = (* "<..." *) token env v1 in let e = map_expression env v2 in let r = (* "...>" *) token env v3 in DeepEllipsis (l, e, r) |> G.e | `Member_ellips_exp (v1, v2, v3) -> let e = map_anon_choice_exp_97f816a env v1 in let _tdot = (* "." *) token env v2 in let tdots = (* "..." *) token env v3 in DotAccessEllipsis (e, tdots) |> G.e and map_anon_choice_exp_97f816a (env : env) (x : CST.anon_choice_exp_97f816a) = match x with | `Exp x -> map_expression env x | `Id tok -> let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env tok in N (H2.name_of_id id) |> G.e and map_member_expression (env : env) ((v1, v2, v3) : CST.member_expression) : expr = let e = map_anon_choice_exp_97f816a env v1 in let tdot = (* "." *) token env v2 in let fld = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v3 in DotAccess (e, tdot, FN (H2.name_of_id fld)) |> G.e and map_nameless_parameter (env : env) ((v1, v2) : CST.nameless_parameter) = let t = map_type_name env v1 in let _attrsTODO = match v2 with | Some x -> [ map_storage_location env x ] | None -> [] in t and map_parameter (env : env) (x : CST.parameter) : parameter = match x with | `Type_name_opt_stor_loca_opt_id (v1, v2, v3) -> let t = map_type_name env v1 in let pattrs = match v2 with | Some x -> [ map_storage_location env x ] | None -> [] in let pname = match v3 with | Some tok -> (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) Some (str env tok) | None -> None in Param (G.param_of_type ~pattrs ~pname t) | `Ellips tok -> ParamEllipsis ((* "..." *) token env tok) and map_parameter_list (env : env) ((v1, v2, v3) : CST.parameter_list) : parameters = let lp = (* "(" *) token env v1 in let params = match v2 with | Some (v1, v2, v3) -> let v1 = map_parameter env v1 in let v2 = Common.map (fun (v1, v2) -> let _v1 = (* "," *) token env v1 in let v2 = map_parameter env v2 in v2) v2 in let _v3 = map_trailing_comma env v3 in v1 :: v2 | None -> [] in let rp = (* ")" *) token env v3 in (lp, params, rp) and map_parenthesized_expression (env : env) ((v1, v2, v3) : CST.parenthesized_expression) : expr = let _lp = (* "(" *) token env v1 in let e = map_expression env v2 in let _rp = (* ")" *) token env v3 in (* alt: ParenExpr (lp, e, rp) |> G.e *) e and map_primary_expression (env : env) (x : CST.primary_expression) : expr = match x with | `Paren_exp x -> map_parenthesized_expression env x | `Member_exp x -> map_member_expression env x | `Array_access x -> map_array_access env x | `Slice_access (v1, v2, v3, v4, v5, v6) -> let e = map_expression env v1 in let lb = (* "[" *) token env v2 in let lower_opt = Option.map (map_expression env) v3 in let _tcolon = (* ":" *) token env v4 in let upper_opt = Option.map (map_expression env) v5 in let rb = (* "]" *) token env v6 in SliceAccess (e, (lb, (lower_opt, upper_opt, None), rb)) |> G.e (* TODO: what is that? *) | `Prim_type x -> let t = map_primitive_type env x in OtherExpr (("TypeExpr", fake ""), [ T t ]) |> G.e | `Assign_exp (v1, v2, v3) -> let lhs = map_expression env v1 in let teq = (* "=" *) token env v2 in let rhs = map_expression env v3 in Assign (lhs, teq, rhs) |> G.e | `Augm_assign_exp (v1, v2, v3) -> let lhs = map_expression env v1 in let op = match v2 with | `PLUSEQ tok -> (* "+=" *) (Plus, token env tok) | `DASHEQ tok -> (* "-=" *) (Minus, token env tok) | `STAREQ tok -> (* "*=" *) (Mult, token env tok) | `SLASHEQ tok -> (* "/=" *) (Div, token env tok) | `PERCEQ tok -> (* "%=" *) (Mod, token env tok) | `HATEQ tok -> (* "^=" *) (BitXor, token env tok) | `AMPEQ tok -> (* "&=" *) (BitAnd, token env tok) | `BAREQ tok -> (* "|=" *) (BitOr, token env tok) | `GTGTEQ tok -> (* ">>=" *) (LSR, token env tok) | `GTGTGTEQ tok -> (* ">>>=" *) (ASR, token env tok) | `LTLTEQ tok -> (* "<<=" *) (LSL, token env tok) in let rhs = map_expression env v3 in AssignOp (lhs, op, rhs) |> G.e (* TODO: this is actually not a type, but in grammar.js maybe because * of ambiguities it uses this instead of a 'path_identifier' *) | `User_defi_type x -> let n = map_user_defined_type env x in N n |> G.e | `Tuple_exp x -> map_tuple_expression env x | `Inline_array_exp (v1, v2, v3) -> let lb = (* "[" *) token env v1 in let es = match v2 with | Some (v1, v2, v3) -> let v1 = map_expression env v1 in let v2 = Common.map (fun (v1, v2) -> let _v1 = (* "," *) token env v1 in let v2 = map_expression env v2 in v2) v2 in let _v3 = map_trailing_comma env v3 in v1 :: v2 | None -> [] in let rb = (* "]" *) token env v3 in OtherExpr ( ("InlineArray", lb), [ Tk lb ] @ (es |> Common.map (fun e -> E e)) @ [ Tk rb ] ) |> G.e | `Id tok -> let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env tok in N (H2.name_of_id id) |> G.e | `Lit x -> map_literal env x | `New_exp (v1, v2, v3) -> ( let tnew = (* "new" *) token env v1 in let t = map_type_name env v2 in let argsopt = match v3 with | Some x -> Some (map_call_arguments env x) | None -> None in match argsopt with | None -> New (tnew, t, fb []) |> G.e | Some (lp, es, rp) -> New (tnew, t, (lp, es, rp)) |> G.e) and map_return_parameters (env : env) ((v0, v1, v2, v3, v4, v5) : CST.return_parameters) : type_ = let _tret = (* returns *) token env v0 in let lp = (* "(" *) token env v1 in let v2 = map_nameless_parameter env v2 in let v3 = Common.map (fun (v1, v2) -> let _v1 = (* "," *) token env v1 in let v2 = map_nameless_parameter env v2 in v2) v3 in let _v4 = map_trailing_comma env v4 in let rp = (* ")" *) token env v5 in TyTuple (lp, v2 :: v3, rp) |> G.t and map_tuple_expression (env : env) ((v1, v2, v3, v4) : CST.tuple_expression) : expr = let lp = (* "(" *) token env v1 in let v2 = match v2 with | Some x -> map_expression env x | None -> tuple_hole_expr env lp in let v3 = Common.map (fun (v1, v2) -> let tcomma = (* "," *) token env v1 in let e = match v2 with | Some x -> map_expression env x | None -> tuple_hole_expr env tcomma in e) v3 in let rp = (* ")" *) token env v4 in Container (Tuple, (lp, v2 :: v3, rp)) |> G.e and map_type_name (env : env) (x : CST.type_name) : type_ = match x with | `Prim_type x -> map_primitive_type env x | `User_defi_type x -> let n = map_user_defined_type env x in TyN n |> G.t | `Mapp (v1, v2, v3, v4, v5, v6) -> let idmap = (* "mapping" *) str env v1 in let lp = (* "(" *) token env v2 in let tkey = map_mapping_key env v3 in let _tarrow = (* "=>" *) token env v4 in let tval = map_type_name env v5 in let rp = (* ")" *) token env v6 in let n = H2.name_of_id idmap in let targs = [ tkey; tval ] |> Common.map (fun t -> TA t) in TyApply (TyN n |> G.t, (lp, targs, rp)) |> G.t | `Array_type (v1, v2, v3, v4) -> let t = map_type_name env v1 in let lb = (* "[" *) token env v2 in let eopt = match v3 with | Some x -> Some (map_expression env x) | None -> None in let rb = (* "]" *) token env v4 in TyArray ((lb, eopt, rb), t) |> G.t | `Func_type (v1, v2, v3, v4) -> let tfunc = (* "function" *) token env v1 in let _, params, _ = map_parameter_list env v2 in let _v3TODO = Common.map (fun x -> match x with | `Visi x -> map_visibility env x | `State_muta x -> map_state_mutability env x) v3 in let tret = match v4 with | Some x -> map_return_parameters env x | None -> G.ty_builtin ("void", tfunc) in TyFun (params, tret) |> G.t and map_unary_expression (env : env) (x : CST.unary_expression) : expr = match x with | `BANG_exp (v1, v2) -> let v1 = (* "!" *) token env v1 in let v2 = map_expression env v2 in G.opcall (Not, v1) [ v2 ] | `TILDE_exp (v1, v2) -> let v1 = (* "~" *) token env v1 in let v2 = map_expression env v2 in G.opcall (BitNot, v1) [ v2 ] | `DASH_exp (v1, v2) -> let v1 = (* "-" *) token env v1 in let v2 = map_expression env v2 in G.opcall (Minus, v1) [ v2 ] | `PLUS_exp (v1, v2) -> let v1 = (* "+" *) token env v1 in let v2 = map_expression env v2 in G.opcall (Plus, v1) [ v2 ] | `Delete_exp (v1, v2) -> let v1 = (* "delete" *) token env v1 in let v2 = map_expression env v2 in OtherExpr (("Delete", v1), [ E v2 ]) |> G.e and map_update_expression (env : env) (x : CST.update_expression) = match x with | `Exp_choice_PLUSPLUS (v1, v2) -> let e = map_expression env v1 in let op, t = map_anon_choice_PLUSPLUS_e498e28 env v2 in G.special (IncrDecr (op, Postfix), t) [ e ] | `Choice_PLUSPLUS_exp (v1, v2) -> let op, t = map_anon_choice_PLUSPLUS_e498e28 env v1 in let e = map_expression env v2 in G.special (IncrDecr (op, Prefix), t) [ e ] let rec map_yul_block (env : env) ((v1, v2, v3) : CST.yul_block) = let lb = (* "{" *) token env v1 in let xs = Common.map (map_yul_statement env) v2 in let rb = (* "}" *) token env v3 in Block (lb, xs, rb) |> G.s and map_yul_statement (env : env) (x : CST.yul_statement) : stmt = match x with | `Yul_blk x -> map_yul_block env x | `Yul_var_decl x -> let def = map_yul_variable_declaration env x in DefStmt def |> G.s | `Yul_assign x -> let e = map_yul_assignment env x in G.exprstmt e | `Yul_func_call x -> let e = map_yul_function_call env x in G.exprstmt e | `Yul_if_stmt (v1, v2, v3) -> let tif = (* "if" *) token env v1 in let cond = map_yul_expression env v2 in let then_ = map_yul_block env v3 in If (tif, Cond cond, then_, None) |> G.s | `Yul_for_stmt (v1, v2, v3, v4, v5) -> let tfor = (* "for" *) token env v1 in let init = map_yul_block env v2 in let cond = map_yul_expression env v3 in let post_iter = map_yul_block env v4 in let body = map_yul_block env v5 in (* TODO: change AST_generic.for_header? ugly to use stmt_to_expr *) let init = [ ForInitExpr (G.stmt_to_expr init) ] in let post = G.stmt_to_expr post_iter in For (tfor, ForClassic (init, Some cond, Some post), body) |> G.s | `Yul_switch_stmt (v1, v2, v3) -> let tswitch = (* "switch" *) token env v1 in let cond = map_yul_expression env v2 in let cases_and_body = match v3 with | `Defa_yul_blk (v1, v2) -> let tdefault = (* "default" *) token env v1 in let st = map_yul_block env v2 in [ CasesAndBody ([ Default tdefault ], st) ] | `Rep1_case_yul_lit_yul_blk_opt_defa_yul_blk (v1, v2) -> let v1 = Common.map (fun (v1, v2, v3) -> let tcase = (* "case" *) token env v1 in let lit = map_yul_literal env v2 in let st = map_yul_block env v3 in CasesAndBody ([ Case (tcase, PatLiteral lit) ], st)) v1 in let v2 = match v2 with | Some (v1, v2) -> let tdefault = (* "default" *) token env v1 in let st = map_yul_block env v2 in [ CasesAndBody ([ Default tdefault ], st) ] | None -> [] in v1 @ v2 in Switch (tswitch, Some (Cond cond), cases_and_body) |> G.s | `Yul_leave tok -> let x = (* "leave" *) token env tok in OtherStmt (OS_Todo, [ G.TodoK ("Leave", x) ]) |> G.s | `Yul_brk tok -> let x = (* "break" *) token env tok in Break (x, LNone, G.sc) |> G.s | `Yul_cont tok -> let x = (* "continue" *) token env tok in Continue (x, LNone, G.sc) |> G.s | `Yul_func_defi (v1, v2, v3, v4, v5, v6, v7) -> let tfunc = (* "function" *) token env v1 in let id = (* pattern [a-zA-Z$_]+ *) str env v2 in let _lp = (* "(" *) token env v3 in let ids = match v4 with | Some x -> map_anon_yul_id_rep_COMMA_yul_id_opt_COMMA_477546e env x | None -> [] in let _rp = (* ")" *) token env v5 in let tret = match v6 with | Some (v1, v2, v3, v4) -> ( let _tarrow = (* "->" *) token env v1 in let v2 = (* pattern [a-zA-Z$_]+ *) str env v2 in let v3 = Common.map (fun (v1, v2) -> let _v1 = (* "," *) token env v1 in let v2 = (* pattern [a-zA-Z$_]+ *) str env v2 in v2) v3 in let _v4 = map_trailing_comma env v4 in match v2 :: v3 with | [] -> raise Impossible | [ id ] -> Some (TyN (H2.name_of_id id) |> G.t) | xs -> Some (TyTuple (fb (xs |> Common.map (fun id -> TyN (H2.name_of_id id) |> G.t) )) |> G.t)) | None -> None in let body = map_yul_block env v7 in let ent = G.basic_entity id in let params = ids |> Common.map (fun id -> Param (G.param_of_id id)) in let def = { fkind = (Function, tfunc); fparams = fb params; frettype = tret; fbody = FBStmt body; } in DefStmt (ent, FuncDef def) |> G.s | `Yul_label (v1, v2) -> let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v1 in let tcol = (* ":" *) token env v2 in (* TODO: change in Label? but following stmt? There is a goto? *) OtherStmt (OS_Todo, [ TodoK ("Label", tcol); I id ]) |> G.s | `Yul_lit x -> let x = map_yul_literal env x in G.exprstmt (L x |> G.e) let map_state_variable_declaration (env : env) ((v1, v2, v3, v4, v5) : CST.state_variable_declaration) : definition = let ty = map_type_name env v1 in let attrs = Common.map (fun x -> match x with | `Visi x -> map_visibility env x | `Cst tok -> let x = (* "constant" *) token env tok in G.attr Const x | `Over_spec x -> let x = map_override_specifier env x in x (* TODO: difference between constant and immutable? *) | `Immu tok -> (* "immutable" *) str env tok |> G.unhandled_keywordattr) v2 in let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v3 in let vinit = match v4 with | Some (v1, v2) -> let _v1 = (* "=" *) token env v1 in let v2 = map_expression env v2 in Some v2 | None -> None in let _sc = (* ";" *) token env v5 in let ent = G.basic_entity ~attrs id in let def = { vinit; vtype = Some ty } in (ent, VarDef def) let map_modifier_invocation (env : env) ((v1, v2) : CST.modifier_invocation) : attribute = let name = map_identifier_path env v1 in let args = match v2 with | Some x -> map_call_arguments env x | None -> fb [] in NamedAttr (fake "@", name, args) let map_expression_statement (env : env) (x : CST.expression_statement) = match x with | `Exp_semi (v1, v2) -> let e = map_expression env v1 in let sc = (* ";" *) token env v2 in (e, sc) | `Ellips_SEMI (v1, v2) -> let tdots = (* "..." *) token env v1 in let sc = (* ";" *) token env v2 in (Ellipsis tdots |> G.e, sc) | `Ellips tok -> let tdots = (* "..." *) token env tok in (Ellipsis tdots |> G.e, G.sc) let map_struct_member (env : env) (x : CST.struct_member) : field = match x with | `Type_name_id_semi (v1, v2, v3) -> let ty = map_type_name env v1 in let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v2 in let _sc = (* ";" *) token env v3 in G.basic_field id None (Some ty) | `Ellips tok -> G.fieldEllipsis ((* "..." *) token env tok) let map_inheritance_specifier (env : env) (v1 : CST.inheritance_specifier) : class_parent = match v1 with | `Ellips tok -> (G.TyEllipsis (token env tok) |> G.t, None) | `User_defi_type_opt_call_args (v1, v2) -> let n = map_user_defined_type env v1 in let ty = TyN n |> G.t in let argsopt = match v2 with | Some x -> Some (map_call_arguments env x) | None -> None in (ty, argsopt) let map_event_paramater (env : env) ((v1, v2, v3) : CST.event_paramater) : parameter_classic = let ty = map_type_name env v1 in let pattrs = match v2 with | Some tok -> [ G.unhandled_keywordattr (* "indexed" *) (str env tok) ] | None -> [] in let idopt = match v3 with | Some tok -> (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) Some (str env tok) | None -> None in G.param_of_type ~pattrs ~pname:idopt ty let map_return_type_definition (env : env) ((v1, v2) : CST.return_type_definition) = let tret = (* "returns" *) token env v1 in let params = map_parameter_list env v2 in (tret, params) let map_variable_declaration (env : env) ((v1, v2, v3) : CST.variable_declaration) = let ty = map_type_name env v1 in let attrs = match v2 with | Some x -> [ map_storage_location env x ] | None -> [] in let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v3 in (ty, attrs, id) let map_using_directive (env : env) ((v1, v2, v3, v4, v5) : CST.using_directive) : directive = (* TODO: a bit similar to an Import *) let tusing = (* "using" *) token env v1 in let n1 = map_user_defined_type env v2 in let ty1 = TyN n1 |> G.t in (* ?? some kind of mixins? *) let tfor = (* "for" *) token env v3 in let ty2 = match v4 with | `Any_source_type tok -> let star = (* "*" *) str env tok in TyN (H2.name_of_id star) |> G.t | `Type_name x -> map_type_name env x in let sc = (* ";" *) token env v5 in OtherDirective (("Using", tusing), [ T ty1; Tk tfor; T ty2; Tk sc ]) |> G.d let map_struct_declaration (env : env) ((v1, v2, v3, v4, v5) : CST.struct_declaration) : definition = let tstruct = (* "struct" *) token env v1 in let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v2 in let lb = (* "{" *) token env v3 in let flds = Common.map (map_struct_member env) v4 in let rb = (* "}" *) token env v5 in let ent = G.basic_entity id in let def = { ckind = (Class, tstruct); cextends = []; cimplements = []; cmixins = []; cparams = fb []; cbody = (lb, flds, rb); } in (ent, ClassDef def) let map_class_heritage (env : env) ((v1, v2, v3, v4) : CST.class_heritage) : class_parent list = let _tis = (* "is" *) token env v1 in let v2 = map_inheritance_specifier env v2 in let v3 = Common.map (fun (v1, v2) -> let _v1 = (* "," *) token env v1 in let v2 = map_inheritance_specifier env v2 in v2) v3 in let _v4 = map_trailing_comma env v4 in v2 :: v3 let map_event_parameter_list (env : env) ((v1, v2, v3) : CST.event_parameter_list) = let lb = (* "(" *) token env v1 in let xs = match v2 with | Some (v1, v2, v3) -> let v1 = map_event_paramater env v1 in let v2 = Common.map (fun (v1, v2) -> let _v1 = (* "," *) token env v1 in let v2 = map_event_paramater env v2 in v2) v2 in let _v3 = map_trailing_comma env v3 in v1 :: v2 | None -> [] in let rb = (* ")" *) token env v3 in (lb, xs, rb) let map_variable_declaration_tuple (env : env) (x : CST.variable_declaration_tuple) : pattern = match x with | `LPAR_opt_opt_var_decl_rep_COMMA_opt_var_decl_opt_COMMA_RPAR (v1, v2, v3) -> let lp = (* "(" *) token env v1 in let xs = match v2 with | Some (v1, v2, v3) -> let v1 = Option.map (map_variable_declaration env) v1 in let v2 = Common.map (fun (v1, v2) -> let _v1 = (* "," *) token env v1 in let v2 = Option.map (map_variable_declaration env) v2 in v2) v2 in let _v3 = map_trailing_comma env v3 in v1 :: v2 (* TODO: should generate hole pattern when using (x,,y) *) |> Common.map_filter (fun x -> x) |> Common.map (fun (ty, _attrsTODO, id) -> PatTyped (PatId (id, G.empty_id_info ()) |> G.p, ty) |> G.p) | None -> [] in let rp = (* ")" *) token env v3 in PatTuple (lp, xs, rp) |> G.p | `Var_LPAR_opt_id_rep_COMMA_opt_id_RPAR (v1, v2, v3, v4, v5) -> let _tvar = (* "var" *) token env v1 in let lp = (* "(" *) token env v2 in let p = match v3 with | Some tok -> let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env tok in PatId (id, G.empty_id_info ()) |> G.p | None -> tuple_hole_pat env lp in let ps = Common.map (fun (v1, v2) -> let tcomma = (* "," *) token env v1 in let pat = match v2 with | Some tok -> let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env tok in PatId (id, G.empty_id_info ()) |> G.p | None -> tuple_hole_pat env tcomma in pat) v4 in let rp = (* ")" *) token env v5 in PatTuple (lp, p :: ps, rp) |> G.p let map_event_definition (env : env) ((v1, v2, v3, v4, v5) : CST.event_definition) : definition = let tevent = (* "event" *) token env v1 in let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v2 in let _lp, params, _rp = map_event_parameter_list env v3 in let attrs = match v4 with | Some tok -> (* "anonymous" *) [ str env tok |> G.unhandled_keywordattr ] | None -> [] in let _sc = (* ";" *) token env v5 in let ent = G.basic_entity id ~attrs in let anys = params |> Common.map (fun pclassic -> Pa (Param pclassic)) in (ent, OtherDef (("Event", tevent), anys)) let map_variable_declaration_statement (env : env) ((v1, v2) : CST.variable_declaration_statement) : entity * variable_definition = let def = match v1 with | `Var_decl_opt_EQ_exp (v1, v2) -> let ty, attrs, id = map_variable_declaration env v1 in let vinit = match v2 with | Some (v1, v2) -> let _teq = (* "=" *) token env v1 in let e = map_expression env v2 in Some e | None -> None in let ent = G.basic_entity id ~attrs in let vdef = { vinit; vtype = Some ty } in (ent, vdef) | `Var_decl_tuple_EQ_exp (v1, v2, v3) -> let pat = map_variable_declaration_tuple env v1 in let _teq = (* "=" *) token env v2 in let e = map_expression env v3 in let ent = { name = EPattern pat; attrs = []; tparams = [] } in let vdef = { vinit = Some e; vtype = None } in (ent, vdef) in let _sc = (* ";" *) token env v2 in def let rec map_block_statement (env : env) ((v0, v1, v2, v3) : CST.block_statement) = let lb = (* "{" *) token env v1 in let xs = Common.map (map_statement env) v2 in let rb = (* "}" *) token env v3 in let stmt = Block (lb, xs, rb) |> G.s in match v0 with | Some tok -> let t = (* "unchecked" *) token env tok in OtherStmtWithStmt (OSWS_Block ("Unchecked", t), [], stmt) |> G.s | None -> stmt and map_catch_clause (env : env) ((v1, v2, v3) : CST.catch_clause) : catch = let tcatch = (* "catch" *) token env v1 in let catch_exn : catch_exn = match v2 with | Some (v1, v2) -> let idopt = match v1 with | Some tok -> (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) [ I (str env tok) ] | None -> [] in let _l, params, _r = map_parameter_list env v2 in let anys = idopt @ (params |> Common.map (fun p -> Pa p)) in OtherCatch (("CatchParams", tcatch), anys) | None -> OtherCatch (("CatchEmpty", tcatch), []) in let st = map_block_statement env v3 in (tcatch, catch_exn, st) and map_statement (env : env) (x : CST.statement) : stmt = match x with | `Blk_stmt x -> map_block_statement env x | `Exp_stmt x -> let e, sc = map_expression_statement env x in ExprStmt (e, sc) |> G.s | `Var_decl_stmt x -> let ent, vdef = map_variable_declaration_statement env x in DefStmt (ent, VarDef vdef) |> G.s | `If_stmt (v1, v2, v3, v4, v5, v6) -> let tif = (* "if" *) token env v1 in let _lp = (* "(" *) token env v2 in let cond = map_expression env v3 in let _rp = (* ")" *) token env v4 in let then_ = map_statement env v5 in let else_opt = match v6 with | Some (v1, v2) -> let _telse = (* "else" *) token env v1 in let st = map_statement env v2 in Some st | None -> None in If (tif, Cond cond, then_, else_opt) |> G.s | `For_stmt v1 -> map_for_statement env v1 | `While_stmt (v1, v2, v3, v4, v5) -> let twhile = (* "while" *) token env v1 in let _lp = (* "(" *) token env v2 in let cond = map_expression env v3 in let _rp = (* ")" *) token env v4 in let st = map_statement env v5 in While (twhile, Cond cond, st) |> G.s | `Do_while_stmt (v1, v2, v3, v4, v5, v6, v7) -> let tdo = (* "do" *) token env v1 in let st = map_statement env v2 in let _twhile = (* "while" *) token env v3 in let _lp = (* "(" *) token env v4 in let cond = map_expression env v5 in let _rp = (* ")" *) token env v6 in let _sc = (* ";" *) token env v7 in DoWhile (tdo, st, cond) |> G.s | `Cont_stmt (v1, v2) -> let tcont = (* "continue" *) token env v1 in let sc = (* ";" *) token env v2 in Continue (tcont, LNone, sc) |> G.s | `Brk_stmt (v1, v2) -> let tbreak = (* "break" *) token env v1 in let sc = (* ";" *) token env v2 in Continue (tbreak, LNone, sc) |> G.s | `Try_stmt (v1, v2, v3, v4, v5) -> let ttry = (* "try" *) token env v1 in (* Solidity try statement is a bit unusual, see for example: * try foo() (Param p1, Param p2) { return p1; } catch { return 1; } * We internally convert part of it in a Lambda below, for the example: * try ((Param p1, Param p2) -> { return p; })(foo()) catch {...}. * There is no Lambda construct in Solidity so we don't risk * a collision with other constructs. *) (* must be an external funcall or contract creation according to doc *) let e = map_expression env v2 in let params = match v3 with | Some x -> let _treturn, params = map_return_type_definition env x in params | None -> fb [] in let st = map_block_statement env v4 in let fun_ = { fkind = (LambdaKind, ttry); fparams = params; frettype = None; fbody = FBStmt st; } in let lambda = Lambda fun_ |> G.e in let call = Call (lambda, fb [ Arg e ]) |> G.e in let try_stmt = G.exprstmt call in let catches = Common.map (map_catch_clause env) v5 in Try (ttry, try_stmt, catches, None) |> G.s | `Ret_stmt (v1, v2, v3) -> let tret = (* "return" *) token env v1 in let eopt = match v2 with | Some x -> Some (map_expression env x) | None -> None in let sc = (* ";" *) token env v3 in Return (tret, eopt, sc) |> G.s | `Emit_stmt (v1, v2, v3, v4) -> let temit = (* "emit" *) token env v1 in let e = map_expression env v2 in let _lp, args, _rp = map_call_arguments env v3 in let sc = (* ";" *) token env v4 in OtherStmt (OS_Todo, [ TodoK ("Emit", temit); E e; Args args; Tk sc ]) |> G.s | `Asse_stmt (v1, v2, v3, v4, v5) -> let tassembly = (* "assembly" *) token env v1 in let _evmasm = match v2 with | Some tok -> (* "\"evmasm\"" *) Some (token env tok) | None -> None in let lb = (* "{" *) token env v3 in let xs = Common.map (map_yul_statement env) v4 in let rb = (* "}" *) token env v5 in let st = Block (lb, xs, rb) |> G.s in OtherStmtWithStmt (OSWS_Block ("Assembly", tassembly), [], st) |> G.s | `Revert_stmt (v1, v2, v3) -> let revert = (* "revert" *) str env v1 in (* less: could be a OtherExpr or OtherStmt *) let name = H2.name_of_id revert in let e = N name |> G.e in let e = match v2 with | Some (v1, v2) -> let op = match v1 with | Some x -> let e1 = map_expression env x in Call (e, fb [ Arg e1 ]) |> G.e | None -> e in let v2 = map_call_arguments env v2 in Call (op, v2) |> G.e | None -> e in let sc = (* ";" *) token env v3 in ExprStmt (e, sc) |> G.s and map_for_statement env v = match v with | `For_LPAR_choice_var_decl_stmt_choice_exp_stmt_opt_exp_RPAR_stmt (v1, v2, v3, v4, v5, v6, v7) -> let tfor = (* "for" *) token env v1 in let _lp = (* "(" *) token env v2 in let init = match v3 with | `Var_decl_stmt x -> let ent, vdef = map_variable_declaration_statement env x in [ ForInitVar (ent, vdef) ] | `Exp_stmt x -> let e, _sc = map_expression_statement env x in [ ForInitExpr e ] | `Semi tok -> (* ";" *) let _sc = token env tok in [] in let cond = match v4 with | `Exp_stmt x -> let e, _sc = map_expression_statement env x in Some e | `Semi tok -> let _sc = (* ";" *) token env tok in None in let post = match v5 with | Some x -> Some (map_expression env x) | None -> None in let _rp = (* ")" *) token env v6 in let st = map_statement env v7 in For (tfor, ForClassic (init, cond, post), st) |> G.s | `For_LPAR_ellips_RPAR_stmt (v1, v2, v3, v4, v5) -> let tfor = (* "for" *) token env v1 in let _lp = (* "(" *) token env v2 in let tellipsis = (* "..." *) token env v3 in let _rp = (* ")" *) token env v4 in let st = map_statement env v5 in For (tfor, ForEllipsis tellipsis, st) |> G.s let map_function_body (env : env) ((v1, v2, v3) : CST.function_body) : function_body = let lb = (* "{" *) token env v1 in let xs = Common.map (map_statement env) v2 in let rb = (* "}" *) token env v3 in FBStmt (Block (lb, xs, rb) |> G.s) let map_constructor_definition (env : env) ((v1, v2, v3, v4) : CST.constructor_definition) = let tctor = (* "constructor" *) token env v1 in let params = map_parameter_list env v2 in let attrs = Common.map (fun x -> match x with | `Modi_invo x -> map_modifier_invocation env x | `Paya tok -> (* "payable" *) str env tok |> G.unhandled_keywordattr | `Choice_inte x -> ( match x with | `Inte tok -> (* "internal" *) str env tok |> G.unhandled_keywordattr | `Public tok -> G.attr Public (* "public" *) (token env tok))) v3 in let fbody = map_function_body env v4 in let ctor_attr = G.attr Ctor tctor in let attrs = ctor_attr :: attrs in let ent = G.basic_entity ("constructor", tctor) ~attrs in let def = { fkind = (Method, tctor); fparams = params; frettype = None; fbody } in (ent, FuncDef def) let map_anon_choice_semi_f2fe6be (env : env) (x : CST.anon_choice_semi_f2fe6be) : function_body = match x with | `Semi tok -> let sc = (* ";" *) token env tok in FBDecl sc | `Func_body x -> let x = map_function_body env x in x let visi_and_co env x : attribute = match x with | `Visi x -> map_visibility env x | `Modi_invo x -> map_modifier_invocation env x | `State_muta x -> map_state_mutability env x | `Virt tok -> let x = (* "virtual" *) token env tok in G.attr Abstract x | `Over_spec x -> map_override_specifier env x let map_fallback_receive_definition (env : env) ((v1, v2, v3, v4) : CST.fallback_receive_definition) = let id = match v1 with (* If it has the function kwd before, then it's a regular func. * Without the function kwd it's a "special" function. * Joran defined both in the grammar for backward compatibility. *) | `Choice_fall v1 -> ( match v1 with (* TODO: or use OtherDef to treat those specially? or via * a CTor like attribute? *) | `Fall tok -> (* "fallback" *) str env tok | `Rece tok -> (* "receive" *) str env tok | `Func tok -> (* "function" *) str env tok) (* This is the old syntax for fallback function, just * function() public { ... } according to Joran Honig *) | `Func tok -> (* "function" *) str env tok in let fparams = map_parameter_list env v2 in let attrs = Common.map (fun x -> visi_and_co env x) v3 in let ent = G.basic_entity ~attrs id in let fbody = map_anon_choice_semi_f2fe6be env v4 in let def = { fkind = (Function, snd id); fparams; frettype = None; fbody } in (ent, FuncDef def) let map_function_definition (env : env) ((v1, v2, v3, v4, v5, v6) : CST.function_definition) : definition = let tfunc = (* "function" *) token env v1 in let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v2 in let params = map_parameter_list env v3 in let attrs = Common.map (fun x -> visi_and_co env x) v4 in let _ret_type_TODO = match v5 with | Some x -> Some (map_return_type_definition env x) | None -> None in let fbody = map_anon_choice_semi_f2fe6be env v6 in let ent = G.basic_entity id ~attrs in let def = { fkind = (Function, tfunc); fparams = params; frettype = None; fbody } in (ent, FuncDef def) let map_modifier_definition (env : env) ((v1, v2, v3, v4, v5) : CST.modifier_definition) : definition = let tmodif = (* "modifier" *) token env v1 in let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v2 in let params = match v3 with | Some x -> map_parameter_list env x | None -> fb [] in let attrs = Common.map (fun x -> match x with | `Virt tok -> let t = (* "virtual" *) token env tok in G.attr Abstract t | `Over_spec x -> map_override_specifier env x) v4 in let attrs = G.unhandled_keywordattr ("modifier", tmodif) :: attrs in let fbody = map_anon_choice_semi_f2fe6be env v5 in let ent = G.basic_entity id ~attrs in let def = { (* TODO? add OtherFunc? *) fkind = (Function, tmodif); fparams = params; frettype = None; fbody; } in (ent, FuncDef def) (* less: could return a G.parameter *) let map_error_parameter (env : env) ((v1, v2) : CST.error_parameter) : type_ = let ty = map_type_name env v1 in let _idTODO = match v2 with | Some tok -> Some ((* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env tok) | None -> None in ty let map_error_declaration (env : env) ((v1, v2, v3, v4, v5, v6) : CST.error_declaration) : definition = let _terror = (* "error" *) token env v1 in let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v2 in let _lp = (* "(" *) token env v3 in let params = match v4 with | Some (v1, v2, v3) -> let v1 = map_error_parameter env v1 in let v2 = Common.map (fun (v1, v2) -> let _v1 = (* "," *) token env v1 in let v2 = map_error_parameter env v2 in v2) v2 in let _v3 = map_trailing_comma env v3 in v1 :: v2 | None -> [] in let _rp = (* ")" *) token env v5 in let _sc = (* ";" *) token env v6 in let ent = G.basic_entity id in let def = { tbody = Exception (id, params) } in (ent, TypeDef def) let map_contract_member (env : env) (x : CST.contract_member) = match x with | `Choice_func_defi x -> ( match x with | `Func_defi x -> Left3 (map_function_definition env x) | `Modi_defi x -> Left3 (map_modifier_definition env x) | `State_var_decl x -> Left3 (map_state_variable_declaration env x) | `Struct_decl x -> Left3 (map_struct_declaration env x) | `Enum_decl x -> Left3 (map_enum_declaration env x) | `Event_defi x -> Left3 (map_event_definition env x) | `Using_dire x -> Right3 (map_using_directive env x) | `Cons_defi x -> Left3 (map_constructor_definition env x) | `Fall_rece_defi x -> Left3 (map_fallback_receive_definition env x) | `Error_decl x -> Left3 (map_error_declaration env x) | `User_defi_type_defi x -> Left3 (map_user_defined_type_definition env x) ) | `Ellips tok -> let t = (* "..." *) token env tok in Middle3 t let map_contract_body (env : env) ((v1, v2, v3) : CST.contract_body) : (definition, tok, directive) either3 list bracket = let lb = (* "{" *) token env v1 in let xs = Common.map (map_contract_member env) v2 in let rb = (* "}" *) token env v3 in (lb, xs, rb) let map_declaration (env : env) (x : CST.declaration) : definition = match x with | `Cont_decl (v1, v2, v3, v4, v5) -> let attrs = match v1 with | Some tok -> [ G.attr Abstract (* "abstract" *) (token env tok) ] | None -> [] in let tcontract = (* "contract" *) token env v2 in let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v3 in let parents = match v4 with | Some x -> map_class_heritage env x | None -> [] in let l, defs_or_dirs, r = map_contract_body env v5 in let flds = defs_or_dirs |> Common.map (fun x -> F (stmt_of_def_or_dir x)) in let ent = G.basic_entity id ~attrs in let def = { (* ugly: but Class is used for solidity struct, so we need to * choose something else *) ckind = (Object, tcontract); cextends = parents; cmixins = []; cimplements = []; cparams = fb []; cbody = (l, flds, r); } in (ent, ClassDef def) | `Inte_decl (v1, v2, v3, v4) -> let tinter = (* "interface" *) token env v1 in let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v2 in let parents = match v3 with | Some x -> map_class_heritage env x | None -> [] in let l, defs_or_dirs, r = map_contract_body env v4 in let flds = defs_or_dirs |> Common.map (fun x -> F (stmt_of_def_or_dir x)) in let ent = G.basic_entity id in let def = { ckind = (Interface, tinter); cextends = parents; cmixins = []; cimplements = []; cparams = fb []; cbody = (l, flds, r); } in (ent, ClassDef def) | `Libr_decl (v1, v2, v3) -> let _tlib = (* "library" *) token env v1 in let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v2 in let _l, defs_or_dirs, _r = map_contract_body env v3 in let ent = G.basic_entity id in let items = defs_or_dirs |> Common.map stmt_of_def_or_dir in (* TODO: kinda of namespace/module? *) let def = { mbody = ModuleStruct (Some [ id ], items) } in (ent, ModuleDef def) | `Struct_decl x -> map_struct_declaration env x | `Enum_decl x -> map_enum_declaration env x | `Func_defi x -> map_function_definition env x | `Cst_var_decl (v1, v2, v3, v4, v5, v6) -> let ty = map_type_name env v1 in let tconst = (* "constant" *) token env v2 in let id = (* pattern [a-zA-Z$_][a-zA-Z0-9$_]* *) str env v3 in let _teq = (* "=" *) token env v4 in let e = map_expression env v5 in let _sc = (* ";" *) token env v6 in let attr = G.attr Const tconst in let ent = G.basic_entity id ~attrs:[ attr ] in let def = { vtype = Some ty; vinit = Some e } in (ent, VarDef def) | `User_defi_type_defi x -> map_user_defined_type_definition env x | `Error_decl x -> map_error_declaration env x let map_source_unit (env : env) (x : CST.source_unit) : item list = match x with | `Dire x -> let xs = map_directive env x in xs |> Common.map (fun dir -> DirectiveStmt dir |> G.s) | `Decl x -> let def = map_declaration env x in [ DefStmt def |> G.s ] let map_source_file (env : env) (x : CST.source_file) : any = match x with | `Rep_source_unit v1 -> let xxs = Common.map (map_source_unit env) v1 in Pr (List.flatten xxs) | `Rep1_stmt xs -> let xs = Common.map (map_statement env) xs in Ss xs | `Exp x -> let e = map_expression env x in E e | `Modi_defi x -> let x = map_modifier_definition env x in S (DefStmt x |> G.s) | `Cons_defi x -> let x = map_constructor_definition env x in S (DefStmt x |> G.s) (*****************************************************************************) (* Entry point *) (*****************************************************************************) let parse file = H.wrap_parser (fun () -> Tree_sitter_solidity.Parse.file file) (fun cst -> let env = { H.file; conv = H.line_col_to_pos file; extra = () } in match map_source_file env cst with | G.Pr xs | G.Ss xs -> xs | _ -> failwith "not a program") let parse_pattern str = H.wrap_parser (fun () -> Tree_sitter_solidity.Parse.string str) (fun cst -> let file = "<pattern>" in let env = { H.file; conv = Hashtbl.create 0; extra = () } in map_source_file env cst)
(* Yoann Padioleau * * Copyright (c) 2021-2022 R2C * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation, with the * special exception on linking described in file LICENSE. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * LICENSE for more details. *)
async.c
#include "fmacros.h" #include <stdlib.h> #include <string.h> #include <strings.h> #include <assert.h> #include <ctype.h> #include <errno.h> #include "async.h" #include "net.h" #include "dict.c" #include "sds.h" #define _EL_ADD_READ(ctx) do { \ if ((ctx)->ev.addRead) (ctx)->ev.addRead((ctx)->ev.data); \ } while(0) #define _EL_DEL_READ(ctx) do { \ if ((ctx)->ev.delRead) (ctx)->ev.delRead((ctx)->ev.data); \ } while(0) #define _EL_ADD_WRITE(ctx) do { \ if ((ctx)->ev.addWrite) (ctx)->ev.addWrite((ctx)->ev.data); \ } while(0) #define _EL_DEL_WRITE(ctx) do { \ if ((ctx)->ev.delWrite) (ctx)->ev.delWrite((ctx)->ev.data); \ } while(0) #define _EL_CLEANUP(ctx) do { \ if ((ctx)->ev.cleanup) (ctx)->ev.cleanup((ctx)->ev.data); \ } while(0); /* Forward declaration of function in hiredis.c */ int __redisAppendCommand(redisContext *c, const char *cmd, size_t len); /* Functions managing dictionary of callbacks for pub/sub. */ static unsigned int callbackHash(const void *key) { return dictGenHashFunction((const unsigned char *)key, sdslen((const sds)key)); } static void *callbackValDup(void *privdata, const void *src) { ((void) privdata); redisCallback *dup = malloc(sizeof(*dup)); memcpy(dup,src,sizeof(*dup)); return dup; } static int callbackKeyCompare(void *privdata, const void *key1, const void *key2) { int l1, l2; ((void) privdata); l1 = sdslen((const sds)key1); l2 = sdslen((const sds)key2); if (l1 != l2) return 0; return memcmp(key1,key2,l1) == 0; } static void callbackKeyDestructor(void *privdata, void *key) { ((void) privdata); sdsfree((sds)key); } static void callbackValDestructor(void *privdata, void *val) { ((void) privdata); free(val); } static dictType callbackDict = { callbackHash, NULL, callbackValDup, callbackKeyCompare, callbackKeyDestructor, callbackValDestructor }; static redisAsyncContext *redisAsyncInitialize(redisContext *c) { redisAsyncContext *ac; ac = realloc(c,sizeof(redisAsyncContext)); if (ac == NULL) return NULL; c = &(ac->c); /* The regular connect functions will always set the flag REDIS_CONNECTED. * For the async API, we want to wait until the first write event is * received up before setting this flag, so reset it here. */ c->flags &= ~REDIS_CONNECTED; ac->err = 0; ac->errstr = NULL; ac->data = NULL; ac->ev.data = NULL; ac->ev.addRead = NULL; ac->ev.delRead = NULL; ac->ev.addWrite = NULL; ac->ev.delWrite = NULL; ac->ev.cleanup = NULL; ac->onConnect = NULL; ac->onDisconnect = NULL; ac->replies.head = NULL; ac->replies.tail = NULL; ac->sub.invalid.head = NULL; ac->sub.invalid.tail = NULL; ac->sub.channels = dictCreate(&callbackDict,NULL); ac->sub.patterns = dictCreate(&callbackDict,NULL); return ac; } /* We want the error field to be accessible directly instead of requiring * an indirection to the redisContext struct. */ static void __redisAsyncCopyError(redisAsyncContext *ac) { if (!ac) return; redisContext *c = &(ac->c); ac->err = c->err; ac->errstr = c->errstr; } redisAsyncContext *redisAsyncConnect(const char *ip, int port) { redisContext *c; redisAsyncContext *ac; c = redisConnectNonBlock(ip,port); if (c == NULL) return NULL; ac = redisAsyncInitialize(c); if (ac == NULL) { redisFree(c); return NULL; } __redisAsyncCopyError(ac); return ac; } redisAsyncContext *redisAsyncConnectBind(const char *ip, int port, const char *source_addr) { redisContext *c = redisConnectBindNonBlock(ip,port,source_addr); redisAsyncContext *ac = redisAsyncInitialize(c); __redisAsyncCopyError(ac); return ac; } redisAsyncContext *redisAsyncConnectBindWithReuse(const char *ip, int port, const char *source_addr) { redisContext *c = redisConnectBindNonBlockWithReuse(ip,port,source_addr); redisAsyncContext *ac = redisAsyncInitialize(c); __redisAsyncCopyError(ac); return ac; } redisAsyncContext *redisAsyncConnectUnix(const char *path) { redisContext *c; redisAsyncContext *ac; c = redisConnectUnixNonBlock(path); if (c == NULL) return NULL; ac = redisAsyncInitialize(c); if (ac == NULL) { redisFree(c); return NULL; } __redisAsyncCopyError(ac); return ac; } int redisAsyncSetConnectCallback(redisAsyncContext *ac, redisConnectCallback *fn) { if (ac->onConnect == NULL) { ac->onConnect = fn; /* The common way to detect an established connection is to wait for * the first write event to be fired. This assumes the related event * library functions are already set. */ _EL_ADD_WRITE(ac); return REDIS_OK; } return REDIS_ERR; } int redisAsyncSetDisconnectCallback(redisAsyncContext *ac, redisDisconnectCallback *fn) { if (ac->onDisconnect == NULL) { ac->onDisconnect = fn; return REDIS_OK; } return REDIS_ERR; } /* Helper functions to push/shift callbacks */ static int __redisPushCallback(redisCallbackList *list, redisCallback *source) { redisCallback *cb; /* Copy callback from stack to heap */ cb = malloc(sizeof(*cb)); if (cb == NULL) return REDIS_ERR_OOM; if (source != NULL) { memcpy(cb,source,sizeof(*cb)); cb->next = NULL; } /* Store callback in list */ if (list->head == NULL) list->head = cb; if (list->tail != NULL) list->tail->next = cb; list->tail = cb; return REDIS_OK; } static int __redisShiftCallback(redisCallbackList *list, redisCallback *target) { redisCallback *cb = list->head; if (cb != NULL) { list->head = cb->next; if (cb == list->tail) list->tail = NULL; /* Copy callback from heap to stack */ if (target != NULL) memcpy(target,cb,sizeof(*cb)); free(cb); return REDIS_OK; } return REDIS_ERR; } static void __redisRunCallback(redisAsyncContext *ac, redisCallback *cb, redisReply *reply) { redisContext *c = &(ac->c); if (cb->fn != NULL) { c->flags |= REDIS_IN_CALLBACK; cb->fn(ac,reply,cb->privdata); c->flags &= ~REDIS_IN_CALLBACK; } } /* Helper function to free the context. */ static void __redisAsyncFree(redisAsyncContext *ac) { redisContext *c = &(ac->c); redisCallback cb; dictIterator *it; dictEntry *de; /* Execute pending callbacks with NULL reply. */ while (__redisShiftCallback(&ac->replies,&cb) == REDIS_OK) __redisRunCallback(ac,&cb,NULL); /* Execute callbacks for invalid commands */ while (__redisShiftCallback(&ac->sub.invalid,&cb) == REDIS_OK) __redisRunCallback(ac,&cb,NULL); /* Run subscription callbacks callbacks with NULL reply */ it = dictGetIterator(ac->sub.channels); while ((de = dictNext(it)) != NULL) __redisRunCallback(ac,dictGetEntryVal(de),NULL); dictReleaseIterator(it); dictRelease(ac->sub.channels); it = dictGetIterator(ac->sub.patterns); while ((de = dictNext(it)) != NULL) __redisRunCallback(ac,dictGetEntryVal(de),NULL); dictReleaseIterator(it); dictRelease(ac->sub.patterns); /* Signal event lib to clean up */ _EL_CLEANUP(ac); /* Execute disconnect callback. When redisAsyncFree() initiated destroying * this context, the status will always be REDIS_OK. */ if (ac->onDisconnect && (c->flags & REDIS_CONNECTED)) { if (c->flags & REDIS_FREEING) { ac->onDisconnect(ac,REDIS_OK); } else { ac->onDisconnect(ac,(ac->err == 0) ? REDIS_OK : REDIS_ERR); } } /* Cleanup self */ redisFree(c); } /* Free the async context. When this function is called from a callback, * control needs to be returned to redisProcessCallbacks() before actual * free'ing. To do so, a flag is set on the context which is picked up by * redisProcessCallbacks(). Otherwise, the context is immediately free'd. */ void redisAsyncFree(redisAsyncContext *ac) { redisContext *c = &(ac->c); c->flags |= REDIS_FREEING; if (!(c->flags & REDIS_IN_CALLBACK)) __redisAsyncFree(ac); } /* Helper function to make the disconnect happen and clean up. */ static void __redisAsyncDisconnect(redisAsyncContext *ac) { redisContext *c = &(ac->c); /* Make sure error is accessible if there is any */ __redisAsyncCopyError(ac); if (ac->err == 0) { /* For clean disconnects, there should be no pending callbacks. */ int ret = __redisShiftCallback(&ac->replies,NULL); assert(ret == REDIS_ERR); } else { /* Disconnection is caused by an error, make sure that pending * callbacks cannot call new commands. */ c->flags |= REDIS_DISCONNECTING; } /* For non-clean disconnects, __redisAsyncFree() will execute pending * callbacks with a NULL-reply. */ __redisAsyncFree(ac); } /* Tries to do a clean disconnect from Redis, meaning it stops new commands * from being issued, but tries to flush the output buffer and execute * callbacks for all remaining replies. When this function is called from a * callback, there might be more replies and we can safely defer disconnecting * to redisProcessCallbacks(). Otherwise, we can only disconnect immediately * when there are no pending callbacks. */ void redisAsyncDisconnect(redisAsyncContext *ac) { redisContext *c = &(ac->c); c->flags |= REDIS_DISCONNECTING; if (!(c->flags & REDIS_IN_CALLBACK) && ac->replies.head == NULL) __redisAsyncDisconnect(ac); } static int __redisGetSubscribeCallback(redisAsyncContext *ac, redisReply *reply, redisCallback *dstcb) { redisContext *c = &(ac->c); dict *callbacks; dictEntry *de; int pvariant; char *stype; sds sname; /* Custom reply functions are not supported for pub/sub. This will fail * very hard when they are used... */ if (reply->type == REDIS_REPLY_ARRAY) { assert(reply->elements >= 2); assert(reply->element[0]->type == REDIS_REPLY_STRING); stype = reply->element[0]->str; pvariant = (tolower(stype[0]) == 'p') ? 1 : 0; if (pvariant) callbacks = ac->sub.patterns; else callbacks = ac->sub.channels; /* Locate the right callback */ assert(reply->element[1]->type == REDIS_REPLY_STRING); sname = sdsnewlen(reply->element[1]->str,reply->element[1]->len); de = dictFind(callbacks,sname); if (de != NULL) { memcpy(dstcb,dictGetEntryVal(de),sizeof(*dstcb)); /* If this is an unsubscribe message, remove it. */ if (strcasecmp(stype+pvariant,"unsubscribe") == 0) { dictDelete(callbacks,sname); /* If this was the last unsubscribe message, revert to * non-subscribe mode. */ assert(reply->element[2]->type == REDIS_REPLY_INTEGER); if (reply->element[2]->integer == 0) c->flags &= ~REDIS_SUBSCRIBED; } } sdsfree(sname); } else { /* Shift callback for invalid commands. */ __redisShiftCallback(&ac->sub.invalid,dstcb); } return REDIS_OK; } void redisProcessCallbacks(redisAsyncContext *ac) { redisContext *c = &(ac->c); redisCallback cb = {NULL, NULL, NULL}; void *reply = NULL; int status; while((status = redisGetReply(c,&reply)) == REDIS_OK) { if (reply == NULL) { /* When the connection is being disconnected and there are * no more replies, this is the cue to really disconnect. */ if (c->flags & REDIS_DISCONNECTING && sdslen(c->obuf) == 0 && ac->replies.head == NULL) { __redisAsyncDisconnect(ac); return; } /* If monitor mode, repush callback */ if(c->flags & REDIS_MONITORING) { __redisPushCallback(&ac->replies,&cb); } /* When the connection is not being disconnected, simply stop * trying to get replies and wait for the next loop tick. */ break; } /* Even if the context is subscribed, pending regular callbacks will * get a reply before pub/sub messages arrive. */ if (__redisShiftCallback(&ac->replies,&cb) != REDIS_OK) { /* * A spontaneous reply in a not-subscribed context can be the error * reply that is sent when a new connection exceeds the maximum * number of allowed connections on the server side. * * This is seen as an error instead of a regular reply because the * server closes the connection after sending it. * * To prevent the error from being overwritten by an EOF error the * connection is closed here. See issue #43. * * Another possibility is that the server is loading its dataset. * In this case we also want to close the connection, and have the * user wait until the server is ready to take our request. */ if (((redisReply*)reply)->type == REDIS_REPLY_ERROR) { c->err = REDIS_ERR_OTHER; snprintf(c->errstr,sizeof(c->errstr),"%s",((redisReply*)reply)->str); c->reader->fn->freeObject(reply); __redisAsyncDisconnect(ac); return; } /* No more regular callbacks and no errors, the context *must* be subscribed or monitoring. */ assert((c->flags & REDIS_SUBSCRIBED || c->flags & REDIS_MONITORING)); if(c->flags & REDIS_SUBSCRIBED) __redisGetSubscribeCallback(ac,reply,&cb); } if (cb.fn != NULL) { __redisRunCallback(ac,&cb,reply); c->reader->fn->freeObject(reply); /* Proceed with free'ing when redisAsyncFree() was called. */ if (c->flags & REDIS_FREEING) { __redisAsyncFree(ac); return; } } else { /* No callback for this reply. This can either be a NULL callback, * or there were no callbacks to begin with. Either way, don't * abort with an error, but simply ignore it because the client * doesn't know what the server will spit out over the wire. */ c->reader->fn->freeObject(reply); } } /* Disconnect when there was an error reading the reply */ if (status != REDIS_OK) __redisAsyncDisconnect(ac); } /* Internal helper function to detect socket status the first time a read or * write event fires. When connecting was not successful, the connect callback * is called with a REDIS_ERR status and the context is free'd. */ static int __redisAsyncHandleConnect(redisAsyncContext *ac) { redisContext *c = &(ac->c); if (redisCheckSocketError(c) == REDIS_ERR) { /* Try again later when connect(2) is still in progress. */ if (errno == EINPROGRESS) return REDIS_OK; if (ac->onConnect) ac->onConnect(ac,REDIS_ERR); __redisAsyncDisconnect(ac); return REDIS_ERR; } /* Mark context as connected. */ c->flags |= REDIS_CONNECTED; if (ac->onConnect) ac->onConnect(ac,REDIS_OK); return REDIS_OK; } /* This function should be called when the socket is readable. * It processes all replies that can be read and executes their callbacks. */ void redisAsyncHandleRead(redisAsyncContext *ac) { redisContext *c = &(ac->c); if (!(c->flags & REDIS_CONNECTED)) { /* Abort connect was not successful. */ if (__redisAsyncHandleConnect(ac) != REDIS_OK) return; /* Try again later when the context is still not connected. */ if (!(c->flags & REDIS_CONNECTED)) return; } if (redisBufferRead(c) == REDIS_ERR) { __redisAsyncDisconnect(ac); } else { /* Always re-schedule reads */ _EL_ADD_READ(ac); redisProcessCallbacks(ac); } } void redisAsyncHandleWrite(redisAsyncContext *ac) { redisContext *c = &(ac->c); int done = 0; if (!(c->flags & REDIS_CONNECTED)) { /* Abort connect was not successful. */ if (__redisAsyncHandleConnect(ac) != REDIS_OK) return; /* Try again later when the context is still not connected. */ if (!(c->flags & REDIS_CONNECTED)) return; } if (redisBufferWrite(c,&done) == REDIS_ERR) { __redisAsyncDisconnect(ac); } else { /* Continue writing when not done, stop writing otherwise */ if (!done) _EL_ADD_WRITE(ac); else _EL_DEL_WRITE(ac); /* Always schedule reads after writes */ _EL_ADD_READ(ac); } } /* Sets a pointer to the first argument and its length starting at p. Returns * the number of bytes to skip to get to the following argument. */ static const char *nextArgument(const char *start, const char **str, size_t *len) { const char *p = start; if (p[0] != '$') { p = strchr(p,'$'); if (p == NULL) return NULL; } *len = (int)strtol(p+1,NULL,10); p = strchr(p,'\r'); assert(p); *str = p+2; return p+2+(*len)+2; } /* Helper function for the redisAsyncCommand* family of functions. Writes a * formatted command to the output buffer and registers the provided callback * function with the context. */ static int __redisAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, const char *cmd, size_t len) { redisContext *c = &(ac->c); redisCallback cb; int pvariant, hasnext; const char *cstr, *astr; size_t clen, alen; const char *p; sds sname; int ret; /* Don't accept new commands when the connection is about to be closed. */ if (c->flags & (REDIS_DISCONNECTING | REDIS_FREEING)) return REDIS_ERR; /* Setup callback */ cb.fn = fn; cb.privdata = privdata; /* Find out which command will be appended. */ p = nextArgument(cmd,&cstr,&clen); assert(p != NULL); hasnext = (p[0] == '$'); pvariant = (tolower(cstr[0]) == 'p') ? 1 : 0; cstr += pvariant; clen -= pvariant; if (hasnext && strncasecmp(cstr,"subscribe\r\n",11) == 0) { c->flags |= REDIS_SUBSCRIBED; /* Add every channel/pattern to the list of subscription callbacks. */ while ((p = nextArgument(p,&astr,&alen)) != NULL) { sname = sdsnewlen(astr,alen); if (pvariant) ret = dictReplace(ac->sub.patterns,sname,&cb); else ret = dictReplace(ac->sub.channels,sname,&cb); if (ret == 0) sdsfree(sname); } } else if (strncasecmp(cstr,"unsubscribe\r\n",13) == 0) { /* It is only useful to call (P)UNSUBSCRIBE when the context is * subscribed to one or more channels or patterns. */ if (!(c->flags & REDIS_SUBSCRIBED)) return REDIS_ERR; /* (P)UNSUBSCRIBE does not have its own response: every channel or * pattern that is unsubscribed will receive a message. This means we * should not append a callback function for this command. */ } else if(strncasecmp(cstr,"monitor\r\n",9) == 0) { /* Set monitor flag and push callback */ c->flags |= REDIS_MONITORING; __redisPushCallback(&ac->replies,&cb); } else { if (c->flags & REDIS_SUBSCRIBED) /* This will likely result in an error reply, but it needs to be * received and passed to the callback. */ __redisPushCallback(&ac->sub.invalid,&cb); else __redisPushCallback(&ac->replies,&cb); } __redisAppendCommand(c,cmd,len); /* Always schedule a write when the write buffer is non-empty */ _EL_ADD_WRITE(ac); return REDIS_OK; } int redisvAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, const char *format, va_list ap) { char *cmd; int len; int status; len = redisvFormatCommand(&cmd,format,ap); /* We don't want to pass -1 or -2 to future functions as a length. */ if (len < 0) return REDIS_ERR; status = __redisAsyncCommand(ac,fn,privdata,cmd,len); free(cmd); return status; } int redisAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, const char *format, ...) { va_list ap; int status; va_start(ap,format); status = redisvAsyncCommand(ac,fn,privdata,format,ap); va_end(ap); return status; } int redisAsyncCommandArgv(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, int argc, const char **argv, const size_t *argvlen) { sds cmd; int len; int status; len = redisFormatSdsCommandArgv(&cmd,argc,argv,argvlen); if (len < 0) return REDIS_ERR; status = __redisAsyncCommand(ac,fn,privdata,cmd,len); sdsfree(cmd); return status; } int redisAsyncFormattedCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, const char *cmd, size_t len) { int status = __redisAsyncCommand(ac,fn,privdata,cmd,len); return status; }
/* * Copyright (c) 2009-2011, Salvatore Sanfilippo <antirez at gmail dot com> * Copyright (c) 2010-2011, Pieter Noordhuis <pcnoordhuis at gmail dot com> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */
cpuid.h
#ifndef __XEN_PUBLIC_ARCH_X86_CPUID_H__ #define __XEN_PUBLIC_ARCH_X86_CPUID_H__ /* * For compatibility with other hypervisor interfaces, the Xen cpuid leaves * can be found at the first otherwise unused 0x100 aligned boundary starting * from 0x40000000. * * e.g If viridian extensions are enabled for an HVM domain, the Xen cpuid * leaves will start at 0x40000100 */ #define XEN_CPUID_FIRST_LEAF 0x40000000 #define XEN_CPUID_LEAF(i) (XEN_CPUID_FIRST_LEAF + (i)) /* * Leaf 1 (0x40000x00) * EAX: Largest Xen-information leaf. All leaves up to an including @EAX * are supported by the Xen host. * EBX-EDX: "XenVMMXenVMM" signature, allowing positive identification * of a Xen host. */ #define XEN_CPUID_SIGNATURE_EBX 0x566e6558 /* "XenV" */ #define XEN_CPUID_SIGNATURE_ECX 0x65584d4d /* "MMXe" */ #define XEN_CPUID_SIGNATURE_EDX 0x4d4d566e /* "nVMM" */ /* * Leaf 2 (0x40000x01) * EAX[31:16]: Xen major version. * EAX[15: 0]: Xen minor version. * EBX-EDX: Reserved (currently all zeroes). */ /* * Leaf 3 (0x40000x02) * EAX: Number of hypercall transfer pages. This register is always guaranteed * to specify one hypercall page. * EBX: Base address of Xen-specific MSRs. * ECX: Features 1. Unused bits are set to zero. * EDX: Features 2. Unused bits are set to zero. */ /* Does the host support MMU_PT_UPDATE_PRESERVE_AD for this guest? */ #define _XEN_CPUID_FEAT1_MMU_PT_UPDATE_PRESERVE_AD 0 #define XEN_CPUID_FEAT1_MMU_PT_UPDATE_PRESERVE_AD (1u<<0) /* * Leaf 4 (0x40000x03) * Sub-leaf 0: EAX: bit 0: emulated tsc * bit 1: host tsc is known to be reliable * bit 2: RDTSCP instruction available * EBX: tsc_mode: 0=default (emulate if necessary), 1=emulate, * 2=no emulation, 3=no emulation + TSC_AUX support * ECX: guest tsc frequency in kHz * EDX: guest tsc incarnation (migration count) * Sub-leaf 1: EAX: tsc offset low part * EBX: tsc offset high part * ECX: multiplicator for tsc->ns conversion * EDX: shift amount for tsc->ns conversion * Sub-leaf 2: EAX: host tsc frequency in kHz */ /* * Leaf 5 (0x40000x04) * HVM-specific features * Sub-leaf 0: EAX: Features * Sub-leaf 0: EBX: vcpu id (iff EAX has XEN_HVM_CPUID_VCPU_ID_PRESENT flag) * Sub-leaf 0: ECX: domain id (iff EAX has XEN_HVM_CPUID_DOMID_PRESENT flag) */ #define XEN_HVM_CPUID_APIC_ACCESS_VIRT (1u << 0) /* Virtualized APIC registers */ #define XEN_HVM_CPUID_X2APIC_VIRT (1u << 1) /* Virtualized x2APIC accesses */ /* Memory mapped from other domains has valid IOMMU entries */ #define XEN_HVM_CPUID_IOMMU_MAPPINGS (1u << 2) #define XEN_HVM_CPUID_VCPU_ID_PRESENT (1u << 3) /* vcpu id is present in EBX */ #define XEN_HVM_CPUID_DOMID_PRESENT (1u << 4) /* domid is present in ECX */ /* * Leaf 6 (0x40000x05) * PV-specific parameters * Sub-leaf 0: EAX: max available sub-leaf * Sub-leaf 0: EBX: bits 0-7: max machine address width */ /* Max. address width in bits taking memory hotplug into account. */ #define XEN_CPUID_MACHINE_ADDRESS_WIDTH_MASK (0xffu << 0) #define XEN_CPUID_MAX_NUM_LEAVES 5 #endif /* __XEN_PUBLIC_ARCH_X86_CPUID_H__ */
/****************************************************************************** * arch-x86/cpuid.h * * CPUID interface to Xen. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Copyright (c) 2007 Citrix Systems, Inc. * * Authors: * Keir Fraser <keir@xen.org> */
mem.mli
(** The memory back-end of Git. The memory back-end means, we never use any I/O operations to read or write a Git value. All of your repository is stored on your memory. For some specific purposes, it's useful. However, keep in your mind, when your program stops, you lost your repository obviously. Because we don't need to handle any I/O operations, this store could be more fast than the Unix/Mirage store and relevant for testing. However, we still use the [Lwt] monad to protect mutable reference value against data-race condition. Finally, this module respects the same API {!Minimal.S} and can handle PACK file - and, by this way, can be used on the Smart protocol. Obviously, some ext. modules like INDEX could not be used with this store (because thay interact with a file-system back-end). *) type 'hash t module Make (Digestif : Digestif.S) : sig type nonrec t = Digestif.t t include Minimal.S with type hash = Digestif.t and type t := t val v : ?dotgit:Fpath.t -> Fpath.t -> (t, error) result Lwt.t (** [create ?dotgit root] creates a new store represented by the path [root] (you can use [Fpath.v "."] as a sane default), where the Git objects are located in [dotgit] (default is [root / ".git"]). *) end module Store : sig include Minimal.S with type t = Digestif.SHA1.t t and type hash = Digestif.SHA1.t val v : ?dotgit:Fpath.t -> Fpath.t -> (t, error) result Lwt.t end module Sync (Store : Minimal.S) : Sync.S with type hash = Store.hash and type store = Store.t
(* * Copyright (c) 2013-2017 Thomas Gazagnaire <thomas@gazagnaire.org> * and Romain Calascibetta <romain.calascibetta@gmail.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
blob_log.mli
(** The implementation of log in which it is maintained as a single unit, or blob. Hence, two versions of the log cannot share their common predecessor. The type of values to be stored as well as a method to obtain timestamps are provided by the user. Merging does the following: the newer entries from each branch, with respect to the least common ancestor, are taken, merged and then appended in front of the LCA. *) (** Signature of [Blob_log] *) module type S = sig module Store : Irmin.KV (** Store for the log. All store related operations like branching, cloning, merging, etc are done through this module. *) type value (** Type of log entry *) val append : path:Store.path -> Store.t -> value -> unit Lwt.t (** Append an entry to the log *) val read_all : path:Store.path -> Store.t -> value list Lwt.t (** Read the entire log *) end (** [Make] returns a mergeable blob log using the backend and other parameters as specified by the user. *) module Make (Backend : Irmin.KV_maker) (T : Time.S) (V : Irmin.Type.S) : S with type value = V.t (** Blob log instantiated using the {{!Irmin_unix.FS} FS backend} provided by [Irmin_unix] and the timestamp method {!Time.Unix} *) module FS (V : Irmin.Type.S) : S with type value = V.t (** Blob log instantiated using the {{!Irmin_mem} in-memory backend} provided by [Irmin_mem] and the timestamp method {!Time.Unix} *) module Mem (V : Irmin.Type.S) : S with type value = V.t
(* * Copyright (c) 2020 KC Sivaramakrishnan <kc@kcsrk.info> * Copyright (c) 2020 Anirudh Sunder Raj <anirudh6626@gmail.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
watch.ml
open! Import include Watch_intf let src = Logs.Src.create "irmin.watch" ~doc:"Irmin watch notifications" module Log = (val Logs.src_log src : Logs.LOG) let none _ _ = Printf.eprintf "Listen hook not set!\n%!"; assert false let listen_dir_hook = ref none type hook = int -> string -> (string -> unit Lwt.t) -> (unit -> unit Lwt.t) Lwt.t let set_listen_dir_hook (h : hook) = listen_dir_hook := h let id () = let c = ref 0 in fun () -> incr c; !c let global = id () let workers_r = ref 0 let workers () = !workers_r let scheduler () = let p = ref None in let niet () = () in let c = ref niet in let push elt = match !p with | Some p -> p elt | None -> let stream, push = Lwt_stream.create () in incr workers_r; Lwt.async (fun () -> (* FIXME: we would like to skip some updates if more recent ones are at the back of the queue. *) Lwt_stream.iter_s (fun f -> f ()) stream); p := Some push; (c := fun () -> push None); push elt in let clean () = !c (); decr workers_r; c := niet; p := None in let enqueue v = push (Some v) in (clean, enqueue) module Make (K : sig type t val t : t Type.t end) (V : sig type t val t : t Type.t end) = struct type key = K.t type value = V.t type watch = int module KMap = Map.Make (struct type t = K.t let compare = Type.(unstage (compare K.t)) end) module IMap = Map.Make (struct type t = int let compare (x : int) (y : int) = compare x y end) type key_handler = value Diff.t -> unit Lwt.t type all_handler = key -> value Diff.t -> unit Lwt.t let pp_value = Type.pp V.t let equal_opt_values = Type.(unstage (equal (option V.t))) let equal_keys = Type.(unstage (equal K.t)) type t = { id : int; (* unique watch manager id. *) lock : Lwt_mutex.t; (* protect [keys] and [glob]. *) mutable next : int; (* next id, to identify watch handlers. *) mutable keys : (key * value option * key_handler) IMap.t; (* key handlers. *) mutable glob : (value KMap.t * all_handler) IMap.t; (* global handlers. *) enqueue : (unit -> unit Lwt.t) -> unit; (* enqueue notifications. *) clean : unit -> unit; (* destroy the notification thread. *) mutable listeners : int; (* number of listeners. *) mutable stop_listening : unit -> unit Lwt.t; (* clean-up listen resources. *) mutable notifications : int; (* number of notifcations. *) } let stats t = (IMap.cardinal t.keys, IMap.cardinal t.glob) let to_string t = let k, a = stats t in Printf.sprintf "[%d: %dk/%dg|%d]" t.id k a t.listeners let next t = let id = t.next in t.next <- id + 1; id let is_empty t = IMap.is_empty t.keys && IMap.is_empty t.glob let clear_unsafe t = t.keys <- IMap.empty; t.glob <- IMap.empty; t.next <- 0 let clear t = Lwt_mutex.with_lock t.lock (fun () -> clear_unsafe t; Lwt.return_unit) let v () = let lock = Lwt_mutex.create () in let clean, enqueue = scheduler () in { lock; clean; enqueue; id = global (); next = 0; keys = IMap.empty; glob = IMap.empty; listeners = 0; stop_listening = (fun () -> Lwt.return_unit); notifications = 0; } let unwatch_unsafe t id = [%log.debug "unwatch %s: id=%d" (to_string t) id]; let glob = IMap.remove id t.glob in let keys = IMap.remove id t.keys in t.glob <- glob; t.keys <- keys let unwatch t id = Lwt_mutex.with_lock t.lock (fun () -> unwatch_unsafe t id; if is_empty t then t.clean (); Lwt.return_unit) let mk old value = match (old, value) with | None, None -> assert false | Some v, None -> `Removed v | None, Some v -> `Added v | Some x, Some y -> `Updated (x, y) let protect f () = Lwt.catch f (fun e -> [%log.err "watch callback got: %a\n%s" Fmt.exn e (Printexc.get_backtrace ())]; Lwt.return_unit) let pp_option = Fmt.option ~none:(Fmt.any "<none>") let pp_key = Type.pp K.t let notify_all_unsafe t key value = let todo = ref [] in let glob = IMap.fold (fun id ((init, f) as arg) acc -> let fire old_value = todo := protect (fun () -> [%log.debug "notify-all[%d.%d:%a]: %d firing! (%a -> %a)" t.id id pp_key key t.notifications (pp_option pp_value) old_value (pp_option pp_value) value]; t.notifications <- t.notifications + 1; f key (mk old_value value)) :: !todo; let init = match value with | None -> KMap.remove key init | Some v -> KMap.add key v init in IMap.add id (init, f) acc in let old_value = try Some (KMap.find key init) with Not_found -> None in if equal_opt_values old_value value then ( [%log.debug "notify-all[%d:%d:%a]: same value, skipping." t.id id pp_key key]; IMap.add id arg acc) else fire old_value) t.glob IMap.empty in t.glob <- glob; match !todo with | [] -> () | ts -> t.enqueue (fun () -> Lwt_list.iter_p (fun x -> x ()) ts) let notify_key_unsafe t key value = let todo = ref [] in let keys = IMap.fold (fun id ((k, old_value, f) as arg) acc -> if not (equal_keys key k) then IMap.add id arg acc else if equal_opt_values value old_value then ( [%log.debug "notify-key[%d.%d:%a]: same value, skipping." t.id id pp_key key]; IMap.add id arg acc) else ( todo := protect (fun () -> [%log.debug "notify-key[%d:%d:%a] %d firing! (%a -> %a)" t.id id pp_key key t.notifications (pp_option pp_value) old_value (pp_option pp_value) value]; t.notifications <- t.notifications + 1; f (mk old_value value)) :: !todo; IMap.add id (k, value, f) acc)) t.keys IMap.empty in t.keys <- keys; match !todo with | [] -> () | ts -> t.enqueue (fun () -> Lwt_list.iter_p (fun x -> x ()) ts) let notify t key value = Lwt_mutex.with_lock t.lock (fun () -> if is_empty t then Lwt.return_unit else ( notify_all_unsafe t key value; notify_key_unsafe t key value; Lwt.return_unit)) let watch_key_unsafe t key ?init f = let id = next t in [%log.debug "watch-key %s: id=%d" (to_string t) id]; t.keys <- IMap.add id (key, init, f) t.keys; id let watch_key t key ?init f = Lwt_mutex.with_lock t.lock (fun () -> let id = watch_key_unsafe t ?init key f in Lwt.return id) let kmap_of_alist l = List.fold_left (fun map (k, v) -> KMap.add k v map) KMap.empty l let watch_unsafe t ?(init = []) f = let id = next t in [%log.debug "watch %s: id=%d" (to_string t) id]; t.glob <- IMap.add id (kmap_of_alist init, f) t.glob; id let watch t ?init f = Lwt_mutex.with_lock t.lock (fun () -> let id = watch_unsafe t ?init f in Lwt.return id) let listen_dir t dir ~key ~value = let init () = if t.listeners = 0 then ( [%log.debug "%s: start listening to %s" (to_string t) dir]; let+ f = !listen_dir_hook t.id dir (fun file -> match key file with | None -> Lwt.return_unit | Some key -> let rec read n = let* value = value key in let n' = t.notifications in if n = n' then notify t key value else ( [%log.debug "Stale event, trying reading again"]; read n') in read t.notifications) in t.stop_listening <- f) else ( [%log.debug "%s: already listening on %s" (to_string t) dir]; Lwt.return_unit) in init () >|= fun () -> t.listeners <- t.listeners + 1; function | () -> if t.listeners > 0 then t.listeners <- t.listeners - 1; if t.listeners <> 0 then Lwt.return_unit else ( [%log.debug "%s: stop listening to %s" (to_string t) dir]; t.stop_listening ()) end
(* * Copyright (c) 2013-2022 Thomas Gazagnaire <thomas@gazagnaire.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
mirage_block_partition.ml
module Make(B : Mirage_block.S) = struct type t = { b : B.t; sector_size : int; (* inclusive *) sector_start : int64; (* exclusive *) sector_end : int64; } type nonrec error = [ | Mirage_block.error | `Block of B.error | `Out_of_bounds ] type nonrec write_error = [ | Mirage_block.write_error | `Block of B.write_error | `Out_of_bounds ] let pp_error ppf = function | `Block e | (#Mirage_block.error as e) -> B.pp_error ppf e | `Out_of_bounds -> Fmt.pf ppf "Operation out of partition bounds" let pp_write_error ppf = function | `Block e | (#Mirage_block.write_error as e) -> B.pp_write_error ppf e | `Out_of_bounds -> Fmt.pf ppf "Operation out of partition bounds" let get_info b = let size_sectors = Int64.(sub b.sector_end b.sector_start) in Lwt.map (fun info -> { info with Mirage_block.size_sectors }) (B.get_info b.b) let get_offset { sector_start; _ } = sector_start let is_within b sector_start buffers = let buffers_len = List.fold_left (fun acc cs -> Int64.(add acc (of_int (Cstruct.length cs)))) 0L buffers in let num_sectors = let sector_size = Int64.of_int b.sector_size in Int64.(div (add buffers_len (pred sector_size)) sector_size) in let sector_start = Int64.add sector_start b.sector_start in let sector_end = Int64.add sector_start num_sectors in sector_start >= b.sector_start && sector_end <= b.sector_end let read b sector_start buffers = (* XXX: here and in [write] we rely on the underlying block device to check for alignment issues of [buffers]. *) if is_within b sector_start buffers then B.read b.b (Int64.add b.sector_start sector_start) buffers |> Lwt_result.map_error (fun b -> `Block b) else Lwt.return (Error `Out_of_bounds) let write b sector_start buffers = if is_within b sector_start buffers then B.write b.b (Int64.add b.sector_start sector_start) buffers |> Lwt_result.map_error (fun b -> `Block b) else Lwt.return (Error `Out_of_bounds) let partition b ~sector_size ~sector_start ~sector_end ~first_sectors = if first_sectors < 0L then raise (Invalid_argument "Partition point before device"); let sector_mid = Int64.add sector_start first_sectors in if sector_mid > sector_end then raise (Invalid_argument "Partition point beyond device"); ({ b; sector_size; sector_start; sector_end = sector_mid }, { b; sector_size; sector_start = sector_mid; sector_end }) let connect first_sectors b = let open Lwt.Syntax in let+ { Mirage_block.sector_size; size_sectors = sector_end; _ } = B.get_info b in let sector_start = 0L in partition b ~sector_size ~sector_start ~sector_end ~first_sectors let subpartition first_sectors { b; sector_size; sector_start; sector_end } = partition b ~sector_size ~sector_start ~sector_end ~first_sectors let disconnect b = (* XXX disconnect both?! *) B.disconnect b.b end
unikernel.ml
module Main (C : Mirage_clock.MCLOCK) = struct module Alcotest = Alcotest_mirage.Make (C) let start () = let open Alcotest in let id () = () in run "suite-name" [ ( "test", [ test_case_sync "A test case for alcotest with mirage" `Quick id ] ); ] end
jar_xm.h
// jar_xm.h // // ORIGINAL LICENSE - FOR LIBXM: // // Author: Romain "Artefact2" Dalmaso <artefact2@gmail.com> // Contributor: Dan Spencer <dan@atomicpotato.net> // Repackaged into jar_xm.h By: Joshua Adam Reisenauer <kd7tck@gmail.com> // This program is free software. It comes without any warranty, to the // extent permitted by applicable law. You can redistribute it and/or // modify it under the terms of the Do What The Fuck You Want To Public // License, Version 2, as published by Sam Hocevar. See // http://sam.zoy.org/wtfpl/COPYING for more details. // // HISTORY: // v0.1.0 2016-02-22 jar_xm.h - development by Joshua Reisenauer, MAR 2016 // v0.2.1 2021-03-07 m4ntr0n1c: Fix clipping noise for "bad" xm's (they will always clip), avoid clip noise and just put a ceiling) // v0.2.2 2021-03-09 m4ntr0n1c: Add complete debug solution (raylib.h must be included) // v0.2.3 2021-03-11 m4ntr0n1c: Fix tempo, bpm and volume on song stop / start / restart / loop // v0.2.4 2021-03-17 m4ntr0n1c: Sanitize code for readability // v0.2.5 2021-03-22 m4ntr0n1c: Minor adjustments // v0.2.6 2021-04-01 m4ntr0n1c: Minor fixes and optimisation // v0.3.0 2021-04-03 m4ntr0n1c: Addition of Stereo sample support, Linear Interpolation and Ramping now addressable options in code // v0.3.1 2021-04-04 m4ntr0n1c: Volume effects column adjustments, sample offset handling adjustments // // USAGE: // // In ONE source file, put: // // #define JAR_XM_IMPLEMENTATION // #include "jar_xm.h" // // Other source files should just include jar_xm.h // // SAMPLE CODE: // // jar_xm_context_t *musicptr; // float musicBuffer[48000 / 60]; // int intro_load(void) // { // jar_xm_create_context_from_file(&musicptr, 48000, "Song.XM"); // return 1; // } // int intro_unload(void) // { // jar_xm_free_context(musicptr); // return 1; // } // int intro_tick(long counter) // { // jar_xm_generate_samples(musicptr, musicBuffer, (48000 / 60) / 2); // if(IsKeyDown(KEY_ENTER)) // return 1; // return 0; // } // #ifndef INCLUDE_JAR_XM_H #define INCLUDE_JAR_XM_H #include <stdint.h> #define JAR_XM_DEBUG 0 #define JAR_XM_DEFENSIVE 1 //#define JAR_XM_RAYLIB 0 // set to 0 to disable the RayLib visualizer extension // Allow custom memory allocators #ifndef JARXM_MALLOC #define JARXM_MALLOC(sz) malloc(sz) #endif #ifndef JARXM_FREE #define JARXM_FREE(p) free(p) #endif //------------------------------------------------------------------------------- struct jar_xm_context_s; typedef struct jar_xm_context_s jar_xm_context_t; #ifdef __cplusplus extern "C" { #endif //** Create a XM context. // * @param moddata the contents of the module // * @param rate play rate in Hz, recommended value of 48000 // * @returns 0 on success // * @returns 1 if module data is not sane // * @returns 2 if memory allocation failed // * @returns 3 unable to open input file // * @returns 4 fseek() failed // * @returns 5 fread() failed // * @returns 6 unkown error // * @deprecated This function is unsafe! // * @see jar_xm_create_context_safe() int jar_xm_create_context_from_file(jar_xm_context_t** ctx, uint32_t rate, const char* filename); //** Create a XM context. // * @param moddata the contents of the module // * @param rate play rate in Hz, recommended value of 48000 // * @returns 0 on success // * @returns 1 if module data is not sane // * @returns 2 if memory allocation failed // * @deprecated This function is unsafe! // * @see jar_xm_create_context_safe() int jar_xm_create_context(jar_xm_context_t** ctx, const char* moddata, uint32_t rate); //** Create a XM context. // * @param moddata the contents of the module // * @param moddata_length the length of the contents of the module, in bytes // * @param rate play rate in Hz, recommended value of 48000 // * @returns 0 on success // * @returns 1 if module data is not sane // * @returns 2 if memory allocation failed int jar_xm_create_context_safe(jar_xm_context_t** ctx, const char* moddata, size_t moddata_length, uint32_t rate); //** Free a XM context created by jar_xm_create_context(). */ void jar_xm_free_context(jar_xm_context_t* ctx); //** Play the module and put the sound samples in an output buffer. // * @param output buffer of 2*numsamples elements (A left and right value for each sample) // * @param numsamples number of samples to generate void jar_xm_generate_samples(jar_xm_context_t* ctx, float* output, size_t numsamples); //** Play the module, resample from float to 16 bit, and put the sound samples in an output buffer. // * @param output buffer of 2*numsamples elements (A left and right value for each sample) // * @param numsamples number of samples to generate void jar_xm_generate_samples_16bit(jar_xm_context_t* ctx, short* output, size_t numsamples) { float* musicBuffer = JARXM_MALLOC((2*numsamples)*sizeof(float)); jar_xm_generate_samples(ctx, musicBuffer, numsamples); if(output){ for(int x=0;x<2*numsamples;x++) output[x] = (musicBuffer[x] * 32767.0f); // scale sample to signed small int } JARXM_FREE(musicBuffer); } //** Play the module, resample from float to 8 bit, and put the sound samples in an output buffer. // * @param output buffer of 2*numsamples elements (A left and right value for each sample) // * @param numsamples number of samples to generate void jar_xm_generate_samples_8bit(jar_xm_context_t* ctx, char* output, size_t numsamples) { float* musicBuffer = JARXM_MALLOC((2*numsamples)*sizeof(float)); jar_xm_generate_samples(ctx, musicBuffer, numsamples); if(output){ for(int x=0;x<2*numsamples;x++) output[x] = (musicBuffer[x] * 127.0f); // scale sample to signed 8 bit } JARXM_FREE(musicBuffer); } //** Set the maximum number of times a module can loop. After the specified number of loops, calls to jar_xm_generate_samples will only generate silence. You can control the current number of loops with jar_xm_get_loop_count(). // * @param loopcnt maximum number of loops. Use 0 to loop indefinitely. void jar_xm_set_max_loop_count(jar_xm_context_t* ctx, uint8_t loopcnt); //** Get the loop count of the currently playing module. This value is 0 when the module is still playing, 1 when the module has looped once, etc. uint8_t jar_xm_get_loop_count(jar_xm_context_t* ctx); //** Mute or unmute a channel. // * @note Channel numbers go from 1 to jar_xm_get_number_of_channels(...). // * @return whether the channel was muted. bool jar_xm_mute_channel(jar_xm_context_t* ctx, uint16_t, bool); //** Mute or unmute an instrument. // * @note Instrument numbers go from 1 to jar_xm_get_number_of_instruments(...). // * @return whether the instrument was muted. bool jar_xm_mute_instrument(jar_xm_context_t* ctx, uint16_t, bool); //** Get the module name as a NUL-terminated string. const char* jar_xm_get_module_name(jar_xm_context_t* ctx); //** Get the tracker name as a NUL-terminated string. const char* jar_xm_get_tracker_name(jar_xm_context_t* ctx); //** Get the number of channels. uint16_t jar_xm_get_number_of_channels(jar_xm_context_t* ctx); //** Get the module length (in patterns). uint16_t jar_xm_get_module_length(jar_xm_context_t*); //** Get the number of patterns. uint16_t jar_xm_get_number_of_patterns(jar_xm_context_t* ctx); //** Get the number of rows of a pattern. // * @note Pattern numbers go from 0 to jar_xm_get_number_of_patterns(...)-1. uint16_t jar_xm_get_number_of_rows(jar_xm_context_t* ctx, uint16_t); //** Get the number of instruments. uint16_t jar_xm_get_number_of_instruments(jar_xm_context_t* ctx); //** Get the number of samples of an instrument. // * @note Instrument numbers go from 1 to jar_xm_get_number_of_instruments(...). uint16_t jar_xm_get_number_of_samples(jar_xm_context_t* ctx, uint16_t); //** Get the current module speed. // * @param bpm will receive the current BPM // * @param tempo will receive the current tempo (ticks per line) void jar_xm_get_playing_speed(jar_xm_context_t* ctx, uint16_t* bpm, uint16_t* tempo); //** Get the current position in the module being played. // * @param pattern_index if not NULL, will receive the current pattern index in the POT (pattern order table) // * @param pattern if not NULL, will receive the current pattern number // * @param row if not NULL, will receive the current row // * @param samples if not NULL, will receive the total number of // * generated samples (divide by sample rate to get seconds of generated audio) void jar_xm_get_position(jar_xm_context_t* ctx, uint8_t* pattern_index, uint8_t* pattern, uint8_t* row, uint64_t* samples); //** Get the latest time (in number of generated samples) when a particular instrument was triggered in any channel. // * @note Instrument numbers go from 1 to jar_xm_get_number_of_instruments(...). uint64_t jar_xm_get_latest_trigger_of_instrument(jar_xm_context_t* ctx, uint16_t); //** Get the latest time (in number of generated samples) when a particular sample was triggered in any channel. // * @note Instrument numbers go from 1 to jar_xm_get_number_of_instruments(...). // * @note Sample numbers go from 0 to jar_xm_get_nubmer_of_samples(...,instr)-1. uint64_t jar_xm_get_latest_trigger_of_sample(jar_xm_context_t* ctx, uint16_t instr, uint16_t sample); //** Get the latest time (in number of generated samples) when any instrument was triggered in a given channel. // * @note Channel numbers go from 1 to jar_xm_get_number_of_channels(...). uint64_t jar_xm_get_latest_trigger_of_channel(jar_xm_context_t* ctx, uint16_t); //** Get the number of remaining samples. Divide by 2 to get the number of individual LR data samples. // * @note This is the remaining number of samples before the loop starts module again, or halts if on last pass. // * @note This function is very slow and should only be run once, if at all. uint64_t jar_xm_get_remaining_samples(jar_xm_context_t* ctx); #ifdef __cplusplus } #endif //------------------------------------------------------------------------------- #ifdef JAR_XM_IMPLEMENTATION #include <math.h> #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <string.h> #if JAR_XM_DEBUG //JAR_XM_DEBUG defined as 0 #include <stdio.h> #define DEBUG(fmt, ...) do { \ fprintf(stderr, "%s(): " fmt "\n", __func__, __VA_ARGS__); \ fflush(stderr); \ } while(0) #else #define DEBUG(...) #endif #if jar_xm_BIG_ENDIAN #error "Big endian platforms are not yet supported, sorry" /* Make sure the compiler stops, even if #error is ignored */ extern int __fail[-1]; #endif /* ----- XM constants ----- */ #define SAMPLE_NAME_LENGTH 22 #define INSTRUMENT_NAME_LENGTH 22 #define MODULE_NAME_LENGTH 20 #define TRACKER_NAME_LENGTH 20 #define PATTERN_ORDER_TABLE_LENGTH 256 #define NUM_NOTES 96 // from 1 to 96, where 1 = C-0 #define NUM_ENVELOPE_POINTS 12 // to be verified if 12 is the max #define MAX_NUM_ROWS 256 #define jar_xm_SAMPLE_RAMPING_POINTS 8 /* ----- Data types ----- */ enum jar_xm_waveform_type_e { jar_xm_SINE_WAVEFORM = 0, jar_xm_RAMP_DOWN_WAVEFORM = 1, jar_xm_SQUARE_WAVEFORM = 2, jar_xm_RANDOM_WAVEFORM = 3, jar_xm_RAMP_UP_WAVEFORM = 4, }; typedef enum jar_xm_waveform_type_e jar_xm_waveform_type_t; enum jar_xm_loop_type_e { jar_xm_NO_LOOP, jar_xm_FORWARD_LOOP, jar_xm_PING_PONG_LOOP, }; typedef enum jar_xm_loop_type_e jar_xm_loop_type_t; enum jar_xm_frequency_type_e { jar_xm_LINEAR_FREQUENCIES, jar_xm_AMIGA_FREQUENCIES, }; typedef enum jar_xm_frequency_type_e jar_xm_frequency_type_t; struct jar_xm_envelope_point_s { uint16_t frame; uint16_t value; }; typedef struct jar_xm_envelope_point_s jar_xm_envelope_point_t; struct jar_xm_envelope_s { jar_xm_envelope_point_t points[NUM_ENVELOPE_POINTS]; uint8_t num_points; uint8_t sustain_point; uint8_t loop_start_point; uint8_t loop_end_point; bool enabled; bool sustain_enabled; bool loop_enabled; }; typedef struct jar_xm_envelope_s jar_xm_envelope_t; struct jar_xm_sample_s { char name[SAMPLE_NAME_LENGTH + 1]; int8_t bits; /* Either 8 or 16 */ int8_t stereo; uint32_t length; uint32_t loop_start; uint32_t loop_length; uint32_t loop_end; float volume; int8_t finetune; jar_xm_loop_type_t loop_type; float panning; int8_t relative_note; uint64_t latest_trigger; float* data; }; typedef struct jar_xm_sample_s jar_xm_sample_t; struct jar_xm_instrument_s { char name[INSTRUMENT_NAME_LENGTH + 1]; uint16_t num_samples; uint8_t sample_of_notes[NUM_NOTES]; jar_xm_envelope_t volume_envelope; jar_xm_envelope_t panning_envelope; jar_xm_waveform_type_t vibrato_type; uint8_t vibrato_sweep; uint8_t vibrato_depth; uint8_t vibrato_rate; uint16_t volume_fadeout; uint64_t latest_trigger; bool muted; jar_xm_sample_t* samples; }; typedef struct jar_xm_instrument_s jar_xm_instrument_t; struct jar_xm_pattern_slot_s { uint8_t note; /* 1-96, 97 = Key Off note */ uint8_t instrument; /* 1-128 */ uint8_t volume_column; uint8_t effect_type; uint8_t effect_param; }; typedef struct jar_xm_pattern_slot_s jar_xm_pattern_slot_t; struct jar_xm_pattern_s { uint16_t num_rows; jar_xm_pattern_slot_t* slots; /* Array of size num_rows * num_channels */ }; typedef struct jar_xm_pattern_s jar_xm_pattern_t; struct jar_xm_module_s { char name[MODULE_NAME_LENGTH + 1]; char trackername[TRACKER_NAME_LENGTH + 1]; uint16_t length; uint16_t restart_position; uint16_t num_channels; uint16_t num_patterns; uint16_t num_instruments; uint16_t linear_interpolation; uint16_t ramping; jar_xm_frequency_type_t frequency_type; uint8_t pattern_table[PATTERN_ORDER_TABLE_LENGTH]; jar_xm_pattern_t* patterns; jar_xm_instrument_t* instruments; /* Instrument 1 has index 0, instrument 2 has index 1, etc. */ }; typedef struct jar_xm_module_s jar_xm_module_t; struct jar_xm_channel_context_s { float note; float orig_note; /* The original note before effect modifications, as read in the pattern. */ jar_xm_instrument_t* instrument; /* Could be NULL */ jar_xm_sample_t* sample; /* Could be NULL */ jar_xm_pattern_slot_t* current; float sample_position; float period; float frequency; float step; bool ping; /* For ping-pong samples: true is -->, false is <-- */ float volume; /* Ideally between 0 (muted) and 1 (loudest) */ float panning; /* Between 0 (left) and 1 (right); 0.5 is centered */ uint16_t autovibrato_ticks; bool sustained; float fadeout_volume; float volume_envelope_volume; float panning_envelope_panning; uint16_t volume_envelope_frame_count; uint16_t panning_envelope_frame_count; float autovibrato_note_offset; bool arp_in_progress; uint8_t arp_note_offset; uint8_t volume_slide_param; uint8_t fine_volume_slide_param; uint8_t global_volume_slide_param; uint8_t panning_slide_param; uint8_t portamento_up_param; uint8_t portamento_down_param; uint8_t fine_portamento_up_param; uint8_t fine_portamento_down_param; uint8_t extra_fine_portamento_up_param; uint8_t extra_fine_portamento_down_param; uint8_t tone_portamento_param; float tone_portamento_target_period; uint8_t multi_retrig_param; uint8_t note_delay_param; uint8_t pattern_loop_origin; /* Where to restart a E6y loop */ uint8_t pattern_loop_count; /* How many loop passes have been done */ bool vibrato_in_progress; jar_xm_waveform_type_t vibrato_waveform; bool vibrato_waveform_retrigger; /* True if a new note retriggers the waveform */ uint8_t vibrato_param; uint16_t vibrato_ticks; /* Position in the waveform */ float vibrato_note_offset; jar_xm_waveform_type_t tremolo_waveform; bool tremolo_waveform_retrigger; uint8_t tremolo_param; uint8_t tremolo_ticks; float tremolo_volume; uint8_t tremor_param; bool tremor_on; uint64_t latest_trigger; bool muted; //* These values are updated at the end of each tick, to save a couple of float operations on every generated sample. float target_panning; float target_volume; unsigned long frame_count; float end_of_previous_sample_left[jar_xm_SAMPLE_RAMPING_POINTS]; float end_of_previous_sample_right[jar_xm_SAMPLE_RAMPING_POINTS]; float curr_left; float curr_right; float actual_panning; float actual_volume; }; typedef struct jar_xm_channel_context_s jar_xm_channel_context_t; struct jar_xm_context_s { void* allocated_memory; jar_xm_module_t module; uint32_t rate; uint16_t default_tempo; // Number of ticks per row uint16_t default_bpm; float default_global_volume; uint16_t tempo; // Number of ticks per row uint16_t bpm; float global_volume; float volume_ramp; /* How much is a channel final volume allowed to change per sample; this is used to avoid abrubt volume changes which manifest as "clicks" in the generated sound. */ float panning_ramp; /* Same for panning. */ uint8_t current_table_index; uint8_t current_row; uint16_t current_tick; /* Can go below 255, with high tempo and a pattern delay */ float remaining_samples_in_tick; uint64_t generated_samples; bool position_jump; bool pattern_break; uint8_t jump_dest; uint8_t jump_row; uint16_t extra_ticks; /* Extra ticks to be played before going to the next row - Used for EEy effect */ uint8_t* row_loop_count; /* Array of size MAX_NUM_ROWS * module_length */ uint8_t loop_count; uint8_t max_loop_count; jar_xm_channel_context_t* channels; }; #if JAR_XM_DEFENSIVE //** Check the module data for errors/inconsistencies. // * @returns 0 if everything looks OK. Module should be safe to load. int jar_xm_check_sanity_preload(const char*, size_t); //** Check a loaded module for errors/inconsistencies. // * @returns 0 if everything looks OK. int jar_xm_check_sanity_postload(jar_xm_context_t*); #endif //** Get the number of bytes needed to store the module data in a dynamically allocated blank context. // * Things that are dynamically allocated: // * - sample data // * - sample structures in instruments // * - pattern data // * - row loop count arrays // * - pattern structures in module // * - instrument structures in module // * - channel contexts // * - context structure itself // * @returns 0 if everything looks OK. size_t jar_xm_get_memory_needed_for_context(const char*, size_t); //** Populate the context from module data. // * @returns pointer to the memory pool char* jar_xm_load_module(jar_xm_context_t*, const char*, size_t, char*); int jar_xm_create_context(jar_xm_context_t** ctxp, const char* moddata, uint32_t rate) { return jar_xm_create_context_safe(ctxp, moddata, SIZE_MAX, rate); } #define ALIGN(x, b) (((x) + ((b) - 1)) & ~((b) - 1)) #define ALIGN_PTR(x, b) (void*)(((uintptr_t)(x) + ((b) - 1)) & ~((b) - 1)) int jar_xm_create_context_safe(jar_xm_context_t** ctxp, const char* moddata, size_t moddata_length, uint32_t rate) { #if JAR_XM_DEFENSIVE int ret; #endif size_t bytes_needed; char* mempool; jar_xm_context_t* ctx; #if JAR_XM_DEFENSIVE if((ret = jar_xm_check_sanity_preload(moddata, moddata_length))) { DEBUG("jar_xm_check_sanity_preload() returned %i, module is not safe to load", ret); return 1; } #endif bytes_needed = jar_xm_get_memory_needed_for_context(moddata, moddata_length); mempool = JARXM_MALLOC(bytes_needed); if(mempool == NULL && bytes_needed > 0) { /* JARXM_MALLOC() failed, trouble ahead */ DEBUG("call to JARXM_MALLOC() failed, returned %p", (void*)mempool); return 2; } /* Initialize most of the fields to 0, 0.f, NULL or false depending on type */ memset(mempool, 0, bytes_needed); ctx = (*ctxp = (jar_xm_context_t *)mempool); ctx->allocated_memory = mempool; /* Keep original pointer for JARXM_FREE() */ mempool += sizeof(jar_xm_context_t); ctx->rate = rate; mempool = jar_xm_load_module(ctx, moddata, moddata_length, mempool); mempool = ALIGN_PTR(mempool, 16); ctx->channels = (jar_xm_channel_context_t*)mempool; mempool += ctx->module.num_channels * sizeof(jar_xm_channel_context_t); mempool = ALIGN_PTR(mempool, 16); ctx->default_global_volume = 1.f; ctx->global_volume = ctx->default_global_volume; ctx->volume_ramp = (1.f / 128.f); ctx->panning_ramp = (1.f / 128.f); for(uint8_t i = 0; i < ctx->module.num_channels; ++i) { jar_xm_channel_context_t *ch = ctx->channels + i; ch->ping = true; ch->vibrato_waveform = jar_xm_SINE_WAVEFORM; ch->vibrato_waveform_retrigger = true; ch->tremolo_waveform = jar_xm_SINE_WAVEFORM; ch->tremolo_waveform_retrigger = true; ch->volume = ch->volume_envelope_volume = ch->fadeout_volume = 1.0f; ch->panning = ch->panning_envelope_panning = .5f; ch->actual_volume = .0f; ch->actual_panning = .5f; } mempool = ALIGN_PTR(mempool, 16); ctx->row_loop_count = (uint8_t *)mempool; mempool += MAX_NUM_ROWS * sizeof(uint8_t); #if JAR_XM_DEFENSIVE if((ret = jar_xm_check_sanity_postload(ctx))) { DEBUG("jar_xm_check_sanity_postload() returned %i, module is not safe to play", ret); jar_xm_free_context(ctx); return 1; } #endif return 0; } void jar_xm_free_context(jar_xm_context_t *ctx) { if (ctx != NULL) { JARXM_FREE(ctx->allocated_memory); } } void jar_xm_set_max_loop_count(jar_xm_context_t *ctx, uint8_t loopcnt) { ctx->max_loop_count = loopcnt; } uint8_t jar_xm_get_loop_count(jar_xm_context_t *ctx) { return ctx->loop_count; } bool jar_xm_mute_channel(jar_xm_context_t *ctx, uint16_t channel, bool mute) { bool old = ctx->channels[channel - 1].muted; ctx->channels[channel - 1].muted = mute; return old; } bool jar_xm_mute_instrument(jar_xm_context_t *ctx, uint16_t instr, bool mute) { bool old = ctx->module.instruments[instr - 1].muted; ctx->module.instruments[instr - 1].muted = mute; return old; } const char* jar_xm_get_module_name(jar_xm_context_t *ctx) { return ctx->module.name; } const char* jar_xm_get_tracker_name(jar_xm_context_t *ctx) { return ctx->module.trackername; } uint16_t jar_xm_get_number_of_channels(jar_xm_context_t *ctx) { return ctx->module.num_channels; } uint16_t jar_xm_get_module_length(jar_xm_context_t *ctx) { return ctx->module.length; } uint16_t jar_xm_get_number_of_patterns(jar_xm_context_t *ctx) { return ctx->module.num_patterns; } uint16_t jar_xm_get_number_of_rows(jar_xm_context_t *ctx, uint16_t pattern) { return ctx->module.patterns[pattern].num_rows; } uint16_t jar_xm_get_number_of_instruments(jar_xm_context_t *ctx) { return ctx->module.num_instruments; } uint16_t jar_xm_get_number_of_samples(jar_xm_context_t *ctx, uint16_t instrument) { return ctx->module.instruments[instrument - 1].num_samples; } void jar_xm_get_playing_speed(jar_xm_context_t *ctx, uint16_t *bpm, uint16_t *tempo) { if(bpm) *bpm = ctx->bpm; if(tempo) *tempo = ctx->tempo; } void jar_xm_get_position(jar_xm_context_t *ctx, uint8_t *pattern_index, uint8_t *pattern, uint8_t *row, uint64_t *samples) { if(pattern_index) *pattern_index = ctx->current_table_index; if(pattern) *pattern = ctx->module.pattern_table[ctx->current_table_index]; if(row) *row = ctx->current_row; if(samples) *samples = ctx->generated_samples; } uint64_t jar_xm_get_latest_trigger_of_instrument(jar_xm_context_t *ctx, uint16_t instr) { return ctx->module.instruments[instr - 1].latest_trigger; } uint64_t jar_xm_get_latest_trigger_of_sample(jar_xm_context_t *ctx, uint16_t instr, uint16_t sample) { return ctx->module.instruments[instr - 1].samples[sample].latest_trigger; } uint64_t jar_xm_get_latest_trigger_of_channel(jar_xm_context_t *ctx, uint16_t chn) { return ctx->channels[chn - 1].latest_trigger; } //* .xm files are little-endian. (XXX: Are they really?) //* Bound reader macros. //* If we attempt to read the buffer out-of-bounds, pretend that the buffer is infinitely padded with zeroes. #define READ_U8(offset) (((offset) < moddata_length) ? (*(uint8_t*)(moddata + (offset))) : 0) #define READ_U16(offset) ((uint16_t)READ_U8(offset) | ((uint16_t)READ_U8((offset) + 1) << 8)) #define READ_U32(offset) ((uint32_t)READ_U16(offset) | ((uint32_t)READ_U16((offset) + 2) << 16)) #define READ_MEMCPY(ptr, offset, length) memcpy_pad(ptr, length, moddata, moddata_length, offset) static void memcpy_pad(void *dst, size_t dst_len, const void *src, size_t src_len, size_t offset) { uint8_t *dst_c = dst; const uint8_t *src_c = src; /* how many bytes can be copied without overrunning `src` */ size_t copy_bytes = (src_len >= offset) ? (src_len - offset) : 0; copy_bytes = copy_bytes > dst_len ? dst_len : copy_bytes; memcpy(dst_c, src_c + offset, copy_bytes); /* padded bytes */ memset(dst_c + copy_bytes, 0, dst_len - copy_bytes); } #if JAR_XM_DEFENSIVE int jar_xm_check_sanity_preload(const char* module, size_t module_length) { if(module_length < 60) { return 4; } if(memcmp("Extended Module: ", module, 17) != 0) { return 1; } if(module[37] != 0x1A) { return 2; } if(module[59] != 0x01 || module[58] != 0x04) { return 3; } /* Not XM 1.04 */ return 0; } int jar_xm_check_sanity_postload(jar_xm_context_t* ctx) { /* Check the POT */ for(uint8_t i = 0; i < ctx->module.length; ++i) { if(ctx->module.pattern_table[i] >= ctx->module.num_patterns) { if(i+1 == ctx->module.length && ctx->module.length > 1) { DEBUG("trimming invalid POT at pos %X", i); --ctx->module.length; } else { DEBUG("module has invalid POT, pos %X references nonexistent pattern %X", i, ctx->module.pattern_table[i]); return 1; } } } return 0; } #endif size_t jar_xm_get_memory_needed_for_context(const char* moddata, size_t moddata_length) { size_t memory_needed = 0; size_t offset = 60; /* 60 = Skip the first header */ uint16_t num_channels; uint16_t num_patterns; uint16_t num_instruments; /* Read the module header */ num_channels = READ_U16(offset + 8); num_patterns = READ_U16(offset + 10); memory_needed += num_patterns * sizeof(jar_xm_pattern_t); memory_needed = ALIGN(memory_needed, 16); num_instruments = READ_U16(offset + 12); memory_needed += num_instruments * sizeof(jar_xm_instrument_t); memory_needed = ALIGN(memory_needed, 16); memory_needed += MAX_NUM_ROWS * READ_U16(offset + 4) * sizeof(uint8_t); /* Module length */ offset += READ_U32(offset); /* Header size */ /* Read pattern headers */ for(uint16_t i = 0; i < num_patterns; ++i) { uint16_t num_rows; num_rows = READ_U16(offset + 5); memory_needed += num_rows * num_channels * sizeof(jar_xm_pattern_slot_t); offset += READ_U32(offset) + READ_U16(offset + 7); /* Pattern header length + packed pattern data size */ } memory_needed = ALIGN(memory_needed, 16); /* Read instrument headers */ for(uint16_t i = 0; i < num_instruments; ++i) { uint16_t num_samples; uint32_t sample_header_size = 0; uint32_t sample_size_aggregate = 0; num_samples = READ_U16(offset + 27); memory_needed += num_samples * sizeof(jar_xm_sample_t); if(num_samples > 0) { sample_header_size = READ_U32(offset + 29); } offset += READ_U32(offset); /* Instrument header size */ for(uint16_t j = 0; j < num_samples; ++j) { uint32_t sample_size; uint8_t flags; sample_size = READ_U32(offset); flags = READ_U8(offset + 14); sample_size_aggregate += sample_size; if(flags & (1 << 4)) { /* 16 bit sample */ memory_needed += sample_size * (sizeof(float) >> 1); } else { /* 8 bit sample */ memory_needed += sample_size * sizeof(float); } offset += sample_header_size; } offset += sample_size_aggregate; } memory_needed += num_channels * sizeof(jar_xm_channel_context_t); memory_needed += sizeof(jar_xm_context_t); return memory_needed; } char* jar_xm_load_module(jar_xm_context_t* ctx, const char* moddata, size_t moddata_length, char* mempool) { size_t offset = 0; jar_xm_module_t* mod = &(ctx->module); /* Read XM header */ READ_MEMCPY(mod->name, offset + 17, MODULE_NAME_LENGTH); READ_MEMCPY(mod->trackername, offset + 38, TRACKER_NAME_LENGTH); offset += 60; /* Read module header */ uint32_t header_size = READ_U32(offset); mod->length = READ_U16(offset + 4); mod->restart_position = READ_U16(offset + 6); mod->num_channels = READ_U16(offset + 8); mod->num_patterns = READ_U16(offset + 10); mod->num_instruments = READ_U16(offset + 12); mod->patterns = (jar_xm_pattern_t*)mempool; mod->linear_interpolation = 1; // Linear interpolation can be set after loading mod->ramping = 1; // ramping can be set after loading mempool += mod->num_patterns * sizeof(jar_xm_pattern_t); mempool = ALIGN_PTR(mempool, 16); mod->instruments = (jar_xm_instrument_t*)mempool; mempool += mod->num_instruments * sizeof(jar_xm_instrument_t); mempool = ALIGN_PTR(mempool, 16); uint16_t flags = READ_U32(offset + 14); mod->frequency_type = (flags & (1 << 0)) ? jar_xm_LINEAR_FREQUENCIES : jar_xm_AMIGA_FREQUENCIES; ctx->default_tempo = READ_U16(offset + 16); ctx->default_bpm = READ_U16(offset + 18); ctx->tempo =ctx->default_tempo; ctx->bpm = ctx->default_bpm; READ_MEMCPY(mod->pattern_table, offset + 20, PATTERN_ORDER_TABLE_LENGTH); offset += header_size; /* Read patterns */ for(uint16_t i = 0; i < mod->num_patterns; ++i) { uint16_t packed_patterndata_size = READ_U16(offset + 7); jar_xm_pattern_t* pat = mod->patterns + i; pat->num_rows = READ_U16(offset + 5); pat->slots = (jar_xm_pattern_slot_t*)mempool; mempool += mod->num_channels * pat->num_rows * sizeof(jar_xm_pattern_slot_t); offset += READ_U32(offset); /* Pattern header length */ if(packed_patterndata_size == 0) { /* No pattern data is present */ memset(pat->slots, 0, sizeof(jar_xm_pattern_slot_t) * pat->num_rows * mod->num_channels); } else { /* This isn't your typical for loop */ for(uint16_t j = 0, k = 0; j < packed_patterndata_size; ++k) { uint8_t note = READ_U8(offset + j); jar_xm_pattern_slot_t* slot = pat->slots + k; if(note & (1 << 7)) { /* MSB is set, this is a compressed packet */ ++j; if(note & (1 << 0)) { /* Note follows */ slot->note = READ_U8(offset + j); ++j; } else { slot->note = 0; } if(note & (1 << 1)) { /* Instrument follows */ slot->instrument = READ_U8(offset + j); ++j; } else { slot->instrument = 0; } if(note & (1 << 2)) { /* Volume column follows */ slot->volume_column = READ_U8(offset + j); ++j; } else { slot->volume_column = 0; } if(note & (1 << 3)) { /* Effect follows */ slot->effect_type = READ_U8(offset + j); ++j; } else { slot->effect_type = 0; } if(note & (1 << 4)) { /* Effect parameter follows */ slot->effect_param = READ_U8(offset + j); ++j; } else { slot->effect_param = 0; } } else { /* Uncompressed packet */ slot->note = note; slot->instrument = READ_U8(offset + j + 1); slot->volume_column = READ_U8(offset + j + 2); slot->effect_type = READ_U8(offset + j + 3); slot->effect_param = READ_U8(offset + j + 4); j += 5; } } } offset += packed_patterndata_size; } mempool = ALIGN_PTR(mempool, 16); /* Read instruments */ for(uint16_t i = 0; i < ctx->module.num_instruments; ++i) { uint32_t sample_header_size = 0; jar_xm_instrument_t* instr = mod->instruments + i; READ_MEMCPY(instr->name, offset + 4, INSTRUMENT_NAME_LENGTH); instr->num_samples = READ_U16(offset + 27); if(instr->num_samples > 0) { /* Read extra header properties */ sample_header_size = READ_U32(offset + 29); READ_MEMCPY(instr->sample_of_notes, offset + 33, NUM_NOTES); instr->volume_envelope.num_points = READ_U8(offset + 225); instr->panning_envelope.num_points = READ_U8(offset + 226); for(uint8_t j = 0; j < instr->volume_envelope.num_points; ++j) { instr->volume_envelope.points[j].frame = READ_U16(offset + 129 + 4 * j); instr->volume_envelope.points[j].value = READ_U16(offset + 129 + 4 * j + 2); } for(uint8_t j = 0; j < instr->panning_envelope.num_points; ++j) { instr->panning_envelope.points[j].frame = READ_U16(offset + 177 + 4 * j); instr->panning_envelope.points[j].value = READ_U16(offset + 177 + 4 * j + 2); } instr->volume_envelope.sustain_point = READ_U8(offset + 227); instr->volume_envelope.loop_start_point = READ_U8(offset + 228); instr->volume_envelope.loop_end_point = READ_U8(offset + 229); instr->panning_envelope.sustain_point = READ_U8(offset + 230); instr->panning_envelope.loop_start_point = READ_U8(offset + 231); instr->panning_envelope.loop_end_point = READ_U8(offset + 232); uint8_t flags = READ_U8(offset + 233); instr->volume_envelope.enabled = flags & (1 << 0); instr->volume_envelope.sustain_enabled = flags & (1 << 1); instr->volume_envelope.loop_enabled = flags & (1 << 2); flags = READ_U8(offset + 234); instr->panning_envelope.enabled = flags & (1 << 0); instr->panning_envelope.sustain_enabled = flags & (1 << 1); instr->panning_envelope.loop_enabled = flags & (1 << 2); instr->vibrato_type = READ_U8(offset + 235); if(instr->vibrato_type == 2) { instr->vibrato_type = 1; } else if(instr->vibrato_type == 1) { instr->vibrato_type = 2; } instr->vibrato_sweep = READ_U8(offset + 236); instr->vibrato_depth = READ_U8(offset + 237); instr->vibrato_rate = READ_U8(offset + 238); instr->volume_fadeout = READ_U16(offset + 239); instr->samples = (jar_xm_sample_t*)mempool; mempool += instr->num_samples * sizeof(jar_xm_sample_t); } else { instr->samples = NULL; } /* Instrument header size */ offset += READ_U32(offset); for(int j = 0; j < instr->num_samples; ++j) { /* Read sample header */ jar_xm_sample_t* sample = instr->samples + j; sample->length = READ_U32(offset); sample->loop_start = READ_U32(offset + 4); sample->loop_length = READ_U32(offset + 8); sample->loop_end = sample->loop_start + sample->loop_length; sample->volume = (float)(READ_U8(offset + 12) << 2) / 256.f; if (sample->volume > 1.0f) {sample->volume = 1.f;}; sample->finetune = (int8_t)READ_U8(offset + 13); uint8_t flags = READ_U8(offset + 14); switch (flags & 3) { case 2: case 3: sample->loop_type = jar_xm_PING_PONG_LOOP; case 1: sample->loop_type = jar_xm_FORWARD_LOOP; break; default: sample->loop_type = jar_xm_NO_LOOP; break; }; sample->bits = (flags & 0x10) ? 16 : 8; sample->stereo = (flags & 0x20) ? 1 : 0; sample->panning = (float)READ_U8(offset + 15) / 255.f; sample->relative_note = (int8_t)READ_U8(offset + 16); READ_MEMCPY(sample->name, 18, SAMPLE_NAME_LENGTH); sample->data = (float*)mempool; if(sample->bits == 16) { /* 16 bit sample */ mempool += sample->length * (sizeof(float) >> 1); sample->loop_start >>= 1; sample->loop_length >>= 1; sample->loop_end >>= 1; sample->length >>= 1; } else { /* 8 bit sample */ mempool += sample->length * sizeof(float); } // Adjust loop points to reflect half of the reported length (stereo) if (sample->stereo && sample->loop_type != jar_xm_NO_LOOP) { div_t lstart = div(READ_U32(offset + 4), 2); sample->loop_start = lstart.quot; div_t llength = div(READ_U32(offset + 8), 2); sample->loop_length = llength.quot; sample->loop_end = sample->loop_start + sample->loop_length; }; offset += sample_header_size; } // Read all samples and convert them to float values for(int j = 0; j < instr->num_samples; ++j) { /* Read sample data */ jar_xm_sample_t* sample = instr->samples + j; int length = sample->length; if (sample->stereo) { // Since it is stereo, we cut the sample in half (treated as single channel) div_t result = div(sample->length, 2); if(sample->bits == 16) { int16_t v = 0; for(int k = 0; k < length; ++k) { if (k == result.quot) { v = 0;}; v = v + (int16_t)READ_U16(offset + (k << 1)); sample->data[k] = (float) v / 32768.f ;//* sign; if(sample->data[k] < -1.0) {sample->data[k] = -1.0;} else if(sample->data[k] > 1.0) {sample->data[k] = 1.0;}; } offset += sample->length << 1; } else { int8_t v = 0; for(int k = 0; k < length; ++k) { if (k == result.quot) { v = 0;}; v = v + (int8_t)READ_U8(offset + k); sample->data[k] = (float)v / 128.f ;//* sign; if(sample->data[k] < -1.0) {sample->data[k] = -1.0;} else if(sample->data[k] > 1.0) {sample->data[k] = 1.0;}; } offset += sample->length; }; sample->length = result.quot; } else { if(sample->bits == 16) { int16_t v = 0; for(int k = 0; k < length; ++k) { v = v + (int16_t)READ_U16(offset + (k << 1)); sample->data[k] = (float) v / 32768.f ;//* sign; if(sample->data[k] < -1.0) {sample->data[k] = -1.0;} else if(sample->data[k] > 1.0) {sample->data[k] = 1.0;}; } offset += sample->length << 1; } else { int8_t v = 0; for(int k = 0; k < length; ++k) { v = v + (int8_t)READ_U8(offset + k); sample->data[k] = (float)v / 128.f ;//* sign; if(sample->data[k] < -1.0) {sample->data[k] = -1.0;} else if(sample->data[k] > 1.0) {sample->data[k] = 1.0;}; } offset += sample->length; } } }; }; return mempool; }; //------------------------------------------------------------------------------- //THE FOLLOWING IS FOR PLAYING static float jar_xm_waveform(jar_xm_waveform_type_t, uint8_t); static void jar_xm_autovibrato(jar_xm_context_t*, jar_xm_channel_context_t*); static void jar_xm_vibrato(jar_xm_context_t*, jar_xm_channel_context_t*, uint8_t, uint16_t); static void jar_xm_tremolo(jar_xm_context_t*, jar_xm_channel_context_t*, uint8_t, uint16_t); static void jar_xm_arpeggio(jar_xm_context_t*, jar_xm_channel_context_t*, uint8_t, uint16_t); static void jar_xm_tone_portamento(jar_xm_context_t*, jar_xm_channel_context_t*); static void jar_xm_pitch_slide(jar_xm_context_t*, jar_xm_channel_context_t*, float); static void jar_xm_panning_slide(jar_xm_channel_context_t*, uint8_t); static void jar_xm_volume_slide(jar_xm_channel_context_t*, uint8_t); static float jar_xm_envelope_lerp(jar_xm_envelope_point_t*, jar_xm_envelope_point_t*, uint16_t); static void jar_xm_envelope_tick(jar_xm_channel_context_t*, jar_xm_envelope_t*, uint16_t*, float*); static void jar_xm_envelopes(jar_xm_channel_context_t*); static float jar_xm_linear_period(float); static float jar_xm_linear_frequency(float); static float jar_xm_amiga_period(float); static float jar_xm_amiga_frequency(float); static float jar_xm_period(jar_xm_context_t*, float); static float jar_xm_frequency(jar_xm_context_t*, float, float); static void jar_xm_update_frequency(jar_xm_context_t*, jar_xm_channel_context_t*); static void jar_xm_handle_note_and_instrument(jar_xm_context_t*, jar_xm_channel_context_t*, jar_xm_pattern_slot_t*); static void jar_xm_trigger_note(jar_xm_context_t*, jar_xm_channel_context_t*, unsigned int flags); static void jar_xm_cut_note(jar_xm_channel_context_t*); static void jar_xm_key_off(jar_xm_channel_context_t*); static void jar_xm_post_pattern_change(jar_xm_context_t*); static void jar_xm_row(jar_xm_context_t*); static void jar_xm_tick(jar_xm_context_t*); static void jar_xm_next_of_sample(jar_xm_context_t*, jar_xm_channel_context_t*, int); static void jar_xm_mixdown(jar_xm_context_t*, float*, float*); #define jar_xm_TRIGGER_KEEP_VOLUME (1 << 0) #define jar_xm_TRIGGER_KEEP_PERIOD (1 << 1) #define jar_xm_TRIGGER_KEEP_SAMPLE_POSITION (1 << 2) // C-2, C#2, D-2, D#2, E-2, F-2, F#2, G-2, G#2, A-2, A#2, B-2, C-3 static const uint16_t amiga_frequencies[] = { 1712, 1616, 1525, 1440, 1357, 1281, 1209, 1141, 1077, 1017, 961, 907, 856 }; // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f static const float multi_retrig_add[] = { 0.f, -1.f, -2.f, -4.f, -8.f, -16.f, 0.f, 0.f, 0.f, 1.f, 2.f, 4.f, 8.f, 16.f, 0.f, 0.f }; // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f static const float multi_retrig_multiply[] = { 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, .6666667f, .5f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.5f, 2.f }; #define jar_xm_CLAMP_UP1F(vol, limit) do { \ if((vol) > (limit)) (vol) = (limit); \ } while(0) #define jar_xm_CLAMP_UP(vol) jar_xm_CLAMP_UP1F((vol), 1.f) #define jar_xm_CLAMP_DOWN1F(vol, limit) do { \ if((vol) < (limit)) (vol) = (limit); \ } while(0) #define jar_xm_CLAMP_DOWN(vol) jar_xm_CLAMP_DOWN1F((vol), .0f) #define jar_xm_CLAMP2F(vol, up, down) do { \ if((vol) > (up)) (vol) = (up); \ else if((vol) < (down)) (vol) = (down); \ } while(0) #define jar_xm_CLAMP(vol) jar_xm_CLAMP2F((vol), 1.f, .0f) #define jar_xm_SLIDE_TOWARDS(val, goal, incr) do { \ if((val) > (goal)) { \ (val) -= (incr); \ jar_xm_CLAMP_DOWN1F((val), (goal)); \ } else if((val) < (goal)) { \ (val) += (incr); \ jar_xm_CLAMP_UP1F((val), (goal)); \ } \ } while(0) #define jar_xm_LERP(u, v, t) ((u) + (t) * ((v) - (u))) #define jar_xm_INVERSE_LERP(u, v, lerp) (((lerp) - (u)) / ((v) - (u))) #define HAS_TONE_PORTAMENTO(s) ((s)->effect_type == 3 \ || (s)->effect_type == 5 \ || ((s)->volume_column >> 4) == 0xF) #define HAS_ARPEGGIO(s) ((s)->effect_type == 0 \ && (s)->effect_param != 0) #define HAS_VIBRATO(s) ((s)->effect_type == 4 \ || (s)->effect_param == 6 \ || ((s)->volume_column >> 4) == 0xB) #define NOTE_IS_VALID(n) ((n) > 0 && (n) < 97) #define NOTE_OFF 97 static float jar_xm_waveform(jar_xm_waveform_type_t waveform, uint8_t step) { static unsigned int next_rand = 24492; step %= 0x40; switch(waveform) { case jar_xm_SINE_WAVEFORM: /* No SIN() table used, direct calculation. */ return -sinf(2.f * 3.141592f * (float)step / (float)0x40); case jar_xm_RAMP_DOWN_WAVEFORM: /* Ramp down: 1.0f when step = 0; -1.0f when step = 0x40 */ return (float)(0x20 - step) / 0x20; case jar_xm_SQUARE_WAVEFORM: /* Square with a 50% duty */ return (step >= 0x20) ? 1.f : -1.f; case jar_xm_RANDOM_WAVEFORM: /* Use the POSIX.1-2001 example, just to be deterministic across different machines */ next_rand = next_rand * 1103515245 + 12345; return (float)((next_rand >> 16) & 0x7FFF) / (float)0x4000 - 1.f; case jar_xm_RAMP_UP_WAVEFORM: /* Ramp up: -1.f when step = 0; 1.f when step = 0x40 */ return (float)(step - 0x20) / 0x20; default: break; } return .0f; } static void jar_xm_autovibrato(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch) { if(ch->instrument == NULL || ch->instrument->vibrato_depth == 0) return; jar_xm_instrument_t* instr = ch->instrument; float sweep = 1.f; if(ch->autovibrato_ticks < instr->vibrato_sweep) { sweep = jar_xm_LERP(0.f, 1.f, (float)ch->autovibrato_ticks / (float)instr->vibrato_sweep); } unsigned int step = ((ch->autovibrato_ticks++) * instr->vibrato_rate) >> 2; ch->autovibrato_note_offset = .25f * jar_xm_waveform(instr->vibrato_type, step) * (float)instr->vibrato_depth / (float)0xF * sweep; jar_xm_update_frequency(ctx, ch); } static void jar_xm_vibrato(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch, uint8_t param, uint16_t pos) { unsigned int step = pos * (param >> 4); ch->vibrato_note_offset = 2.f * jar_xm_waveform(ch->vibrato_waveform, step) * (float)(param & 0x0F) / (float)0xF; jar_xm_update_frequency(ctx, ch); } static void jar_xm_tremolo(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch, uint8_t param, uint16_t pos) { unsigned int step = pos * (param >> 4); ch->tremolo_volume = -1.f * jar_xm_waveform(ch->tremolo_waveform, step) * (float)(param & 0x0F) / (float)0xF; } static void jar_xm_arpeggio(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch, uint8_t param, uint16_t tick) { switch(tick % 3) { case 0: ch->arp_in_progress = false; ch->arp_note_offset = 0; break; case 2: ch->arp_in_progress = true; ch->arp_note_offset = param >> 4; break; case 1: ch->arp_in_progress = true; ch->arp_note_offset = param & 0x0F; break; } jar_xm_update_frequency(ctx, ch); } static void jar_xm_tone_portamento(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch) { /* 3xx called without a note, wait until we get an actual target note. */ if(ch->tone_portamento_target_period == 0.f) return; /* no value, exit */ if(ch->period != ch->tone_portamento_target_period) { jar_xm_SLIDE_TOWARDS(ch->period, ch->tone_portamento_target_period, (ctx->module.frequency_type == jar_xm_LINEAR_FREQUENCIES ? 4.f : 1.f) * ch->tone_portamento_param); jar_xm_update_frequency(ctx, ch); } } static void jar_xm_pitch_slide(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch, float period_offset) { /* Don't ask about the 4.f coefficient. I found mention of it nowhere. Found by ear™. */ if(ctx->module.frequency_type == jar_xm_LINEAR_FREQUENCIES) {period_offset *= 4.f; } ch->period += period_offset; jar_xm_CLAMP_DOWN(ch->period); /* XXX: upper bound of period ? */ jar_xm_update_frequency(ctx, ch); } static void jar_xm_panning_slide(jar_xm_channel_context_t* ch, uint8_t rawval) { if (rawval & 0xF0) {ch->panning += (float)((rawval & 0xF0 )>> 4) / (float)0xFF;}; if (rawval & 0x0F) {ch->panning -= (float)(rawval & 0x0F) / (float)0xFF;}; }; static void jar_xm_volume_slide(jar_xm_channel_context_t* ch, uint8_t rawval) { if (rawval & 0xF0) {ch->volume += (float)((rawval & 0xF0) >> 4) / (float)0x40;}; if (rawval & 0x0F) {ch->volume -= (float)(rawval & 0x0F) / (float)0x40;}; }; static float jar_xm_envelope_lerp(jar_xm_envelope_point_t* a, jar_xm_envelope_point_t* b, uint16_t pos) { /* Linear interpolation between two envelope points */ if(pos <= a->frame) return a->value; else if(pos >= b->frame) return b->value; else { float p = (float)(pos - a->frame) / (float)(b->frame - a->frame); return a->value * (1 - p) + b->value * p; } } static void jar_xm_post_pattern_change(jar_xm_context_t* ctx) { /* Loop if necessary */ if(ctx->current_table_index >= ctx->module.length) { ctx->current_table_index = ctx->module.restart_position; ctx->tempo =ctx->default_tempo; // reset to file default value ctx->bpm = ctx->default_bpm; // reset to file default value ctx->global_volume = ctx->default_global_volume; // reset to file default value } } static float jar_xm_linear_period(float note) { return 7680.f - note * 64.f; } static float jar_xm_linear_frequency(float period) { return 8363.f * powf(2.f, (4608.f - period) / 768.f); } static float jar_xm_amiga_period(float note) { unsigned int intnote = note; uint8_t a = intnote % 12; int8_t octave = note / 12.f - 2; uint16_t p1 = amiga_frequencies[a], p2 = amiga_frequencies[a + 1]; if(octave > 0) { p1 >>= octave; p2 >>= octave; } else if(octave < 0) { p1 <<= -octave; p2 <<= -octave; } return jar_xm_LERP(p1, p2, note - intnote); } static float jar_xm_amiga_frequency(float period) { if(period == .0f) return .0f; return 7093789.2f / (period * 2.f); /* This is the PAL value. (we could use the NTSC value also) */ } static float jar_xm_period(jar_xm_context_t* ctx, float note) { switch(ctx->module.frequency_type) { case jar_xm_LINEAR_FREQUENCIES: return jar_xm_linear_period(note); case jar_xm_AMIGA_FREQUENCIES: return jar_xm_amiga_period(note); } return .0f; } static float jar_xm_frequency(jar_xm_context_t* ctx, float period, float note_offset) { switch(ctx->module.frequency_type) { case jar_xm_LINEAR_FREQUENCIES: return jar_xm_linear_frequency(period - 64.f * note_offset); case jar_xm_AMIGA_FREQUENCIES: if(note_offset == 0) { return jar_xm_amiga_frequency(period); }; int8_t octave; float note; uint16_t p1, p2; uint8_t a = octave = 0; /* Find the octave of the current period */ if(period > amiga_frequencies[0]) { --octave; while(period > (amiga_frequencies[0] << -octave)) --octave; } else if(period < amiga_frequencies[12]) { ++octave; while(period < (amiga_frequencies[12] >> octave)) ++octave; } /* Find the smallest note closest to the current period */ for(uint8_t i = 0; i < 12; ++i) { p1 = amiga_frequencies[i], p2 = amiga_frequencies[i + 1]; if(octave > 0) { p1 >>= octave; p2 >>= octave; } else if(octave < 0) { p1 <<= (-octave); p2 <<= (-octave); } if(p2 <= period && period <= p1) { a = i; break; } } if(JAR_XM_DEBUG && (p1 < period || p2 > period)) { DEBUG("%i <= %f <= %i should hold but doesn't, this is a bug", p2, period, p1); } note = 12.f * (octave + 2) + a + jar_xm_INVERSE_LERP(p1, p2, period); return jar_xm_amiga_frequency(jar_xm_amiga_period(note + note_offset)); } return .0f; } static void jar_xm_update_frequency(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch) { ch->frequency = jar_xm_frequency( ctx, ch->period, (ch->arp_note_offset > 0 ? ch->arp_note_offset : ( ch->vibrato_note_offset + ch->autovibrato_note_offset )) ); ch->step = ch->frequency / ctx->rate; } static void jar_xm_handle_note_and_instrument(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch, jar_xm_pattern_slot_t* s) { jar_xm_module_t* mod = &(ctx->module); if(s->instrument > 0) { if(HAS_TONE_PORTAMENTO(ch->current) && ch->instrument != NULL && ch->sample != NULL) { /* Tone portamento in effect */ jar_xm_trigger_note(ctx, ch, jar_xm_TRIGGER_KEEP_PERIOD | jar_xm_TRIGGER_KEEP_SAMPLE_POSITION); } else if(s->instrument > ctx->module.num_instruments) { /* Invalid instrument, Cut current note */ jar_xm_cut_note(ch); ch->instrument = NULL; ch->sample = NULL; } else { ch->instrument = ctx->module.instruments + (s->instrument - 1); if(s->note == 0 && ch->sample != NULL) { /* Ghost instrument, trigger note */ /* Sample position is kept, but envelopes are reset */ jar_xm_trigger_note(ctx, ch, jar_xm_TRIGGER_KEEP_SAMPLE_POSITION); } } } if(NOTE_IS_VALID(s->note)) { // note value is s->note -1 jar_xm_instrument_t* instr = ch->instrument; if(HAS_TONE_PORTAMENTO(ch->current) && instr != NULL && ch->sample != NULL) { /* Tone portamento in effect */ ch->note = s->note + ch->sample->relative_note + ch->sample->finetune / 128.f - 1.f; ch->tone_portamento_target_period = jar_xm_period(ctx, ch->note); } else if(instr == NULL || ch->instrument->num_samples == 0) { /* Issue on instrument */ jar_xm_cut_note(ch); } else { if(instr->sample_of_notes[s->note - 1] < instr->num_samples) { if (mod->ramping) { for(int i = 0; i < jar_xm_SAMPLE_RAMPING_POINTS; ++i) { jar_xm_next_of_sample(ctx, ch, i); } ch->frame_count = 0; }; ch->sample = instr->samples + instr->sample_of_notes[s->note - 1]; ch->orig_note = ch->note = s->note + ch->sample->relative_note + ch->sample->finetune / 128.f - 1.f; if(s->instrument > 0) { jar_xm_trigger_note(ctx, ch, 0); } else { /* Ghost note: keep old volume */ jar_xm_trigger_note(ctx, ch, jar_xm_TRIGGER_KEEP_VOLUME); } } else { jar_xm_cut_note(ch); } } } else if(s->note == NOTE_OFF) { jar_xm_key_off(ch); } // Interpret Effect column switch(s->effect_type) { case 1: /* 1xx: Portamento up */ if(s->effect_param > 0) { ch->portamento_up_param = s->effect_param; } break; case 2: /* 2xx: Portamento down */ if(s->effect_param > 0) { ch->portamento_down_param = s->effect_param; } break; case 3: /* 3xx: Tone portamento */ if(s->effect_param > 0) { ch->tone_portamento_param = s->effect_param; } break; case 4: /* 4xy: Vibrato */ if(s->effect_param & 0x0F) { ch->vibrato_param = (ch->vibrato_param & 0xF0) | (s->effect_param & 0x0F); } /* Set vibrato depth */ if(s->effect_param >> 4) { ch->vibrato_param = (s->effect_param & 0xF0) | (ch->vibrato_param & 0x0F); } /* Set vibrato speed */ break; case 5: /* 5xy: Tone portamento + Volume slide */ if(s->effect_param > 0) { ch->volume_slide_param = s->effect_param; } break; case 6: /* 6xy: Vibrato + Volume slide */ if(s->effect_param > 0) { ch->volume_slide_param = s->effect_param; } break; case 7: /* 7xy: Tremolo */ if(s->effect_param & 0x0F) { ch->tremolo_param = (ch->tremolo_param & 0xF0) | (s->effect_param & 0x0F); } /* Set tremolo depth */ if(s->effect_param >> 4) { ch->tremolo_param = (s->effect_param & 0xF0) | (ch->tremolo_param & 0x0F); } /* Set tremolo speed */ break; case 8: /* 8xx: Set panning */ ch->panning = (float)s->effect_param / 255.f; break; case 9: /* 9xx: Sample offset */ if(ch->sample != 0) { //&& NOTE_IS_VALID(s->note)) { uint32_t final_offset = s->effect_param << (ch->sample->bits == 16 ? 7 : 8); switch (ch->sample->loop_type) { case jar_xm_NO_LOOP: if(final_offset >= ch->sample->length) { /* Pretend the sample dosen't loop and is done playing */ ch->sample_position = -1; } else { ch->sample_position = final_offset; } break; case jar_xm_FORWARD_LOOP: if (final_offset >= ch->sample->loop_end) { ch->sample_position -= ch->sample->loop_length; } else if(final_offset >= ch->sample->length) { ch->sample_position = ch->sample->loop_start; } else { ch->sample_position = final_offset; } break; case jar_xm_PING_PONG_LOOP: if(final_offset >= ch->sample->loop_end) { ch->ping = false; ch->sample_position = (ch->sample->loop_end << 1) - ch->sample_position; } else if(final_offset >= ch->sample->length) { ch->ping = false; ch->sample_position -= ch->sample->length - 1; } else { ch->sample_position = final_offset; }; break; } } break; case 0xA: /* Axy: Volume slide */ if(s->effect_param > 0) { ch->volume_slide_param = s->effect_param; } break; case 0xB: /* Bxx: Position jump */ if(s->effect_param < ctx->module.length) { ctx->position_jump = true; ctx->jump_dest = s->effect_param; } break; case 0xC: /* Cxx: Set volume */ ch->volume = (float)((s->effect_param > 0x40) ? 0x40 : s->effect_param) / (float)0x40; break; case 0xD: /* Dxx: Pattern break */ /* Jump after playing this line */ ctx->pattern_break = true; ctx->jump_row = (s->effect_param >> 4) * 10 + (s->effect_param & 0x0F); break; case 0xE: /* EXy: Extended command */ switch(s->effect_param >> 4) { case 1: /* E1y: Fine portamento up */ if(s->effect_param & 0x0F) { ch->fine_portamento_up_param = s->effect_param & 0x0F; } jar_xm_pitch_slide(ctx, ch, -ch->fine_portamento_up_param); break; case 2: /* E2y: Fine portamento down */ if(s->effect_param & 0x0F) { ch->fine_portamento_down_param = s->effect_param & 0x0F; } jar_xm_pitch_slide(ctx, ch, ch->fine_portamento_down_param); break; case 4: /* E4y: Set vibrato control */ ch->vibrato_waveform = s->effect_param & 3; ch->vibrato_waveform_retrigger = !((s->effect_param >> 2) & 1); break; case 5: /* E5y: Set finetune */ if(NOTE_IS_VALID(ch->current->note) && ch->sample != NULL) { ch->note = ch->current->note + ch->sample->relative_note + (float)(((s->effect_param & 0x0F) - 8) << 4) / 128.f - 1.f; ch->period = jar_xm_period(ctx, ch->note); jar_xm_update_frequency(ctx, ch); } break; case 6: /* E6y: Pattern loop */ if(s->effect_param & 0x0F) { if((s->effect_param & 0x0F) == ch->pattern_loop_count) { /* Loop is over */ ch->pattern_loop_count = 0; ctx->position_jump = false; } else { /* Jump to the beginning of the loop */ ch->pattern_loop_count++; ctx->position_jump = true; ctx->jump_row = ch->pattern_loop_origin; ctx->jump_dest = ctx->current_table_index; } } else { ch->pattern_loop_origin = ctx->current_row; /* Set loop start point */ ctx->jump_row = ch->pattern_loop_origin; /* Replicate FT2 E60 bug */ } break; case 7: /* E7y: Set tremolo control */ ch->tremolo_waveform = s->effect_param & 3; ch->tremolo_waveform_retrigger = !((s->effect_param >> 2) & 1); break; case 0xA: /* EAy: Fine volume slide up */ if(s->effect_param & 0x0F) { ch->fine_volume_slide_param = s->effect_param & 0x0F; } jar_xm_volume_slide(ch, ch->fine_volume_slide_param << 4); break; case 0xB: /* EBy: Fine volume slide down */ if(s->effect_param & 0x0F) { ch->fine_volume_slide_param = s->effect_param & 0x0F; } jar_xm_volume_slide(ch, ch->fine_volume_slide_param); break; case 0xD: /* EDy: Note delay */ /* XXX: figure this out better. EDx triggers the note even when there no note and no instrument. But ED0 acts like like a ghost note, EDx (x ≠ 0) does not. */ if(s->note == 0 && s->instrument == 0) { unsigned int flags = jar_xm_TRIGGER_KEEP_VOLUME; if(ch->current->effect_param & 0x0F) { ch->note = ch->orig_note; jar_xm_trigger_note(ctx, ch, flags); } else { jar_xm_trigger_note(ctx, ch, flags | jar_xm_TRIGGER_KEEP_PERIOD | jar_xm_TRIGGER_KEEP_SAMPLE_POSITION ); } } break; case 0xE: /* EEy: Pattern delay */ ctx->extra_ticks = (ch->current->effect_param & 0x0F) * ctx->tempo; break; default: break; } break; case 0xF: /* Fxx: Set tempo/BPM */ if(s->effect_param > 0) { if(s->effect_param <= 0x1F) { // First 32 possible values adjust the ticks (goes into tempo) ctx->tempo = s->effect_param; } else { //32 and greater values adjust the BPM ctx->bpm = s->effect_param; } } break; case 16: /* Gxx: Set global volume */ ctx->global_volume = (float)((s->effect_param > 0x40) ? 0x40 : s->effect_param) / (float)0x40; break; case 17: /* Hxy: Global volume slide */ if(s->effect_param > 0) { ch->global_volume_slide_param = s->effect_param; } break; case 21: /* Lxx: Set envelope position */ ch->volume_envelope_frame_count = s->effect_param; ch->panning_envelope_frame_count = s->effect_param; break; case 25: /* Pxy: Panning slide */ if(s->effect_param > 0) { ch->panning_slide_param = s->effect_param; } break; case 27: /* Rxy: Multi retrig note */ if(s->effect_param > 0) { if((s->effect_param >> 4) == 0) { /* Keep previous x value */ ch->multi_retrig_param = (ch->multi_retrig_param & 0xF0) | (s->effect_param & 0x0F); } else { ch->multi_retrig_param = s->effect_param; } } break; case 29: /* Txy: Tremor */ if(s->effect_param > 0) { ch->tremor_param = s->effect_param; } /* Tremor x and y params are not separately kept in memory, unlike Rxy */ break; case 33: /* Xxy: Extra stuff */ switch(s->effect_param >> 4) { case 1: /* X1y: Extra fine portamento up */ if(s->effect_param & 0x0F) { ch->extra_fine_portamento_up_param = s->effect_param & 0x0F; } jar_xm_pitch_slide(ctx, ch, -1.0f * ch->extra_fine_portamento_up_param); break; case 2: /* X2y: Extra fine portamento down */ if(s->effect_param & 0x0F) { ch->extra_fine_portamento_down_param = s->effect_param & 0x0F; } jar_xm_pitch_slide(ctx, ch, ch->extra_fine_portamento_down_param); break; default: break; } break; default: break; } } static void jar_xm_trigger_note(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch, unsigned int flags) { if (!(flags & jar_xm_TRIGGER_KEEP_SAMPLE_POSITION)) { ch->sample_position = 0.f; ch->ping = true; }; if (!(flags & jar_xm_TRIGGER_KEEP_VOLUME)) { if(ch->sample != NULL) { ch->volume = ch->sample->volume; }; }; ch->panning = ch->sample->panning; ch->sustained = true; ch->fadeout_volume = ch->volume_envelope_volume = 1.0f; ch->panning_envelope_panning = .5f; ch->volume_envelope_frame_count = ch->panning_envelope_frame_count = 0; ch->vibrato_note_offset = 0.f; ch->tremolo_volume = 0.f; ch->tremor_on = false; ch->autovibrato_ticks = 0; if(ch->vibrato_waveform_retrigger) { ch->vibrato_ticks = 0; } /* XXX: should the waveform itself also be reset to sine? */ if(ch->tremolo_waveform_retrigger) { ch->tremolo_ticks = 0; } if(!(flags & jar_xm_TRIGGER_KEEP_PERIOD)) { ch->period = jar_xm_period(ctx, ch->note); jar_xm_update_frequency(ctx, ch); } ch->latest_trigger = ctx->generated_samples; if(ch->instrument != NULL) { ch->instrument->latest_trigger = ctx->generated_samples; } if(ch->sample != NULL) { ch->sample->latest_trigger = ctx->generated_samples; } } static void jar_xm_cut_note(jar_xm_channel_context_t* ch) { ch->volume = .0f; /* NB: this is not the same as Key Off */ // ch->curr_left = .0f; // ch->curr_right = .0f; } static void jar_xm_key_off(jar_xm_channel_context_t* ch) { ch->sustained = false; /* Key Off */ if(ch->instrument == NULL || !ch->instrument->volume_envelope.enabled) { jar_xm_cut_note(ch); } /* If no volume envelope is used, also cut the note */ } static void jar_xm_row(jar_xm_context_t* ctx) { if(ctx->position_jump) { ctx->current_table_index = ctx->jump_dest; ctx->current_row = ctx->jump_row; ctx->position_jump = false; ctx->pattern_break = false; ctx->jump_row = 0; jar_xm_post_pattern_change(ctx); } else if(ctx->pattern_break) { ctx->current_table_index++; ctx->current_row = ctx->jump_row; ctx->pattern_break = false; ctx->jump_row = 0; jar_xm_post_pattern_change(ctx); } jar_xm_pattern_t* cur = ctx->module.patterns + ctx->module.pattern_table[ctx->current_table_index]; bool in_a_loop = false; /* Read notes information for all channels into temporary pattern slot */ for(uint8_t i = 0; i < ctx->module.num_channels; ++i) { jar_xm_pattern_slot_t* s = cur->slots + ctx->current_row * ctx->module.num_channels + i; jar_xm_channel_context_t* ch = ctx->channels + i; ch->current = s; // If there is no note delay effect (0xED) then... if(s->effect_type != 0xE || s->effect_param >> 4 != 0xD) { //********** Process the channel slot information ********** jar_xm_handle_note_and_instrument(ctx, ch, s); } else { // read the note delay information ch->note_delay_param = s->effect_param & 0x0F; } if(!in_a_loop && ch->pattern_loop_count > 0) { // clarify if in a loop or not in_a_loop = true; } } if(!in_a_loop) { /* No E6y loop is in effect (or we are in the first pass) */ ctx->loop_count = (ctx->row_loop_count[MAX_NUM_ROWS * ctx->current_table_index + ctx->current_row]++); } /// Move to next row ctx->current_row++; /* uint8 warning: can increment from 255 to 0, in which case it is still necessary to go the next pattern. */ if (!ctx->position_jump && !ctx->pattern_break && (ctx->current_row >= cur->num_rows || ctx->current_row == 0)) { ctx->current_table_index++; ctx->current_row = ctx->jump_row; /* This will be 0 most of the time, except when E60 is used */ ctx->jump_row = 0; jar_xm_post_pattern_change(ctx); } } static void jar_xm_envelope_tick(jar_xm_channel_context_t *ch, jar_xm_envelope_t *env, uint16_t *counter, float *outval) { if(env->num_points < 2) { if(env->num_points == 1) { *outval = (float)env->points[0].value / (float)0x40; if(*outval > 1) { *outval = 1; }; } else {; return; }; } else { if(env->loop_enabled) { uint16_t loop_start = env->points[env->loop_start_point].frame; uint16_t loop_end = env->points[env->loop_end_point].frame; uint16_t loop_length = loop_end - loop_start; if(*counter >= loop_end) { *counter -= loop_length; }; }; for(uint8_t j = 0; j < (env->num_points - 1); ++j) { if(env->points[j].frame <= *counter && env->points[j+1].frame >= *counter) { *outval = jar_xm_envelope_lerp(env->points + j, env->points + j + 1, *counter) / (float)0x40; break; }; }; /* Make sure it is safe to increment frame count */ if(!ch->sustained || !env->sustain_enabled || *counter != env->points[env->sustain_point].frame) { (*counter)++; }; }; }; static void jar_xm_envelopes(jar_xm_channel_context_t *ch) { if(ch->instrument != NULL) { if(ch->instrument->volume_envelope.enabled) { if(!ch->sustained) { ch->fadeout_volume -= (float)ch->instrument->volume_fadeout / 65536.f; jar_xm_CLAMP_DOWN(ch->fadeout_volume); }; jar_xm_envelope_tick(ch, &(ch->instrument->volume_envelope), &(ch->volume_envelope_frame_count), &(ch->volume_envelope_volume)); }; if(ch->instrument->panning_envelope.enabled) { jar_xm_envelope_tick(ch, &(ch->instrument->panning_envelope), &(ch->panning_envelope_frame_count), &(ch->panning_envelope_panning)); }; }; }; static void jar_xm_tick(jar_xm_context_t* ctx) { if(ctx->current_tick == 0) { jar_xm_row(ctx); // We have processed all ticks and we run the row } jar_xm_module_t* mod = &(ctx->module); for(uint8_t i = 0; i < ctx->module.num_channels; ++i) { jar_xm_channel_context_t* ch = ctx->channels + i; jar_xm_envelopes(ch); jar_xm_autovibrato(ctx, ch); if(ch->arp_in_progress && !HAS_ARPEGGIO(ch->current)) { ch->arp_in_progress = false; ch->arp_note_offset = 0; jar_xm_update_frequency(ctx, ch); } if(ch->vibrato_in_progress && !HAS_VIBRATO(ch->current)) { ch->vibrato_in_progress = false; ch->vibrato_note_offset = 0.f; jar_xm_update_frequency(ctx, ch); } // Effects in volumne column mostly handled on a per tick basis switch(ch->current->volume_column & 0xF0) { case 0x50: // Checks for volume = 64 if(ch->current->volume_column != 0x50) break; case 0x10: // Set volume 0-15 case 0x20: // Set volume 16-32 case 0x30: // Set volume 32-48 case 0x40: // Set volume 48-64 ch->volume = (float)(ch->current->volume_column - 16) / 64.0f; break; case 0x60: // Volume slide down jar_xm_volume_slide(ch, ch->current->volume_column & 0x0F); break; case 0x70: // Volume slide up jar_xm_volume_slide(ch, ch->current->volume_column << 4); break; case 0x80: // Fine volume slide down jar_xm_volume_slide(ch, ch->current->volume_column & 0x0F); break; case 0x90: // Fine volume slide up jar_xm_volume_slide(ch, ch->current->volume_column << 4); break; case 0xA0: // Set vibrato speed ch->vibrato_param = (ch->vibrato_param & 0x0F) | ((ch->current->volume_column & 0x0F) << 4); break; case 0xB0: // Vibrato ch->vibrato_in_progress = false; jar_xm_vibrato(ctx, ch, ch->vibrato_param, ch->vibrato_ticks++); break; case 0xC0: // Set panning if(!ctx->current_tick ) { ch->panning = (float)(ch->current->volume_column & 0x0F) / 15.0f; } break; case 0xD0: // Panning slide left jar_xm_panning_slide(ch, ch->current->volume_column & 0x0F); break; case 0xE0: // Panning slide right jar_xm_panning_slide(ch, ch->current->volume_column << 4); break; case 0xF0: // Tone portamento if(!ctx->current_tick ) { if(ch->current->volume_column & 0x0F) { ch->tone_portamento_param = ((ch->current->volume_column & 0x0F) << 4) | (ch->current->volume_column & 0x0F); } }; jar_xm_tone_portamento(ctx, ch); break; default: break; } // Only some standard effects handled on a per tick basis // see jar_xm_handle_note_and_instrument for all effects handling on a per row basis switch(ch->current->effect_type) { case 0: /* 0xy: Arpeggio */ if(ch->current->effect_param > 0) { char arp_offset = ctx->tempo % 3; switch(arp_offset) { case 2: /* 0 -> x -> 0 -> y -> x -> … */ if(ctx->current_tick == 1) { ch->arp_in_progress = true; ch->arp_note_offset = ch->current->effect_param >> 4; jar_xm_update_frequency(ctx, ch); break; } /* No break here, this is intended */ case 1: /* 0 -> 0 -> y -> x -> … */ if(ctx->current_tick == 0) { ch->arp_in_progress = false; ch->arp_note_offset = 0; jar_xm_update_frequency(ctx, ch); break; } /* No break here, this is intended */ case 0: /* 0 -> y -> x -> … */ jar_xm_arpeggio(ctx, ch, ch->current->effect_param, ctx->current_tick - arp_offset); default: break; } } break; case 1: /* 1xx: Portamento up */ if(ctx->current_tick == 0) break; jar_xm_pitch_slide(ctx, ch, -ch->portamento_up_param); break; case 2: /* 2xx: Portamento down */ if(ctx->current_tick == 0) break; jar_xm_pitch_slide(ctx, ch, ch->portamento_down_param); break; case 3: /* 3xx: Tone portamento */ if(ctx->current_tick == 0) break; jar_xm_tone_portamento(ctx, ch); break; case 4: /* 4xy: Vibrato */ if(ctx->current_tick == 0) break; ch->vibrato_in_progress = true; jar_xm_vibrato(ctx, ch, ch->vibrato_param, ch->vibrato_ticks++); break; case 5: /* 5xy: Tone portamento + Volume slide */ if(ctx->current_tick == 0) break; jar_xm_tone_portamento(ctx, ch); jar_xm_volume_slide(ch, ch->volume_slide_param); break; case 6: /* 6xy: Vibrato + Volume slide */ if(ctx->current_tick == 0) break; ch->vibrato_in_progress = true; jar_xm_vibrato(ctx, ch, ch->vibrato_param, ch->vibrato_ticks++); jar_xm_volume_slide(ch, ch->volume_slide_param); break; case 7: /* 7xy: Tremolo */ if(ctx->current_tick == 0) break; jar_xm_tremolo(ctx, ch, ch->tremolo_param, ch->tremolo_ticks++); break; case 8: /* 8xy: Set panning */ break; case 9: /* 9xy: Sample offset */ break; case 0xA: /* Axy: Volume slide */ if(ctx->current_tick == 0) break; jar_xm_volume_slide(ch, ch->volume_slide_param); break; case 0xE: /* EXy: Extended command */ switch(ch->current->effect_param >> 4) { case 0x9: /* E9y: Retrigger note */ if(ctx->current_tick != 0 && ch->current->effect_param & 0x0F) { if(!(ctx->current_tick % (ch->current->effect_param & 0x0F))) { jar_xm_trigger_note(ctx, ch, 0); jar_xm_envelopes(ch); } } break; case 0xC: /* ECy: Note cut */ if((ch->current->effect_param & 0x0F) == ctx->current_tick) { jar_xm_cut_note(ch); } break; case 0xD: /* EDy: Note delay */ if(ch->note_delay_param == ctx->current_tick) { jar_xm_handle_note_and_instrument(ctx, ch, ch->current); jar_xm_envelopes(ch); } break; default: break; } break; case 16: /* Fxy: Set tempo/BPM */ break; case 17: /* Hxy: Global volume slide */ if(ctx->current_tick == 0) break; if((ch->global_volume_slide_param & 0xF0) && (ch->global_volume_slide_param & 0x0F)) { break; }; /* Invalid state */ if(ch->global_volume_slide_param & 0xF0) { /* Global slide up */ float f = (float)(ch->global_volume_slide_param >> 4) / (float)0x40; ctx->global_volume += f; jar_xm_CLAMP_UP(ctx->global_volume); } else { /* Global slide down */ float f = (float)(ch->global_volume_slide_param & 0x0F) / (float)0x40; ctx->global_volume -= f; jar_xm_CLAMP_DOWN(ctx->global_volume); }; break; case 20: /* Kxx: Key off */ if(ctx->current_tick == ch->current->effect_param) { jar_xm_key_off(ch); }; break; case 21: /* Lxx: Set envelope position */ break; case 25: /* Pxy: Panning slide */ if(ctx->current_tick == 0) break; jar_xm_panning_slide(ch, ch->panning_slide_param); break; case 27: /* Rxy: Multi retrig note */ if(ctx->current_tick == 0) break; if(((ch->multi_retrig_param) & 0x0F) == 0) break; if((ctx->current_tick % (ch->multi_retrig_param & 0x0F)) == 0) { float v = ch->volume * multi_retrig_multiply[ch->multi_retrig_param >> 4] + multi_retrig_add[ch->multi_retrig_param >> 4]; jar_xm_CLAMP(v); jar_xm_trigger_note(ctx, ch, 0); ch->volume = v; }; break; case 29: /* Txy: Tremor */ if(ctx->current_tick == 0) break; ch->tremor_on = ( (ctx->current_tick - 1) % ((ch->tremor_param >> 4) + (ch->tremor_param & 0x0F) + 2) > (ch->tremor_param >> 4) ); break; default: break; }; float panning, volume; panning = ch->panning + (ch->panning_envelope_panning - .5f) * (.5f - fabs(ch->panning - .5f)) * 2.0f; if(ch->tremor_on) { volume = .0f; } else { volume = ch->volume + ch->tremolo_volume; jar_xm_CLAMP(volume); volume *= ch->fadeout_volume * ch->volume_envelope_volume; }; if (mod->ramping) { ch->target_panning = panning; ch->target_volume = volume; } else { ch->actual_panning = panning; ch->actual_volume = volume; }; }; ctx->current_tick++; // ok so we understand that ticks increment within the row if(ctx->current_tick >= ctx->tempo + ctx->extra_ticks) { // This means it reached the end of the row and we reset ctx->current_tick = 0; ctx->extra_ticks = 0; }; // Number of ticks / second = BPM * 0.4 ctx->remaining_samples_in_tick += (float)ctx->rate / ((float)ctx->bpm * 0.4f); }; static void jar_xm_next_of_sample(jar_xm_context_t* ctx, jar_xm_channel_context_t* ch, int previous) { jar_xm_module_t* mod = &(ctx->module); // ch->curr_left = 0.f; // ch->curr_right = 0.f; if(ch->instrument == NULL || ch->sample == NULL || ch->sample_position < 0) { ch->curr_left = 0.f; ch->curr_right = 0.f; if (mod->ramping) { if (ch->frame_count < jar_xm_SAMPLE_RAMPING_POINTS) { if (previous > -1) { ch->end_of_previous_sample_left[previous] = jar_xm_LERP(ch->end_of_previous_sample_left[ch->frame_count], ch->curr_left, (float)ch->frame_count / (float)jar_xm_SAMPLE_RAMPING_POINTS); ch->end_of_previous_sample_right[previous] = jar_xm_LERP(ch->end_of_previous_sample_right[ch->frame_count], ch->curr_right, (float)ch->frame_count / (float)jar_xm_SAMPLE_RAMPING_POINTS); } else { ch->curr_left = jar_xm_LERP(ch->end_of_previous_sample_left[ch->frame_count], ch->curr_left, (float)ch->frame_count / (float)jar_xm_SAMPLE_RAMPING_POINTS); ch->curr_right = jar_xm_LERP(ch->end_of_previous_sample_right[ch->frame_count], ch->curr_right, (float)ch->frame_count / (float)jar_xm_SAMPLE_RAMPING_POINTS); }; }; }; return; }; if(ch->sample->length == 0) { return; }; float t = 0.f; uint32_t b = 0; if(mod->linear_interpolation) { b = ch->sample_position + 1; t = ch->sample_position - (uint32_t)ch->sample_position; /* Cheaper than fmodf(., 1.f) */ }; float u_left, u_right; u_left = ch->sample->data[(uint32_t)ch->sample_position]; if (ch->sample->stereo) { u_right = ch->sample->data[(uint32_t)ch->sample_position + ch->sample->length]; } else { u_right = u_left; }; float v_left = 0.f, v_right = 0.f; switch(ch->sample->loop_type) { case jar_xm_NO_LOOP: if(mod->linear_interpolation) { v_left = (b < ch->sample->length) ? ch->sample->data[b] : .0f; if (ch->sample->stereo) { v_right = (b < ch->sample->length) ? ch->sample->data[b + ch->sample->length] : .0f; } else { v_right = v_left; }; }; ch->sample_position += ch->step; if(ch->sample_position >= ch->sample->length) { ch->sample_position = -1; } // stop playing this sample break; case jar_xm_FORWARD_LOOP: if(mod->linear_interpolation) { v_left = ch->sample->data[ (b == ch->sample->loop_end) ? ch->sample->loop_start : b ]; if (ch->sample->stereo) { v_right = ch->sample->data[ (b == ch->sample->loop_end) ? ch->sample->loop_start + ch->sample->length : b + ch->sample->length]; } else { v_right = v_left; }; }; ch->sample_position += ch->step; if (ch->sample_position >= ch->sample->loop_end) { ch->sample_position -= ch->sample->loop_length; }; if(ch->sample_position >= ch->sample->length) { ch->sample_position = ch->sample->loop_start; }; break; case jar_xm_PING_PONG_LOOP: if(ch->ping) { if(mod->linear_interpolation) { v_left = (b >= ch->sample->loop_end) ? ch->sample->data[(uint32_t)ch->sample_position] : ch->sample->data[b]; if (ch->sample->stereo) { v_right = (b >= ch->sample->loop_end) ? ch->sample->data[(uint32_t)ch->sample_position + ch->sample->length] : ch->sample->data[b + ch->sample->length]; } else { v_right = v_left; }; }; ch->sample_position += ch->step; if(ch->sample_position >= ch->sample->loop_end) { ch->ping = false; ch->sample_position = (ch->sample->loop_end << 1) - ch->sample_position; }; if(ch->sample_position >= ch->sample->length) { ch->ping = false; ch->sample_position -= ch->sample->length - 1; }; } else { if(mod->linear_interpolation) { v_left = u_left; v_right = u_right; u_left = (b == 1 || b - 2 <= ch->sample->loop_start) ? ch->sample->data[(uint32_t)ch->sample_position] : ch->sample->data[b - 2]; if (ch->sample->stereo) { u_right = (b == 1 || b - 2 <= ch->sample->loop_start) ? ch->sample->data[(uint32_t)ch->sample_position + ch->sample->length] : ch->sample->data[b + ch->sample->length - 2]; } else { u_right = u_left; }; }; ch->sample_position -= ch->step; if(ch->sample_position <= ch->sample->loop_start) { ch->ping = true; ch->sample_position = (ch->sample->loop_start << 1) - ch->sample_position; }; if (ch->sample_position <= .0f) { ch->ping = true; ch->sample_position = .0f; }; }; break; default: v_left = .0f; v_right = .0f; break; }; float endval_left = mod->linear_interpolation ? jar_xm_LERP(u_left, v_left, t) : u_left; float endval_right = mod->linear_interpolation ? jar_xm_LERP(u_right, v_right, t) : u_right; if (mod->ramping) { if(ch->frame_count < jar_xm_SAMPLE_RAMPING_POINTS) { /* Smoothly transition between old and new sample. */ if (previous > -1) { ch->end_of_previous_sample_left[previous] = jar_xm_LERP(ch->end_of_previous_sample_left[ch->frame_count], endval_left, (float)ch->frame_count / (float)jar_xm_SAMPLE_RAMPING_POINTS); ch->end_of_previous_sample_right[previous] = jar_xm_LERP(ch->end_of_previous_sample_right[ch->frame_count], endval_right, (float)ch->frame_count / (float)jar_xm_SAMPLE_RAMPING_POINTS); } else { ch->curr_left = jar_xm_LERP(ch->end_of_previous_sample_left[ch->frame_count], endval_left, (float)ch->frame_count / (float)jar_xm_SAMPLE_RAMPING_POINTS); ch->curr_right = jar_xm_LERP(ch->end_of_previous_sample_right[ch->frame_count], endval_right, (float)ch->frame_count / (float)jar_xm_SAMPLE_RAMPING_POINTS); }; }; }; if (previous > -1) { ch->end_of_previous_sample_left[previous] = endval_left; ch->end_of_previous_sample_right[previous] = endval_right; } else { ch->curr_left = endval_left; ch->curr_right = endval_right; }; }; // gather all channel audio into stereo float static void jar_xm_mixdown(jar_xm_context_t* ctx, float* left, float* right) { jar_xm_module_t* mod = &(ctx->module); if(ctx->remaining_samples_in_tick <= 0) { jar_xm_tick(ctx); }; ctx->remaining_samples_in_tick--; *left = 0.f; *right = 0.f; if(ctx->max_loop_count > 0 && ctx->loop_count > ctx->max_loop_count) { return; } for(uint8_t i = 0; i < ctx->module.num_channels; ++i) { jar_xm_channel_context_t* ch = ctx->channels + i; if(ch->instrument != NULL && ch->sample != NULL && ch->sample_position >= 0) { jar_xm_next_of_sample(ctx, ch, -1); if(!ch->muted && !ch->instrument->muted) { *left += ch->curr_left * ch->actual_volume * (1.f - ch->actual_panning); *right += ch->curr_right * ch->actual_volume * ch->actual_panning; }; if (mod->ramping) { ch->frame_count++; jar_xm_SLIDE_TOWARDS(ch->actual_volume, ch->target_volume, ctx->volume_ramp); jar_xm_SLIDE_TOWARDS(ch->actual_panning, ch->target_panning, ctx->panning_ramp); }; }; }; if (ctx->global_volume != 1.0f) { *left *= ctx->global_volume; *right *= ctx->global_volume; }; // experimental // float counter = (float)ctx->generated_samples * 0.0001f // *left = tan(&left + sin(counter)); // *right = tan(&right + cos(counter)); // apply brick wall limiter when audio goes beyond bounderies if(*left < -1.0) {*left = -1.0;} else if(*left > 1.0) {*left = 1.0;}; if(*right < -1.0) {*right = -1.0;} else if(*right > 1.0) {*right = 1.0;}; }; void jar_xm_generate_samples(jar_xm_context_t* ctx, float* output, size_t numsamples) { if(ctx && output) { ctx->generated_samples += numsamples; for(size_t i = 0; i < numsamples; i++) { jar_xm_mixdown(ctx, output + (2 * i), output + (2 * i + 1)); }; }; }; uint64_t jar_xm_get_remaining_samples(jar_xm_context_t* ctx) { uint64_t total = 0; uint8_t currentLoopCount = jar_xm_get_loop_count(ctx); jar_xm_set_max_loop_count(ctx, 0); while(jar_xm_get_loop_count(ctx) == currentLoopCount) { total += ctx->remaining_samples_in_tick; ctx->remaining_samples_in_tick = 0; jar_xm_tick(ctx); } ctx->loop_count = currentLoopCount; return total; } //-------------------------------------------- //FILE LOADER - TODO - NEEDS TO BE CLEANED UP //-------------------------------------------- #undef DEBUG #define DEBUG(...) do { \ fprintf(stderr, __VA_ARGS__); \ fflush(stderr); \ } while(0) #define DEBUG_ERR(...) do { \ fprintf(stderr, __VA_ARGS__); \ fflush(stderr); \ } while(0) #define FATAL(...) do { \ fprintf(stderr, __VA_ARGS__); \ fflush(stderr); \ exit(1); \ } while(0) #define FATAL_ERR(...) do { \ fprintf(stderr, __VA_ARGS__); \ fflush(stderr); \ exit(1); \ } while(0) int jar_xm_create_context_from_file(jar_xm_context_t** ctx, uint32_t rate, const char* filename) { FILE* xmf; int size; int ret; xmf = fopen(filename, "rb"); if(xmf == NULL) { DEBUG_ERR("Could not open input file"); *ctx = NULL; return 3; } fseek(xmf, 0, SEEK_END); size = ftell(xmf); rewind(xmf); if(size == -1) { fclose(xmf); DEBUG_ERR("fseek() failed"); *ctx = NULL; return 4; } char* data = JARXM_MALLOC(size + 1); if(!data || fread(data, 1, size, xmf) < size) { fclose(xmf); DEBUG_ERR(data ? "fread() failed" : "JARXM_MALLOC() failed"); JARXM_FREE(data); *ctx = NULL; return 5; } fclose(xmf); ret = jar_xm_create_context_safe(ctx, data, size, rate); JARXM_FREE(data); switch(ret) { case 0: break; case 1: DEBUG("could not create context: module is not sane\n"); *ctx = NULL; return 1; break; case 2: FATAL("could not create context: malloc failed\n"); return 2; break; default: FATAL("could not create context: unknown error\n"); return 6; break; } return 0; } // not part of the original library void jar_xm_reset(jar_xm_context_t* ctx) { for (uint16_t i = 0; i < jar_xm_get_number_of_channels(ctx); i++) { jar_xm_cut_note(&ctx->channels[i]); } ctx->generated_samples = 0; ctx->current_row = 0; ctx->current_table_index = 0; ctx->current_tick = 0; ctx->tempo =ctx->default_tempo; // reset to file default value ctx->bpm = ctx->default_bpm; // reset to file default value ctx->global_volume = ctx->default_global_volume; // reset to file default value } void jar_xm_flip_linear_interpolation(jar_xm_context_t* ctx) { if (ctx->module.linear_interpolation) { ctx->module.linear_interpolation = 0; } else { ctx->module.linear_interpolation = 1; } } void jar_xm_table_jump(jar_xm_context_t* ctx, int table_ptr) { for (uint16_t i = 0; i < jar_xm_get_number_of_channels(ctx); i++) { jar_xm_cut_note(&ctx->channels[i]); } ctx->current_row = 0; ctx->current_tick = 0; if(table_ptr > 0 && table_ptr < ctx->module.length) { ctx->current_table_index = table_ptr; ctx->module.restart_position = table_ptr; // The reason to jump is to start a new loop or track } else { ctx->current_table_index = 0; ctx->module.restart_position = 0; // The reason to jump is to start a new loop or track ctx->tempo =ctx->default_tempo; // reset to file default value ctx->bpm = ctx->default_bpm; // reset to file default value ctx->global_volume = ctx->default_global_volume; // reset to file default value }; } // TRANSLATE NOTE NUMBER INTO USER VALUE (ie. 1 = C-1, 2 = C#1, 3 = D-1 ... ) const char* xm_note_chr(int number) { if (number == NOTE_OFF) { return "=="; }; number = number % 12; switch(number) { case 1: return "C-"; case 2: return "C#"; case 3: return "D-"; case 4: return "D#"; case 5: return "E-"; case 6: return "F-"; case 7: return "F#"; case 8: return "G-"; case 9: return "G#"; case 10: return "A-"; case 11: return "A#"; case 12: return "B-"; }; return "??"; }; const char* xm_octave_chr(int number) { if (number == NOTE_OFF) { return "="; }; int number2 = number - number % 12; int result = floor(number2 / 12) + 1; switch(result) { case 1: return "1"; case 2: return "2"; case 3: return "3"; case 4: return "4"; case 5: return "5"; case 6: return "6"; case 7: return "7"; case 8: return "8"; default: return "?"; /* UNKNOWN */ }; }; // TRANSLATE NOTE EFFECT CODE INTO USER VALUE const char* xm_effect_chr(int fx) { switch(fx) { case 0: return "0"; /* ZERO = NO EFFECT */ case 1: return "1"; /* 1xx: Portamento up */ case 2: return "2"; /* 2xx: Portamento down */ case 3: return "3"; /* 3xx: Tone portamento */ case 4: return "4"; /* 4xy: Vibrato */ case 5: return "5"; /* 5xy: Tone portamento + Volume slide */ case 6: return "6"; /* 6xy: Vibrato + Volume slide */ case 7: return "7"; /* 7xy: Tremolo */ case 8: return "8"; /* 8xx: Set panning */ case 9: return "9"; /* 9xx: Sample offset */ case 0xA: return "A";/* Axy: Volume slide */ case 0xB: return "B";/* Bxx: Position jump */ case 0xC: return "C";/* Cxx: Set volume */ case 0xD: return "D";/* Dxx: Pattern break */ case 0xE: return "E";/* EXy: Extended command */ case 0xF: return "F";/* Fxx: Set tempo/BPM */ case 16: return "G"; /* Gxx: Set global volume */ case 17: return "H"; /* Hxy: Global volume slide */ case 21: return "L"; /* Lxx: Set envelope position */ case 25: return "P"; /* Pxy: Panning slide */ case 27: return "R"; /* Rxy: Multi retrig note */ case 29: return "T"; /* Txy: Tremor */ case 33: return "X"; /* Xxy: Extra stuff */ default: return "?"; /* UNKNOWN */ }; } #ifdef JAR_XM_RAYLIB #include "raylib.h" // Need RayLib API calls for the DEBUG display void jar_xm_debug(jar_xm_context_t *ctx) { int size=40; int x = 0, y = 0; // DEBUG VARIABLES y += size; DrawText(TextFormat("CUR TBL = %i", ctx->current_table_index), x, y, size, WHITE); y += size; DrawText(TextFormat("CUR PAT = %i", ctx->module.pattern_table[ctx->current_table_index]), x, y, size, WHITE); y += size; DrawText(TextFormat("POS JMP = %d", ctx->position_jump), x, y, size, WHITE); y += size; DrawText(TextFormat("JMP DST = %i", ctx->jump_dest), x, y, size, WHITE); y += size; DrawText(TextFormat("PTN BRK = %d", ctx->pattern_break), x, y, size, WHITE); y += size; DrawText(TextFormat("CUR ROW = %i", ctx->current_row), x, y, size, WHITE); y += size; DrawText(TextFormat("JMP ROW = %i", ctx->jump_row), x, y, size, WHITE); y += size; DrawText(TextFormat("ROW LCT = %i", ctx->row_loop_count), x, y, size, WHITE); y += size; DrawText(TextFormat("LCT = %i", ctx->loop_count), x, y, size, WHITE); y += size; DrawText(TextFormat("MAX LCT = %i", ctx->max_loop_count), x, y, size, WHITE); x = size * 12; y = 0; y += size; DrawText(TextFormat("CUR TCK = %i", ctx->current_tick), x, y, size, WHITE); y += size; DrawText(TextFormat("XTR TCK = %i", ctx->extra_ticks), x, y, size, WHITE); y += size; DrawText(TextFormat("TCK/ROW = %i", ctx->tempo), x, y, size, ORANGE); y += size; DrawText(TextFormat("SPL TCK = %f", ctx->remaining_samples_in_tick), x, y, size, WHITE); y += size; DrawText(TextFormat("GEN SPL = %i", ctx->generated_samples), x, y, size, WHITE); y += size * 7; x = 0; size=16; // TIMELINE OF MODULE for (int i=0; i < ctx->module.length; i++) { if (i == ctx->jump_dest) { if (ctx->position_jump) { DrawRectangle(i * size * 2, y - size, size * 2, size, GOLD); } else { DrawRectangle(i * size * 2, y - size, size * 2, size, BROWN); }; }; if (i == ctx->current_table_index) { // DrawText(TextFormat("%02X", ctx->current_tick), i * size * 2, y - size, size, WHITE); DrawRectangle(i * size * 2, y, size * 2, size, RED); DrawText(TextFormat("%02X", ctx->current_row), i * size * 2, y - size, size, YELLOW); } else { DrawRectangle(i * size * 2, y, size * 2, size, ORANGE); }; DrawText(TextFormat("%02X", ctx->module.pattern_table[i]), i * size * 2, y, size, WHITE); }; y += size; jar_xm_pattern_t* cur = ctx->module.patterns + ctx->module.pattern_table[ctx->current_table_index]; /* DISPLAY CURRENTLY PLAYING PATTERN */ x += 2 * size; for(uint8_t i = 0; i < ctx->module.num_channels; i++) { DrawRectangle(x, y, 8 * size, size, PURPLE); DrawText("N", x, y, size, YELLOW); DrawText("I", x + size * 2, y, size, YELLOW); DrawText("V", x + size * 4, y, size, YELLOW); DrawText("FX", x + size * 6, y, size, YELLOW); x += 9 * size; }; x += size; for (int j=(ctx->current_row - 14); j<(ctx->current_row + 15); j++) { y += size; x = 0; if (j >=0 && j < (cur->num_rows)) { DrawRectangle(x, y, size * 2, size, BROWN); DrawText(TextFormat("%02X",j), x, y, size, WHITE); x += 2 * size; for(uint8_t i = 0; i < ctx->module.num_channels; i++) { if (j==(ctx->current_row)) { DrawRectangle(x, y, 8 * size, size, DARKGREEN); } else { DrawRectangle(x, y, 8 * size, size, DARKGRAY); }; jar_xm_pattern_slot_t *s = cur->slots + j * ctx->module.num_channels + i; // jar_xm_channel_context_t *ch = ctx->channels + i; if (s->note > 0) {DrawText(TextFormat("%s%s", xm_note_chr(s->note), xm_octave_chr(s->note) ), x, y, size, WHITE);} else {DrawText("...", x, y, size, GRAY);}; if (s->instrument > 0) { DrawText(TextFormat("%02X", s->instrument), x + size * 2, y, size, WHITE); if (s->volume_column == 0) { DrawText(TextFormat("%02X", 64), x + size * 4, y, size, YELLOW); }; } else { DrawText("..", x + size * 2, y, size, GRAY); if (s->volume_column == 0) { DrawText("..", x + size * 4, y, size, GRAY); }; }; if (s->volume_column > 0) {DrawText(TextFormat("%02X", (s->volume_column - 16)), x + size * 4, y, size, WHITE);}; if (s->effect_type > 0 || s->effect_param > 0) {DrawText(TextFormat("%s%02X", xm_effect_chr(s->effect_type), s->effect_param), x + size * 6, y, size, WHITE);}; x += 9 * size; }; }; }; } #endif // RayLib extension #endif//end of JAR_XM_IMPLEMENTATION //------------------------------------------------------------------------------- #endif//end of INCLUDE_JAR_XM_H
blit.ml
open! Import include Blit_intf module type Sequence_gen = sig type 'a t val length : _ t -> int end module Make_gen (Src : Sequence_gen) (Dst : sig include Sequence_gen val create_like : len:int -> 'a Src.t -> 'a t val unsafe_blit : ('a Src.t, 'a t) blit end) = struct let unsafe_blit = Dst.unsafe_blit let blit ~src ~src_pos ~dst ~dst_pos ~len = Ordered_collection_common.check_pos_len_exn ~pos:src_pos ~len ~total_length:(Src.length src); Ordered_collection_common.check_pos_len_exn ~pos:dst_pos ~len ~total_length:(Dst.length dst); if len > 0 then unsafe_blit ~src ~src_pos ~dst ~dst_pos ~len ;; let blito ~src ?(src_pos = 0) ?(src_len = Src.length src - src_pos) ~dst ?(dst_pos = 0) () = blit ~src ~src_pos ~len:src_len ~dst ~dst_pos ;; (* [sub] and [subo] ensure that every position of the created sequence is populated by an element of the source array. Thus every element of [dst] below is well defined. *) let sub src ~pos ~len = Ordered_collection_common.check_pos_len_exn ~pos ~len ~total_length:(Src.length src); let dst = Dst.create_like ~len src in if len > 0 then unsafe_blit ~src ~src_pos:pos ~dst ~dst_pos:0 ~len; dst ;; let subo ?(pos = 0) ?len src = sub src ~pos ~len: (match len with | Some i -> i | None -> Src.length src - pos) ;; end module Make1 (Sequence : sig include Sequence_gen val create_like : len:int -> 'a t -> 'a t val unsafe_blit : ('a t, 'a t) blit end) = Make_gen (Sequence) (Sequence) module Make1_generic (Sequence : Sequence1) = Make_gen (Sequence) (Sequence) module Make (Sequence : sig include Sequence val create : len:int -> t val unsafe_blit : (t, t) blit end) = struct module Sequence = struct type 'a t = Sequence.t open Sequence let create_like ~len _ = create ~len let length = length let unsafe_blit = unsafe_blit end include Make_gen (Sequence) (Sequence) end module Make_distinct (Src : Sequence) (Dst : sig include Sequence val create : len:int -> t val unsafe_blit : (Src.t, t) blit end) = Make_gen (struct type 'a t = Src.t open Src let length = length end) (struct type 'a t = Dst.t open Dst let length = length let create_like ~len _ = create ~len let unsafe_blit = unsafe_blit end) module Make_to_string (T : sig type t end) (To_bytes : S_distinct with type src := T.t with type dst := bytes) = struct open To_bytes let sub src ~pos ~len = Bytes0.unsafe_to_string ~no_mutation_while_string_reachable:(sub src ~pos ~len) ;; let subo ?pos ?len src = Bytes0.unsafe_to_string ~no_mutation_while_string_reachable:(subo ?pos ?len src) ;; end
scanner.c
#include "scanner.h" void *tree_sitter_typescript_external_scanner_create() { return NULL; } void tree_sitter_typescript_external_scanner_destroy(void *p) {} void tree_sitter_typescript_external_scanner_reset(void *p) {} unsigned tree_sitter_typescript_external_scanner_serialize(void *p, char *buffer) { return 0; } void tree_sitter_typescript_external_scanner_deserialize(void *p, const char *b, unsigned n) {} bool tree_sitter_typescript_external_scanner_scan(void *payload, TSLexer *lexer, const bool *valid_symbols) { return external_scanner_scan(payload, lexer, valid_symbols); }
caqti_common.ml
type counit = {absurd: 'a. 'a} let absurd {absurd} = absurd
(* Copyright (C) 2014--2019 Petter A. Urkedal <paurkedal@gmail.com> * * 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, either version 3 of the License, or (at your * option) any later version, with the OCaml static compilation exception. * * 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, see <http://www.gnu.org/licenses/>. *)
s.ml
(** A transport is used to send and receive bytes and file descriptors. Typically this will just call the usual Unix [sendmsg] and [recvmsg] functions, but other transports are possible. *) class type transport = object method send : Cstruct.t -> Unix.file_descr list -> unit Lwt.t (** [send data fds] transmits the bytes of [data] and the file descriptors in [fds]. *) method recv : Cstruct.t -> (int * Unix.file_descr list) Lwt.t (** [recv buffer] reads incoming data from the remote peer. The data is read into [buffer] and the method returns the number of bytes read and the list of attached file descriptors. *) method shutdown : unit Lwt.t (** Shut down the sending side of the connection. This will cause the peer to read end-of-file. *) method up : bool (** [up] is [true] until the transport has sent or received an end-of-file (indicating that the connection is being shut down). This can be accessed via {!Proxy.transport_up}. *) method pp : Format.formatter -> unit (** Can be used for logging. *) end type ('a, 'role) user_data = .. (** Extra data that can be attached to a proxy of type ['a] with ['role]. *) type ('a, 'role) user_data += No_data (** The default user data for a proxy. *)
(** A transport is used to send and receive bytes and file descriptors. Typically this will just call the usual Unix [sendmsg] and [recvmsg] functions, but other transports are possible. *)
fitness_storage.mli
val current : Raw_context.t -> Int64.t val increase : Raw_context.t -> Raw_context.t
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* Copyright (c) 2020-2021 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
t-powmod_ui_binexp_preinv.c
#include "fq_poly.h" #ifdef T #undef T #endif #define T fq #define CAP_T FQ #include "fq_poly_templates/test/t-powmod_ui_binexp_preinv.c" #undef CAP_T #undef T
/* Copyright (C) 2013 Mike Hansen This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
owl_stats_dist_negative_binomial.c
#include "owl_maths.h" #include "owl_stats.h" /** Negative Binomial distribution **/ long negative_binomial_rvs(double n, double p) { double Y = gamma_rvs(n, (1 - p) / p); return poisson_rvs(Y); }
/* * OWL - OCaml Scientific Computing * Copyright (c) 2016-2022 Liang Wang <liang@ocaml.xyz> */
bitcoin_cohttp_async.ml
open! Core open! Async (** Offers an implementation of a {!Bitcoin.HTTPCLIENT} using Cohttp's [Cohttp_lwt_async.Client]. *) (********************************************************************************) (** {1 Exceptions} *) (********************************************************************************) exception No_response (********************************************************************************) (** {1 Private modules} *) (********************************************************************************) module C = Cohttp module CA = Cohttp_async module CB = Cohttp_async.Body (********************************************************************************) (** {1 Public modules} *) (********************************************************************************) module Httpclient : Bitcoin.HTTPCLIENT with type 'a Monad.t = ('a, exn) Result.t Deferred.t = struct (* Unlike Lwt promises, Async promises don't attach errors to it. So, we wrap Async promises around a Result.t to satisfy the interface. *) module Monad = struct type 'a t = ('a, exn) Result.t Deferred.t let return v = Deferred.return (Ok v) let fail e = Deferred.return (Error e) let bind d f = d >>= fun res -> match res with | Ok v -> f v | Error e -> Deferred.return (Error e) let catch f g = f () >>= fun res -> match res with | Ok v -> Deferred.return (Ok v) | Error e -> g e end let post_string ~headers ~inet_addr:_ ~host ~port ~uri request = (* Leaving out the 'connection: close' here causes lingering old connections to pile up. *) let headers = C.Header.of_list (("connection", "close") :: headers) in let uri = Uri.make ~scheme:"http" ~host ~port ~path:uri () in Monitor.try_with (fun () -> Cohttp_async.Client.call ~chunked:false ~headers ~body:(CB.of_string request) `POST uri) >>= fun res -> match res with | Error exn -> Monad.fail exn | Ok (_, b) -> CB.to_string b >>= fun body -> Monad.return body end
(* Bitcoin_cohttp_async.ml Copyright (c) 2021 Michael Bacarella <m@bacarella.com> *)
stream.mli
val cases : int -> unit Alcotest.test list
pervasives.mli
(** The OCaml Standard library. This module is automatically opened at the beginning of each compilation. All components of this module can therefore be referred by their short name, without prefixing them by [Stdlib]. It particular, it provides the basic operations over the built-in types (numbers, booleans, byte sequences, strings, exceptions, references, lists, arrays, input-output channels, ...) and the {{!modules}standard library modules}. *) (** {1 Exceptions} *) external raise : exn -> 'a = "%raise" (** Raise the given exception value *) external raise_notrace : exn -> 'a = "%raise_notrace" (** A faster version [raise] which does not record the backtrace. @since 4.02.0 *) val invalid_arg : string -> 'a (** Raise exception [Invalid_argument] with the given string. *) val failwith : string -> 'a (** Raise exception [Failure] with the given string. *) exception Exit (** The [Exit] exception is not raised by any library function. It is provided for use in your programs. *) (** {1 Boolean operations} *) external not : bool -> bool = "%boolnot" (** The boolean negation. *) external ( && ) : bool -> bool -> bool = "%sequand" (** The boolean 'and'. Evaluation is sequential, left-to-right: in [e1 && e2], [e1] is evaluated first, and if it returns [false], [e2] is not evaluated at all. Right-associative operator, see {!Ocaml_operators} for more information. *) external ( || ) : bool -> bool -> bool = "%sequor" (** The boolean 'or'. Evaluation is sequential, left-to-right: in [e1 || e2], [e1] is evaluated first, and if it returns [true], [e2] is not evaluated at all. Right-associative operator, see {!Ocaml_operators} for more information. *) (** {1 Debugging} *) external __LOC__ : string = "%loc_LOC" (** [__LOC__] returns the location at which this expression appears in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d". @since 4.02.0 *) external __FILE__ : string = "%loc_FILE" (** [__FILE__] returns the name of the file currently being parsed by the compiler. @since 4.02.0 *) external __LINE__ : int = "%loc_LINE" (** [__LINE__] returns the line number at which this expression appears in the file currently being parsed by the compiler. @since 4.02.0 *) external __MODULE__ : string = "%loc_MODULE" (** [__MODULE__] returns the module name of the file being parsed by the compiler. @since 4.02.0 *) external __POS__ : string * int * int * int = "%loc_POS" (** [__POS__] returns a tuple [(file,lnum,cnum,enum)], corresponding to the location at which this expression appears in the file currently being parsed by the compiler. [file] is the current filename, [lnum] the line number, [cnum] the character position in the line and [enum] the last character position in the line. @since 4.02.0 *) external __LOC_OF__ : 'a -> string * 'a = "%loc_LOC" (** [__LOC_OF__ expr] returns a pair [(loc, expr)] where [loc] is the location of [expr] in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d". @since 4.02.0 *) external __LINE_OF__ : 'a -> int * 'a = "%loc_LINE" (** [__LINE_OF__ expr] returns a pair [(line, expr)], where [line] is the line number at which the expression [expr] appears in the file currently being parsed by the compiler. @since 4.02.0 *) external __POS_OF__ : 'a -> (string * int * int * int) * 'a = "%loc_POS" (** [__POS_OF__ expr] returns a pair [(loc,expr)], where [loc] is a tuple [(file,lnum,cnum,enum)] corresponding to the location at which the expression [expr] appears in the file currently being parsed by the compiler. [file] is the current filename, [lnum] the line number, [cnum] the character position in the line and [enum] the last character position in the line. @since 4.02.0 *) (** {1 Composition operators} *) external ( |> ) : 'a -> ('a -> 'b) -> 'b = "%revapply" (** Reverse-application operator: [x |> f |> g] is exactly equivalent to [g (f (x))]. Left-associative operator, see {!Ocaml_operators} for more information. @since 4.01 *) external ( @@ ) : ('a -> 'b) -> 'a -> 'b = "%apply" (** Application operator: [g @@ f @@ x] is exactly equivalent to [g (f (x))]. Right-associative operator, see {!Ocaml_operators} for more information. @since 4.01 *) (** {1 Integer arithmetic} *) (** Integers are [Sys.int_size] bits wide. All operations are taken modulo 2{^[Sys.int_size]}. They do not fail on overflow. *) external ( ~- ) : int -> int = "%negint" (** Unary negation. You can also write [- e] instead of [~- e]. Unary operator, see {!Ocaml_operators} for more information. *) external ( ~+ ) : int -> int = "%identity" (** Unary addition. You can also write [+ e] instead of [~+ e]. Unary operator, see {!Ocaml_operators} for more information. @since 3.12.0 *) external succ : int -> int = "%succint" (** [succ x] is [x + 1]. *) external pred : int -> int = "%predint" (** [pred x] is [x - 1]. *) external ( + ) : int -> int -> int = "%addint" (** Integer addition. Left-associative operator, see {!Ocaml_operators} for more information. *) external ( - ) : int -> int -> int = "%subint" (** Integer subtraction. Left-associative operator, , see {!Ocaml_operators} for more information. *) external ( * ) : int -> int -> int = "%mulint" (** Integer multiplication. Left-associative operator, see {!Ocaml_operators} for more information. *) external ( / ) : int -> int -> int = "%divint" (** Integer division. Raise [Division_by_zero] if the second argument is 0. Integer division rounds the real quotient of its arguments towards zero. More precisely, if [x >= 0] and [y > 0], [x / y] is the greatest integer less than or equal to the real quotient of [x] by [y]. Moreover, [(- x) / y = x / (- y) = - (x / y)]. Left-associative operator, see {!Ocaml_operators} for more information. *) external ( mod ) : int -> int -> int = "%modint" (** Integer remainder. If [y] is not zero, the result of [x mod y] satisfies the following properties: [x = (x / y) * y + x mod y] and [abs(x mod y) <= abs(y) - 1]. If [y = 0], [x mod y] raises [Division_by_zero]. Note that [x mod y] is negative only if [x < 0]. Raise [Division_by_zero] if [y] is zero. Left-associative operator, see {!Ocaml_operators} for more information. *) val abs : int -> int (** Return the absolute value of the argument. Note that this may be negative if the argument is [min_int]. *) val max_int : int (** The greatest representable integer. *) val min_int : int (** The smallest representable integer. *) (** {2 Bitwise operations} *) external ( land ) : int -> int -> int = "%andint" (** Bitwise logical and. Left-associative operator, see {!Ocaml_operators} for more information. *) external ( lor ) : int -> int -> int = "%orint" (** Bitwise logical or. Left-associative operator, see {!Ocaml_operators} for more information. *) external ( lxor ) : int -> int -> int = "%xorint" (** Bitwise logical exclusive or. Left-associative operator, see {!Ocaml_operators} for more information. *) val lnot : int -> int (** Bitwise logical negation. *) external ( lsl ) : int -> int -> int = "%lslint" (** [n lsl m] shifts [n] to the left by [m] bits. The result is unspecified if [m < 0] or [m > Sys.int_size]. Right-associative operator, see {!Ocaml_operators} for more information. *) external ( lsr ) : int -> int -> int = "%lsrint" (** [n lsr m] shifts [n] to the right by [m] bits. This is a logical shift: zeroes are inserted regardless of the sign of [n]. The result is unspecified if [m < 0] or [m > Sys.int_size]. Right-associative operator, see {!Ocaml_operators} for more information. *) external ( asr ) : int -> int -> int = "%asrint" (** [n asr m] shifts [n] to the right by [m] bits. This is an arithmetic shift: the sign bit of [n] is replicated. The result is unspecified if [m < 0] or [m > Sys.int_size]. Right-associative operator, see {!Ocaml_operators} for more information. *) (** {1 String operations} More string operations are provided in module {!String}. *) val ( ^ ) : string -> string -> string (** String concatenation. Right-associative operator, see {!Ocaml_operators} for more information. *) (** {1 Character operations} More character operations are provided in module {!Char}. *) external int_of_char : char -> int = "%identity" (** Return the ASCII code of the argument. *) val char_of_int : int -> char (** Return the character with the given ASCII code. Raise [Invalid_argument "char_of_int"] if the argument is outside the range 0--255. *) (** {1 Unit operations} *) external ignore : 'a -> unit = "%ignore" (** Discard the value of its argument and return [()]. For instance, [ignore(f x)] discards the result of the side-effecting function [f]. It is equivalent to [f x; ()], except that the latter may generate a compiler warning; writing [ignore(f x)] instead avoids the warning. *) (** {1 String conversion functions} *) val string_of_bool : bool -> string (** Return the string representation of a boolean. As the returned values may be shared, the user should not modify them directly. *) val bool_of_string_opt: string -> bool option (** Convert the given string to a boolean. Return [None] if the string is not ["true"] or ["false"]. @since 4.05 *) val string_of_int : int -> string (** Return the string representation of an integer, in decimal. *) val int_of_string_opt: string -> int option (** Convert the given string to an integer. The string is read in decimal (by default, or if the string begins with [0u]), in hexadecimal (if it begins with [0x] or [0X]), in octal (if it begins with [0o] or [0O]), or in binary (if it begins with [0b] or [0B]). The [0u] prefix reads the input as an unsigned integer in the range [[0, 2*max_int+1]]. If the input exceeds {!max_int} it is converted to the signed integer [min_int + input - max_int - 1]. The [_] (underscore) character can appear anywhere in the string and is ignored. Return [None] if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type [int]. @since 4.05 *) (** {1 Pair operations} *) external fst : 'a * 'b -> 'a = "%field0" (** Return the first component of a pair. *) external snd : 'a * 'b -> 'b = "%field1" (** Return the second component of a pair. *) (** {1 List operations} More list operations are provided in module {!List}. *) val ( @ ) : 'a list -> 'a list -> 'a list (** List concatenation. Not tail-recursive (length of the first argument). Right-associative operator, see {!Ocaml_operators} for more information. *) (** {1 References} *) type 'a ref = { mutable contents : 'a } (** The type of references (mutable indirection cells) containing a value of type ['a]. *) external ref : 'a -> 'a ref = "%makemutable" (** Return a fresh reference containing the given value. *) external ( ! ) : 'a ref -> 'a = "%field0" (** [!r] returns the current contents of reference [r]. Equivalent to [fun r -> r.contents]. Unary operator, see {!Ocaml_operators} for more information. *) external ( := ) : 'a ref -> 'a -> unit = "%setfield0" (** [r := a] stores the value of [a] in reference [r]. Equivalent to [fun r v -> r.contents <- v]. Right-associative operator, see {!Ocaml_operators} for more information. *) external incr : int ref -> unit = "%incr" (** Increment the integer contained in the given reference. Equivalent to [fun r -> r := succ !r]. *) external decr : int ref -> unit = "%decr" (** Decrement the integer contained in the given reference. Equivalent to [fun r -> r := pred !r]. *) (** {1 Result type} *) (** @since 4.03.0 *) type ('a,'b) result = Ok of 'a | Error of 'b (** {1 Operations on format strings} *) (** Format strings are character strings with special lexical conventions that defines the functionality of formatted input/output functions. Format strings are used to read data with formatted input functions from module {!Scanf} and to print data with formatted output functions from modules {!Printf} and {!Format}. Format strings are made of three kinds of entities: - {e conversions specifications}, introduced by the special character ['%'] followed by one or more characters specifying what kind of argument to read or print, - {e formatting indications}, introduced by the special character ['@'] followed by one or more characters specifying how to read or print the argument, - {e plain characters} that are regular characters with usual lexical conventions. Plain characters specify string literals to be read in the input or printed in the output. There is an additional lexical rule to escape the special characters ['%'] and ['@'] in format strings: if a special character follows a ['%'] character, it is treated as a plain character. In other words, ["%%"] is considered as a plain ['%'] and ["%@"] as a plain ['@']. For more information about conversion specifications and formatting indications available, read the documentation of modules {!Scanf}, {!Printf} and {!Format}. *) (** Format strings have a general and highly polymorphic type [('a, 'b, 'c, 'd, 'e, 'f) format6]. The two simplified types, [format] and [format4] below are included for backward compatibility with earlier releases of OCaml. The meaning of format string type parameters is as follows: - ['a] is the type of the parameters of the format for formatted output functions ([printf]-style functions); ['a] is the type of the values read by the format for formatted input functions ([scanf]-style functions). - ['b] is the type of input source for formatted input functions and the type of output target for formatted output functions. For [printf]-style functions from module {!Printf}, ['b] is typically [out_channel]; for [printf]-style functions from module {!Format}, ['b] is typically {!Format.formatter}; for [scanf]-style functions from module {!Scanf}, ['b] is typically {!Scanf.Scanning.in_channel}. Type argument ['b] is also the type of the first argument given to user's defined printing functions for [%a] and [%t] conversions, and user's defined reading functions for [%r] conversion. - ['c] is the type of the result of the [%a] and [%t] printing functions, and also the type of the argument transmitted to the first argument of [kprintf]-style functions or to the [kscanf]-style functions. - ['d] is the type of parameters for the [scanf]-style functions. - ['e] is the type of the receiver function for the [scanf]-style functions. - ['f] is the final result type of a formatted input/output function invocation: for the [printf]-style functions, it is typically [unit]; for the [scanf]-style functions, it is typically the result type of the receiver function. *) type ('a, 'b, 'c, 'd, 'e, 'f) format6 = ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6 type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6 type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4 val string_of_format : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string (** Converts a format string into a string. *) external format_of_string : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> ('a, 'b, 'c, 'd, 'e, 'f) format6 = "%identity" (** [format_of_string s] returns a format string read from the string literal [s]. Note: [format_of_string] can not convert a string argument that is not a literal. If you need this functionality, use the more general {!Scanf.format_from_string} function. *) val ( ^^ ) : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> ('f, 'b, 'c, 'e, 'g, 'h) format6 -> ('a, 'b, 'c, 'd, 'g, 'h) format6 (** [f1 ^^ f2] catenates format strings [f1] and [f2]. The result is a format string that behaves as the concatenation of format strings [f1] and [f2]: in case of formatted output, it accepts arguments from [f1], then arguments from [f2]; in case of formatted input, it returns results from [f1], then results from [f2]. Right-associative operator, see {!Ocaml_operators} for more information. *)
(**************************************************************************) (* *) (* OCaml *) (* *) (* Xavier Leroy, projet Cristal, INRIA Rocquencourt *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************)
randtest_monic.c
#ifdef T #include "templates.h" void TEMPLATE(T, poly_randtest_monic) (TEMPLATE(T, poly_t) f, flint_rand_t state, slong len, const TEMPLATE(T, ctx_t) ctx) { slong i; TEMPLATE(T, poly_fit_length) (f, len, ctx); for (i = 0; i < len - 1; i++) { TEMPLATE(T, randtest) (f->coeffs + i, state, ctx); } TEMPLATE(T, one) (f->coeffs + (len - 1), ctx); _TEMPLATE(T, poly_set_length) (f, len, ctx); _TEMPLATE(T, poly_normalise) (f, ctx); } #endif
/* Copyright (C) 2009 William Hart Copyright (C) 2012 Andres Goens Copyright (C) 2013 Mike Hansen This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
clear.c
#include "fmpz_mat.h" #include "padic_mat.h" void padic_mat_clear(padic_mat_t A) { fmpz_mat_clear(padic_mat(A)); A->val = 0; }
/* Copyright (C) 2011 Sebastian Pancratz This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
vals.mli
val f : int -> int -> int (*@ r = f y x *) val f : y:int -> int -> int (*@ r = f ~y x *) val f : ?y:int -> int -> int (*@ r = f ?y x *) val f : y:int -> ?x:int -> int (*@ r = f ~y ?x *) val f : ?y:int -> x:int -> int (*@ r = f ?y ~x *) val f : ('a -> 'b -> 'c) -> 'a -> ('b -> 'c) (*@ r = f x y z *) val f : x:('a -> 'b -> 'c) -> 'a -> ('b -> 'c) (*@ r = f ~x y z *) val f : x:('a -> 'b -> 'c) -> y:'a -> ('b -> 'c) (*@ r = f ~x ~y z *) val f : x:('a -> 'b -> 'c) -> y:'a -> ('b -> 'c) (*@ r = f ~x [w:int] ~y z *) val f : x:('a -> 'b -> 'c) -> y:'a -> ('b -> 'c) (*@ r = f ~x [w:int] ~y [p:integer] z *) val f : x:('a -> 'b -> 'c) -> y:'a -> ('b -> 'c) (*@ r,[a:'a] = f ~x [w:int] ~y [p:integer] z *) val f : x:('a -> 'b -> 'c) -> y:'a -> ('b -> 'c) (*@ [b:integer],r,[a:'a] = f ~x [w:int] ~y [p:integer] z *) val f : x:('a -> 'b -> 'c) -> y:'a -> ('b -> 'c) (*@ [b:integer],r,[a:'a] = f ~x [w:int] ~y [p:integer] z *)
(**************************************************************************) (* *) (* GOSPEL -- A Specification Language for OCaml *) (* *) (* Copyright (c) 2018- The VOCaL Project *) (* *) (* This software is free software, distributed under the MIT license *) (* (as described in file LICENSE enclosed). *) (**************************************************************************)
script_timestamp_repr.mli
(** Defines the internal Michelson representation for timestamps and basic operations that can be performed on it. *) open Script_int_repr (** Representation of timestamps specific to the Michelson interpreter. A number of seconds since the epoch. *) type t (** Convert a number of seconds since the epoch to a timestamp.*) val of_int64 : int64 -> t (** Compare timestamps. Returns [1] if the first timestamp is later than the second one; [0] if they're equal and [-1] othwerwise. *) val compare : t -> t -> int (** Convert a timestamp to RFC3339 notation if possible **) val to_notation : t -> string option (** Convert a timestamp to a string representation of the seconds *) val to_num_str : t -> string (** Convert to RFC3339 notation if possible, or num if not *) val to_string : t -> string val of_string : string -> t option (** Returns difference between timestamps as integral number of seconds in Michelson representation of numbers. *) val diff : t -> t -> z num (** Add a number of seconds to the timestamp. *) val add_delta : t -> z num -> t (** Subtract a number of seconds from the timestamp. *) val sub_delta : t -> z num -> t val to_zint : t -> Z.t val of_zint : Z.t -> t (* Timestamps are encoded exactly as Z. *) val encoding : t Data_encoding.encoding
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
default_parameters.mli
open Protocol.Alpha_context val constants_mainnet : Constants.parametric val constants_sandbox : Constants.parametric val constants_test : Constants.parametric val make_bootstrap_account : Signature.public_key_hash * Signature.public_key * Tez.t -> Parameters.bootstrap_account val parameters_of_constants : ?bootstrap_accounts:Parameters.bootstrap_account list -> ?bootstrap_contracts:Parameters.bootstrap_contract list -> ?with_commitments:bool -> Constants.parametric -> Parameters.t val json_of_parameters : Parameters.t -> Data_encoding.json
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
hdr_atomic_test.c
/** * hdr_histogram_test.c * Written by Michael Barker and released to the public domain, * as explained at http://creativecommons.org/publicdomain/zero/1.0/ */ #include <stdint.h> #include <stdio.h> #include <hdr_atomic.h> #include "minunit.h" int tests_run = 0; static char* test_store_load_64() { int64_t value = 45; int64_t b; int64_t p = 0; hdr_atomic_store_64(&p, value); mu_assert("Failed hdr_atomic_store_64", compare_int64(p, value)); b = hdr_atomic_load_64(&p); mu_assert("Failed hdr_atomic_load_64", compare_int64(p, b)); return 0; } static char* test_store_load_pointer() { int64_t r = 12; int64_t* q = 0; int64_t* s; hdr_atomic_store_pointer((void**) &q, &r); mu_assert("Failed hdr_atomic_store_pointer", compare_int64(*q, r)); s = hdr_atomic_load_pointer((void**) &q); mu_assert("Failed hdr_atomic_load_pointer", compare_int64(*s, r)); return 0; } static char* test_exchange() { int64_t val1 = 123124; int64_t val2 = 987234; int64_t p = val1; int64_t q = val2; hdr_atomic_exchange_64(&p, q); mu_assert("Failed hdr_atomic_exchange_64", compare_int64(p, val2)); return 0; } static char* test_add() { int64_t val1 = 123124; int64_t val2 = 987234; int64_t expected = val1 + val2; int64_t result = hdr_atomic_add_fetch_64(&val1, val2); mu_assert("Failed hdr_atomic_exchange_64", compare_int64(result, expected)); mu_assert("Failed hdr_atomic_exchange_64", compare_int64(val1, expected)); return 0; } static struct mu_result all_tests() { mu_run_test(test_store_load_64); mu_run_test(test_store_load_pointer); mu_run_test(test_exchange); mu_run_test(test_add); mu_ok; } static int hdr_atomic_run_tests() { struct mu_result result = all_tests(); if (result.message != 0) { printf("hdr_atomic_test.%s(): %s\n", result.test, result.message); } else { printf("ALL TESTS PASSED\n"); } printf("Tests run: %d\n", tests_run); return result.message == NULL ? 0 : -1; } int main() { return hdr_atomic_run_tests(); }
/** * hdr_histogram_test.c * Written by Michael Barker and released to the public domain, * as explained at http://creativecommons.org/publicdomain/zero/1.0/ */
is_irreducible.c
#include "fq_nmod_poly.h" #ifdef T #undef T #endif #define T fq_nmod #define CAP_T FQ_NMOD #include "fq_poly_factor_templates/is_irreducible.c" #undef CAP_T #undef T
/* Copyright (C) 2013 Mike Hansen This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
token_helpers_ml.ml
open Parser_ml module PI = Parse_info (*****************************************************************************) (* Token Helpers *) (*****************************************************************************) let is_eof = function | EOF _ -> true | _ -> false let is_comment = function | TComment _ | TCommentSpace _ | TCommentNewline _ -> true | TCommentMisc _ -> true | _ -> false (* let is_just_comment = function | TComment _ -> true | _ -> false *) let token_kind_of_tok t = match t with | TOBrace _ -> PI.LBrace | TCBrace _ -> PI.RBrace | TOParen _ -> PI.LPar | TCParen _ -> PI.RPar (* less: also TOBracket? (and TOBracketAt...) *) | TComment _ | TCommentMisc _ -> PI.Esthet PI.Comment | TCommentSpace _ -> PI.Esthet PI.Space | TCommentNewline _ -> PI.Esthet PI.Newline | _ -> PI.Other (*****************************************************************************) (* Visitors *) (*****************************************************************************) let visitor_info_of_tok f = function | LETOP (s, ii) -> LETOP (s, f ii) | ANDOP (s, ii) -> ANDOP (s, f ii) | TDots ii -> TDots (f ii) | LDots ii -> LDots (f ii) | RDots ii -> RDots (f ii) | TCommentSpace ii -> TCommentSpace (f ii) | TCommentNewline ii -> TCommentNewline (f ii) | TComment ii -> TComment (f ii) | TCommentMisc ii -> TCommentMisc (f ii) | TUnknown ii -> TUnknown (f ii) | EOF ii -> EOF (f ii) | TSharpDirective ii -> TSharpDirective (f ii) | TInt (s, ii) -> TInt (s, f ii) | TFloat (s, ii) -> TFloat (s, f ii) | TChar (s, ii) -> TChar (s, f ii) | TString (s, ii) -> TString (s, f ii) | TLowerIdent (s, ii) -> TLowerIdent (s, f ii) | TUpperIdent (s, ii) -> TUpperIdent (s, f ii) | TLabelUse (s, ii) -> TLabelUse (s, f ii) | TLabelDecl (s, ii) -> TLabelDecl (s, f ii) | TOptLabelUse (s, ii) -> TOptLabelUse (s, f ii) | TOptLabelDecl (s, ii) -> TOptLabelDecl (s, f ii) | TPrefixOperator (s, ii) -> TPrefixOperator (s, f ii) | TInfixOperator (s, ii) -> TInfixOperator (s, f ii) | Tfun ii -> Tfun (f ii) | Tfunction ii -> Tfunction (f ii) | Trec ii -> Trec (f ii) | Ttype ii -> Ttype (f ii) | Tof ii -> Tof (f ii) | Tif ii -> Tif (f ii) | Tthen ii -> Tthen (f ii) | Telse ii -> Telse (f ii) | Tmatch ii -> Tmatch (f ii) | Twith ii -> Twith (f ii) | Twhen ii -> Twhen (f ii) | Tlet ii -> Tlet (f ii) | Tin ii -> Tin (f ii) | Tas ii -> Tas (f ii) | Ttry ii -> Ttry (f ii) | Texception ii -> Texception (f ii) | Tbegin ii -> Tbegin (f ii) | Tend ii -> Tend (f ii) | Tfor ii -> Tfor (f ii) | Tdo ii -> Tdo (f ii) | Tdone ii -> Tdone (f ii) | Tdownto ii -> Tdownto (f ii) | Twhile ii -> Twhile (f ii) | Tto ii -> Tto (f ii) | Tval ii -> Tval (f ii) | Texternal ii -> Texternal (f ii) | Ttrue ii -> Ttrue (f ii) | Tfalse ii -> Tfalse (f ii) | Tmodule ii -> Tmodule (f ii) | Topen ii -> Topen (f ii) | Tfunctor ii -> Tfunctor (f ii) | Tinclude ii -> Tinclude (f ii) | Tsig ii -> Tsig (f ii) | Tstruct ii -> Tstruct (f ii) | Tclass ii -> Tclass (f ii) | Tnew ii -> Tnew (f ii) | Tinherit ii -> Tinherit (f ii) | Tconstraint ii -> Tconstraint (f ii) | Tinitializer ii -> Tinitializer (f ii) | Tmethod ii -> Tmethod (f ii) | Tobject ii -> Tobject (f ii) | Tprivate ii -> Tprivate (f ii) | Tvirtual ii -> Tvirtual (f ii) | Tlazy ii -> Tlazy (f ii) | Tmutable ii -> Tmutable (f ii) | Tassert ii -> Tassert (f ii) | Tand ii -> Tand (f ii) | Tor ii -> Tor (f ii) | Tmod ii -> Tmod (f ii) | Tlor ii -> Tlor (f ii) | Tlsl ii -> Tlsl (f ii) | Tlsr ii -> Tlsr (f ii) | Tlxor ii -> Tlxor (f ii) | Tasr ii -> Tasr (f ii) | Tland ii -> Tland (f ii) | TOParen ii -> TOParen (f ii) | TCParen ii -> TCParen (f ii) | TOBrace ii -> TOBrace (f ii) | TCBrace ii -> TCBrace (f ii) | TOBracket ii -> TOBracket (f ii) | TCBracket ii -> TCBracket (f ii) | TOBracketPipe ii -> TOBracketPipe (f ii) | TPipeCBracket ii -> TPipeCBracket (f ii) | TOBracketLess ii -> TOBracketLess (f ii) | TGreaterCBracket ii -> TGreaterCBracket (f ii) | TOBraceLess ii -> TOBraceLess (f ii) | TGreaterCBrace ii -> TGreaterCBrace (f ii) | TOBracketGreater ii -> TOBracketGreater (f ii) | TColonGreater ii -> TColonGreater (f ii) | TLess ii -> TLess (f ii) | TGreater ii -> TGreater (f ii) | TDot ii -> TDot (f ii) | TDotDot ii -> TDotDot (f ii) | TComma ii -> TComma (f ii) | TEq ii -> TEq (f ii) | TAssign ii -> TAssign (f ii) | TAssignMutable ii -> TAssignMutable (f ii) | TColon ii -> TColon (f ii) | TColonColon ii -> TColonColon (f ii) | TBang ii -> TBang (f ii) | TBangEq ii -> TBangEq (f ii) | TTilde ii -> TTilde (f ii) | TPipe ii -> TPipe (f ii) | TSemiColon ii -> TSemiColon (f ii) | TSemiColonSemiColon ii -> TSemiColonSemiColon (f ii) | TQuestion ii -> TQuestion (f ii) | TQuestionQuestion ii -> TQuestionQuestion (f ii) | TUnderscore ii -> TUnderscore (f ii) | TStar ii -> TStar (f ii) | TArrow ii -> TArrow (f ii) | TQuote ii -> TQuote (f ii) | TBackQuote ii -> TBackQuote (f ii) | TAnd ii -> TAnd (f ii) | TAndAnd ii -> TAndAnd (f ii) | TSharp ii -> TSharp (f ii) | TMinusDot ii -> TMinusDot (f ii) | TPlusDot ii -> TPlusDot (f ii) | TPlus ii -> TPlus (f ii) | TMinus ii -> TMinus (f ii) | TBracketAt ii -> TBracketAt (f ii) | TBracketAtAt ii -> TBracketAtAt (f ii) | TBracketAtAtAt ii -> TBracketAtAtAt (f ii) | TBracketPercent ii -> TBracketPercent (f ii) | TBracketPercentPercent ii -> TBracketPercentPercent (f ii) let info_of_tok tok = let res = ref None in visitor_info_of_tok (fun ii -> res := Some ii; ii) tok |> ignore; Common2.some !res (*****************************************************************************) (* Accessors *) (*****************************************************************************) let line_of_tok tok = let info = info_of_tok tok in PI.line_of_info info
(* Yoann Padioleau * * Copyright (C) 2010 Facebook * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation, with the * special exception on linking described in file license.txt. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * license.txt for more details. *)
script_typed_ir.ml
open Alpha_context open Script_int (* ---- Auxiliary types -----------------------------------------------------*) type var_annot = Var_annot of string type type_annot = Type_annot of string type field_annot = Field_annot of string type address = Contract.t * string type ('a, 'b) pair = 'a * 'b type ('a, 'b) union = L of 'a | R of 'b type never = | type _ comparable_ty = | Unit_key : type_annot option -> unit comparable_ty | Never_key : type_annot option -> never comparable_ty | Int_key : type_annot option -> z num comparable_ty | Nat_key : type_annot option -> n num comparable_ty | Signature_key : type_annot option -> signature comparable_ty | String_key : type_annot option -> string comparable_ty | Bytes_key : type_annot option -> Bytes.t comparable_ty | Mutez_key : type_annot option -> Tez.t comparable_ty | Bool_key : type_annot option -> bool comparable_ty | Key_hash_key : type_annot option -> public_key_hash comparable_ty | Key_key : type_annot option -> public_key comparable_ty | Timestamp_key : type_annot option -> Script_timestamp.t comparable_ty | Chain_id_key : type_annot option -> Chain_id.t comparable_ty | Address_key : type_annot option -> address comparable_ty | Pair_key : ('a comparable_ty * field_annot option) * ('b comparable_ty * field_annot option) * type_annot option -> ('a, 'b) pair comparable_ty | Union_key : ('a comparable_ty * field_annot option) * ('b comparable_ty * field_annot option) * type_annot option -> ('a, 'b) union comparable_ty | Option_key : 'v comparable_ty * type_annot option -> 'v option comparable_ty module type Boxed_set = sig type elt val elt_ty : elt comparable_ty module OPS : S.SET with type elt = elt val boxed : OPS.t val size : int end type 'elt set = (module Boxed_set with type elt = 'elt) module type Boxed_map = sig type key type value val key_ty : key comparable_ty module OPS : S.MAP with type key = key val boxed : value OPS.t * int end type ('key, 'value) map = (module Boxed_map with type key = 'key and type value = 'value) type operation = packed_internal_operation * Lazy_storage.diffs option type 'a ticket = {ticketer : address; contents : 'a; amount : n num} type ('arg, 'storage) script = { code : (('arg, 'storage) pair, (operation boxed_list, 'storage) pair) lambda; arg_type : 'arg ty; storage : 'storage; storage_type : 'storage ty; root_name : field_annot option; } and end_of_stack = unit and ('arg, 'ret) lambda = | Lam : ('arg * end_of_stack, 'ret * end_of_stack) descr * Script.node -> ('arg, 'ret) lambda and 'arg typed_contract = 'arg ty * address and 'ty ty = | Unit_t : type_annot option -> unit ty | Int_t : type_annot option -> z num ty | Nat_t : type_annot option -> n num ty | Signature_t : type_annot option -> signature ty | String_t : type_annot option -> string ty | Bytes_t : type_annot option -> bytes ty | Mutez_t : type_annot option -> Tez.t ty | Key_hash_t : type_annot option -> public_key_hash ty | Key_t : type_annot option -> public_key ty | Timestamp_t : type_annot option -> Script_timestamp.t ty | Address_t : type_annot option -> address ty | Bool_t : type_annot option -> bool ty | Pair_t : ('a ty * field_annot option * var_annot option) * ('b ty * field_annot option * var_annot option) * type_annot option -> ('a, 'b) pair ty | Union_t : ('a ty * field_annot option) * ('b ty * field_annot option) * type_annot option -> ('a, 'b) union ty | Lambda_t : 'arg ty * 'ret ty * type_annot option -> ('arg, 'ret) lambda ty | Option_t : 'v ty * type_annot option -> 'v option ty | List_t : 'v ty * type_annot option -> 'v boxed_list ty | Set_t : 'v comparable_ty * type_annot option -> 'v set ty | Map_t : 'k comparable_ty * 'v ty * type_annot option -> ('k, 'v) map ty | Big_map_t : 'k comparable_ty * 'v ty * type_annot option -> ('k, 'v) big_map ty | Contract_t : 'arg ty * type_annot option -> 'arg typed_contract ty | Sapling_transaction_t : Sapling.Memo_size.t * type_annot option -> Sapling.transaction ty | Sapling_state_t : Sapling.Memo_size.t * type_annot option -> Sapling.state ty | Operation_t : type_annot option -> operation ty | Chain_id_t : type_annot option -> Chain_id.t ty | Never_t : type_annot option -> never ty | Bls12_381_g1_t : type_annot option -> Bls12_381.G1.t ty | Bls12_381_g2_t : type_annot option -> Bls12_381.G2.t ty | Bls12_381_fr_t : type_annot option -> Bls12_381.Fr.t ty | Ticket_t : 'a comparable_ty * type_annot option -> 'a ticket ty and 'ty stack_ty = | Item_t : 'ty ty * 'rest stack_ty * var_annot option -> ('ty * 'rest) stack_ty | Empty_t : end_of_stack stack_ty and ('key, 'value) big_map = { id : Big_map.Id.t option; diff : ('key, 'value option) map; key_type : 'key comparable_ty; value_type : 'value ty; } and 'elt boxed_list = {elements : 'elt list; length : int} (* ---- Instructions --------------------------------------------------------*) (* The low-level, typed instructions, as a GADT whose parameters encode the typing rules. The left parameter is the typed shape of the stack before the instruction, the right one the shape after. Any program whose construction is accepted by OCaml's type-checker is guaranteed to be type-safe. Overloadings of the concrete syntax are already resolved in this representation, either by using different constructors or type witness parameters. When adding a new instruction, please check whether it is duplicating a data (rule of thumb: the type variable appears twice in the after stack, beware it might be hidden in a witness). If it is, please protect it with [check_dupable_ty]. *) and ('bef, 'aft) instr = (* stack ops *) | Drop : (_ * 'rest, 'rest) instr | Dup : ('top * 'rest, 'top * ('top * 'rest)) instr | Swap : ('tip * ('top * 'rest), 'top * ('tip * 'rest)) instr | Const : 'ty -> ('rest, 'ty * 'rest) instr (* pairs *) | Cons_pair : ('car * ('cdr * 'rest), ('car, 'cdr) pair * 'rest) instr | Car : (('car, _) pair * 'rest, 'car * 'rest) instr | Cdr : ((_, 'cdr) pair * 'rest, 'cdr * 'rest) instr | Unpair : (('car, 'cdr) pair * 'rest, 'car * ('cdr * 'rest)) instr (* options *) | Cons_some : ('v * 'rest, 'v option * 'rest) instr | Cons_none : 'a ty -> ('rest, 'a option * 'rest) instr | If_none : ('bef, 'aft) descr * ('a * 'bef, 'aft) descr -> ('a option * 'bef, 'aft) instr (* unions *) | Cons_left : ('l * 'rest, ('l, 'r) union * 'rest) instr | Cons_right : ('r * 'rest, ('l, 'r) union * 'rest) instr | If_left : ('l * 'bef, 'aft) descr * ('r * 'bef, 'aft) descr -> (('l, 'r) union * 'bef, 'aft) instr (* lists *) | Cons_list : ('a * ('a boxed_list * 'rest), 'a boxed_list * 'rest) instr | Nil : ('rest, 'a boxed_list * 'rest) instr | If_cons : ('a * ('a boxed_list * 'bef), 'aft) descr * ('bef, 'aft) descr -> ('a boxed_list * 'bef, 'aft) instr | List_map : ('a * 'rest, 'b * 'rest) descr -> ('a boxed_list * 'rest, 'b boxed_list * 'rest) instr | List_iter : ('a * 'rest, 'rest) descr -> ('a boxed_list * 'rest, 'rest) instr | List_size : ('a boxed_list * 'rest, n num * 'rest) instr (* sets *) | Empty_set : 'a comparable_ty -> ('rest, 'a set * 'rest) instr | Set_iter : ('a * 'rest, 'rest) descr -> ('a set * 'rest, 'rest) instr | Set_mem : ('elt * ('elt set * 'rest), bool * 'rest) instr | Set_update : ('elt * (bool * ('elt set * 'rest)), 'elt set * 'rest) instr | Set_size : ('a set * 'rest, n num * 'rest) instr (* maps *) | Empty_map : 'a comparable_ty * 'v ty -> ('rest, ('a, 'v) map * 'rest) instr | Map_map : (('a * 'v) * 'rest, 'r * 'rest) descr -> (('a, 'v) map * 'rest, ('a, 'r) map * 'rest) instr | Map_iter : (('a * 'v) * 'rest, 'rest) descr -> (('a, 'v) map * 'rest, 'rest) instr | Map_mem : ('a * (('a, 'v) map * 'rest), bool * 'rest) instr | Map_get : ('a * (('a, 'v) map * 'rest), 'v option * 'rest) instr | Map_update : ('a * ('v option * (('a, 'v) map * 'rest)), ('a, 'v) map * 'rest) instr | Map_get_and_update : ( 'a * ('v option * (('a, 'v) map * 'rest)), 'v option * (('a, 'v) map * 'rest) ) instr | Map_size : (('a, 'b) map * 'rest, n num * 'rest) instr (* big maps *) | Empty_big_map : 'a comparable_ty * 'v ty -> ('rest, ('a, 'v) big_map * 'rest) instr | Big_map_mem : ('a * (('a, 'v) big_map * 'rest), bool * 'rest) instr | Big_map_get : ('a * (('a, 'v) big_map * 'rest), 'v option * 'rest) instr | Big_map_update : ( 'key * ('value option * (('key, 'value) big_map * 'rest)), ('key, 'value) big_map * 'rest ) instr | Big_map_get_and_update : ( 'a * ('v option * (('a, 'v) big_map * 'rest)), 'v option * (('a, 'v) big_map * 'rest) ) instr (* string operations *) | Concat_string : (string boxed_list * 'rest, string * 'rest) instr | Concat_string_pair : (string * (string * 'rest), string * 'rest) instr | Slice_string : (n num * (n num * (string * 'rest)), string option * 'rest) instr | String_size : (string * 'rest, n num * 'rest) instr (* bytes operations *) | Concat_bytes : (bytes boxed_list * 'rest, bytes * 'rest) instr | Concat_bytes_pair : (bytes * (bytes * 'rest), bytes * 'rest) instr | Slice_bytes : (n num * (n num * (bytes * 'rest)), bytes option * 'rest) instr | Bytes_size : (bytes * 'rest, n num * 'rest) instr (* timestamp operations *) | Add_seconds_to_timestamp : ( z num * (Script_timestamp.t * 'rest), Script_timestamp.t * 'rest ) instr | Add_timestamp_to_seconds : ( Script_timestamp.t * (z num * 'rest), Script_timestamp.t * 'rest ) instr | Sub_timestamp_seconds : ( Script_timestamp.t * (z num * 'rest), Script_timestamp.t * 'rest ) instr | Diff_timestamps : ( Script_timestamp.t * (Script_timestamp.t * 'rest), z num * 'rest ) instr (* tez operations *) | Add_tez : (Tez.t * (Tez.t * 'rest), Tez.t * 'rest) instr | Sub_tez : (Tez.t * (Tez.t * 'rest), Tez.t * 'rest) instr | Mul_teznat : (Tez.t * (n num * 'rest), Tez.t * 'rest) instr | Mul_nattez : (n num * (Tez.t * 'rest), Tez.t * 'rest) instr | Ediv_teznat : (Tez.t * (n num * 'rest), (Tez.t, Tez.t) pair option * 'rest) instr | Ediv_tez : (Tez.t * (Tez.t * 'rest), (n num, Tez.t) pair option * 'rest) instr (* boolean operations *) | Or : (bool * (bool * 'rest), bool * 'rest) instr | And : (bool * (bool * 'rest), bool * 'rest) instr | Xor : (bool * (bool * 'rest), bool * 'rest) instr | Not : (bool * 'rest, bool * 'rest) instr (* integer operations *) | Is_nat : (z num * 'rest, n num option * 'rest) instr | Neg_nat : (n num * 'rest, z num * 'rest) instr | Neg_int : (z num * 'rest, z num * 'rest) instr | Abs_int : (z num * 'rest, n num * 'rest) instr | Int_nat : (n num * 'rest, z num * 'rest) instr | Add_intint : (z num * (z num * 'rest), z num * 'rest) instr | Add_intnat : (z num * (n num * 'rest), z num * 'rest) instr | Add_natint : (n num * (z num * 'rest), z num * 'rest) instr | Add_natnat : (n num * (n num * 'rest), n num * 'rest) instr | Sub_int : ('s num * ('t num * 'rest), z num * 'rest) instr | Mul_intint : (z num * (z num * 'rest), z num * 'rest) instr | Mul_intnat : (z num * (n num * 'rest), z num * 'rest) instr | Mul_natint : (n num * (z num * 'rest), z num * 'rest) instr | Mul_natnat : (n num * (n num * 'rest), n num * 'rest) instr | Ediv_intint : (z num * (z num * 'rest), (z num, n num) pair option * 'rest) instr | Ediv_intnat : (z num * (n num * 'rest), (z num, n num) pair option * 'rest) instr | Ediv_natint : (n num * (z num * 'rest), (z num, n num) pair option * 'rest) instr | Ediv_natnat : (n num * (n num * 'rest), (n num, n num) pair option * 'rest) instr | Lsl_nat : (n num * (n num * 'rest), n num * 'rest) instr | Lsr_nat : (n num * (n num * 'rest), n num * 'rest) instr | Or_nat : (n num * (n num * 'rest), n num * 'rest) instr | And_nat : (n num * (n num * 'rest), n num * 'rest) instr | And_int_nat : (z num * (n num * 'rest), n num * 'rest) instr | Xor_nat : (n num * (n num * 'rest), n num * 'rest) instr | Not_nat : (n num * 'rest, z num * 'rest) instr | Not_int : (z num * 'rest, z num * 'rest) instr (* control *) | Seq : ('bef, 'trans) descr * ('trans, 'aft) descr -> ('bef, 'aft) instr | If : ('bef, 'aft) descr * ('bef, 'aft) descr -> (bool * 'bef, 'aft) instr | Loop : ('rest, bool * 'rest) descr -> (bool * 'rest, 'rest) instr | Loop_left : ('a * 'rest, ('a, 'b) union * 'rest) descr -> (('a, 'b) union * 'rest, 'b * 'rest) instr | Dip : ('bef, 'aft) descr -> ('top * 'bef, 'top * 'aft) instr | Exec : ('arg * (('arg, 'ret) lambda * 'rest), 'ret * 'rest) instr | Apply : 'arg ty -> ( 'arg * (('arg * 'remaining, 'ret) lambda * 'rest), ('remaining, 'ret) lambda * 'rest ) instr | Lambda : ('arg, 'ret) lambda -> ('rest, ('arg, 'ret) lambda * 'rest) instr | Failwith : 'a ty -> ('a * 'rest, 'aft) instr | Nop : ('rest, 'rest) instr (* comparison *) | Compare : 'a comparable_ty -> ('a * ('a * 'rest), z num * 'rest) instr (* comparators *) | Eq : (z num * 'rest, bool * 'rest) instr | Neq : (z num * 'rest, bool * 'rest) instr | Lt : (z num * 'rest, bool * 'rest) instr | Gt : (z num * 'rest, bool * 'rest) instr | Le : (z num * 'rest, bool * 'rest) instr | Ge : (z num * 'rest, bool * 'rest) instr (* protocol *) | Address : (_ typed_contract * 'rest, address * 'rest) instr | Contract : 'p ty * string -> (address * 'rest, 'p typed_contract option * 'rest) instr | Transfer_tokens : ( 'arg * (Tez.t * ('arg typed_contract * 'rest)), operation * 'rest ) instr | Implicit_account : (public_key_hash * 'rest, unit typed_contract * 'rest) instr | Create_contract : 'g ty * 'p ty * ('p * 'g, operation boxed_list * 'g) lambda * field_annot option -> ( public_key_hash option * (Tez.t * ('g * 'rest)), operation * (address * 'rest) ) instr | Set_delegate : (public_key_hash option * 'rest, operation * 'rest) instr | Now : ('rest, Script_timestamp.t * 'rest) instr | Balance : ('rest, Tez.t * 'rest) instr | Level : ('rest, n num * 'rest) instr | Check_signature : (public_key * (signature * (bytes * 'rest)), bool * 'rest) instr | Hash_key : (public_key * 'rest, public_key_hash * 'rest) instr | Pack : 'a ty -> ('a * 'rest, bytes * 'rest) instr | Unpack : 'a ty -> (bytes * 'rest, 'a option * 'rest) instr | Blake2b : (bytes * 'rest, bytes * 'rest) instr | Sha256 : (bytes * 'rest, bytes * 'rest) instr | Sha512 : (bytes * 'rest, bytes * 'rest) instr | Source : ('rest, address * 'rest) instr | Sender : ('rest, address * 'rest) instr | Self : 'p ty * string -> ('rest, 'p typed_contract * 'rest) instr | Self_address : ('rest, address * 'rest) instr | Amount : ('rest, Tez.t * 'rest) instr | Sapling_empty_state : { memo_size : Sapling.Memo_size.t; } -> ('rest, Sapling.state * 'rest) instr | Sapling_verify_update : ( Sapling.transaction * (Sapling.state * 'rest), (z num, Sapling.state) pair option * 'rest ) instr | Dig : int * ('x * 'rest, 'rest, 'bef, 'aft) stack_prefix_preservation_witness -> ('bef, 'x * 'aft) instr | Dug : int * ('rest, 'x * 'rest, 'bef, 'aft) stack_prefix_preservation_witness -> ('x * 'bef, 'aft) instr | Dipn : int * ('fbef, 'faft, 'bef, 'aft) stack_prefix_preservation_witness * ('fbef, 'faft) descr -> ('bef, 'aft) instr | Dropn : int * ('rest, 'rest, 'bef, _) stack_prefix_preservation_witness -> ('bef, 'rest) instr | ChainId : ('rest, Chain_id.t * 'rest) instr | Never : (never * 'rest, 'aft) instr | Voting_power : (public_key_hash * 'rest, n num * 'rest) instr | Total_voting_power : ('rest, n num * 'rest) instr | Keccak : (bytes * 'rest, bytes * 'rest) instr | Sha3 : (bytes * 'rest, bytes * 'rest) instr | Add_bls12_381_g1 : ( Bls12_381.G1.t * (Bls12_381.G1.t * 'rest), Bls12_381.G1.t * 'rest ) instr | Add_bls12_381_g2 : ( Bls12_381.G2.t * (Bls12_381.G2.t * 'rest), Bls12_381.G2.t * 'rest ) instr | Add_bls12_381_fr : ( Bls12_381.Fr.t * (Bls12_381.Fr.t * 'rest), Bls12_381.Fr.t * 'rest ) instr | Mul_bls12_381_g1 : ( Bls12_381.G1.t * (Bls12_381.Fr.t * 'rest), Bls12_381.G1.t * 'rest ) instr | Mul_bls12_381_g2 : ( Bls12_381.G2.t * (Bls12_381.Fr.t * 'rest), Bls12_381.G2.t * 'rest ) instr | Mul_bls12_381_fr : ( Bls12_381.Fr.t * (Bls12_381.Fr.t * 'rest), Bls12_381.Fr.t * 'rest ) instr | Mul_bls12_381_z_fr : (Bls12_381.Fr.t * (_ num * 'rest), Bls12_381.Fr.t * 'rest) instr | Mul_bls12_381_fr_z : (_ num * (Bls12_381.Fr.t * 'rest), Bls12_381.Fr.t * 'rest) instr | Int_bls12_381_fr : (Bls12_381.Fr.t * 'rest, z num * 'rest) instr | Neg_bls12_381_g1 : (Bls12_381.G1.t * 'rest, Bls12_381.G1.t * 'rest) instr | Neg_bls12_381_g2 : (Bls12_381.G2.t * 'rest, Bls12_381.G2.t * 'rest) instr | Neg_bls12_381_fr : (Bls12_381.Fr.t * 'rest, Bls12_381.Fr.t * 'rest) instr | Pairing_check_bls12_381 : ( (Bls12_381.G1.t, Bls12_381.G2.t) pair boxed_list * 'rest, bool * 'rest ) instr | Comb : int * ('before, 'after) comb_gadt_witness -> ('before, 'after) instr | Uncomb : int * ('before, 'after) uncomb_gadt_witness -> ('before, 'after) instr | Comb_get : int * ('before, 'after) comb_get_gadt_witness -> ('before * 'rest, 'after * 'rest) instr | Comb_set : int * ('value, 'before, 'after) comb_set_gadt_witness -> ('value * ('before * 'rest), 'after * 'rest) instr | Dup_n : int * ('before, 'after) dup_n_gadt_witness -> ('before, 'after * 'before) instr | Ticket : ('a * (n num * 'rest), 'a ticket * 'rest) instr | Read_ticket : ( 'a ticket * 'rest, (address * ('a * n num)) * ('a ticket * 'rest) ) instr | Split_ticket : ( 'a ticket * ((n num * n num) * 'rest), ('a ticket * 'a ticket) option * 'rest ) instr | Join_tickets : 'a comparable_ty -> (('a ticket * 'a ticket) * 'rest, 'a ticket option * 'rest) instr and ('before, 'after) comb_gadt_witness = | Comb_one : ('a * 'before, 'a * 'before) comb_gadt_witness | Comb_succ : ('before, 'b * 'after) comb_gadt_witness -> ('a * 'before, ('a * 'b) * 'after) comb_gadt_witness and ('before, 'after) uncomb_gadt_witness = | Uncomb_one : ('rest, 'rest) uncomb_gadt_witness | Uncomb_succ : ('b * 'before, 'after) uncomb_gadt_witness -> (('a * 'b) * 'before, 'a * 'after) uncomb_gadt_witness and ('before, 'after) comb_get_gadt_witness = | Comb_get_zero : ('b, 'b) comb_get_gadt_witness | Comb_get_one : ('a * 'b, 'a) comb_get_gadt_witness | Comb_get_plus_two : ('before, 'after) comb_get_gadt_witness -> ('a * 'before, 'after) comb_get_gadt_witness and ('value, 'before, 'after) comb_set_gadt_witness = | Comb_set_zero : ('value, _, 'value) comb_set_gadt_witness | Comb_set_one : ('value, 'hd * 'tl, 'value * 'tl) comb_set_gadt_witness | Comb_set_plus_two : ('value, 'before, 'after) comb_set_gadt_witness -> ('value, 'a * 'before, 'a * 'after) comb_set_gadt_witness and ('before, 'after) dup_n_gadt_witness = | Dup_n_zero : ('a * 'rest, 'a) dup_n_gadt_witness | Dup_n_succ : ('before, 'b) dup_n_gadt_witness -> ('a * 'before, 'b) dup_n_gadt_witness (* Type witness for operations that work deep in the stack ignoring (and preserving) a prefix. The two right parameters are the shape of the stack with the (same) prefix before and after the transformation. The two left parameters are the shape of the stack without the prefix before and after. The inductive definition makes it so by construction. *) and ('bef, 'aft, 'bef_suffix, 'aft_suffix) stack_prefix_preservation_witness = | Prefix : ('fbef, 'faft, 'bef, 'aft) stack_prefix_preservation_witness -> ('fbef, 'faft, 'x * 'bef, 'x * 'aft) stack_prefix_preservation_witness | Rest : ('bef, 'aft, 'bef, 'aft) stack_prefix_preservation_witness and ('bef, 'aft) descr = { loc : Script.location; bef : 'bef stack_ty; aft : 'aft stack_ty; instr : ('bef, 'aft) instr; }
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
Desugar_jsonnet.mli
(* Hook to customize how ojsonnet should resolve import expressions * (`local $NAME = import $PATH`). The first parameter below is the base * directory of the file currently processed and the second is the $PATH * above in the local expression. * The hook should return an AST_jsonnet expression if it can handle * the PATH or None, in which case it will default to a regular * jsonnet file import as in `local x = import "foo.jsonnet". * * This callback is useful for example in osemgrep to let ojsonnet * import yaml files (e.g., local x = import 'foo.yaml') or rules from the * registry (e.g., local x = import 'p/python'). *) type import_callback = Common.dirname -> string -> AST_jsonnet.expr option val default_callback : import_callback (* We pass the original file in addition to its AST so desugar can * handle correctly imports by using the dirname of the file as the * base directory for imports. * The use_std argument is set to true by default and means that * the program is first prefixed with 'local std = import "std.jsonnet" * where std.jsonnet is the content in Std_jsonnet.std. *) val desugar_program : ?import_callback:import_callback -> ?use_std:bool -> Common.filename -> AST_jsonnet.program -> Core_jsonnet.program
(* Hook to customize how ojsonnet should resolve import expressions * (`local $NAME = import $PATH`). The first parameter below is the base * directory of the file currently processed and the second is the $PATH * above in the local expression. * The hook should return an AST_jsonnet expression if it can handle * the PATH or None, in which case it will default to a regular * jsonnet file import as in `local x = import "foo.jsonnet". * * This callback is useful for example in osemgrep to let ojsonnet * import yaml files (e.g., local x = import 'foo.yaml') or rules from the * registry (e.g., local x = import 'p/python'). *)
myocamlbuild.ml
open Ocamlbuild_plugin open Command (* no longer needed for OCaml >= 3.10.2 *) (** Overview of tags: - [pkg_batteries] to use Batteries as a library, without syntax extensions - [use_batteries] and [use_batteries_r] to use both Batteries and all the non-destructive syntax extensions - [pkg_sexplib.syntax] with [syntax_camlp4o] or [syntax_camlp4r] for sexplib *) (** {1 OCamlFind} *) let run_and_read = Ocamlbuild_pack.My_unix.run_and_read let blank_sep_strings = Ocamlbuild_pack.Lexers.blank_sep_strings module OCamlFind = struct (* this lists all supported packages *) let find_packages () = blank_sep_strings & Lexing.from_string & run_and_read "ocamlfind list | cut -d' ' -f1" (* this is supposed to list available syntaxes, but I don't know how to do it. *) let find_syntaxes () = ["camlp4o"; "camlp4r"] (* ocamlfind command *) let ocamlfind x = S[A"ocamlfind"; x] let before_options () = (* by using Before_options one let command line options have an higher priority *) (* on the contrary using After_options will guarantee to have the higher priority *) (* override default commands by ocamlfind ones *) Options.ocamlc := ocamlfind & A"ocamlc"; Options.ocamlopt := ocamlfind & A"ocamlopt"; Options.ocamldep := ocamlfind & A"ocamldep"; Options.ocamldoc := ocamlfind & A"ocamldoc"; Options.ocamlmktop := ocamlfind & A"ocamlmktop" let get_ocamldoc_directory () = let ocamldoc_directory = run_and_read "ocamlfind ocamldoc -customdir" in let length = String.length ocamldoc_directory in assert (length != 0); let char = ocamldoc_directory.[length - 1] in if (char = '\n') || (char = '\r') then String.sub ocamldoc_directory 0 (length - 1) else ocamldoc_directory let after_rules () = (* When one link an OCaml library/binary/package, one should use -linkpkg *) flag ["ocaml"; "byte"; "link"; "program"] & A"-linkpkg"; flag ["ocaml"; "native"; "link"; "program"] & A"-linkpkg"; flag ["ocaml"; "native"; "link"; "toplevel"] & A"-linkpkg"; (* For each ocamlfind package one inject the -package option when * compiling, computing dependencies, generating documentation and * linking. *) List.iter begin fun pkg -> flag ["ocaml"; "compile"; "pkg_"^pkg] & S[A"-package"; A pkg]; flag ["ocaml"; "ocamldep"; "pkg_"^pkg] & S[A"-package"; A pkg]; flag ["ocaml"; "doc"; "pkg_"^pkg] & S[A"-package"; A pkg]; flag ["ocaml"; "link"; "pkg_"^pkg] & S[A"-package"; A pkg]; end (find_packages ()); (* Like -package but for extensions syntax. Morover -syntax is useless * when linking. *) List.iter begin fun syntax -> flag ["ocaml"; "compile"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; flag ["ocaml"; "ocamldep"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; flag ["ocaml"; "doc"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; end (find_syntaxes ()); (* The default "thread" tag is not compatible with ocamlfind. Indeed, the default rules add the "threads.cma" or "threads.cmxa" options when using this tag. When using the "-linkpkg" option with ocamlfind, this module will then be added twice on the command line. To solve this, one approach is to add the "-thread" option when using the "threads" package using the previous plugin. *) flag ["ocaml"; "pkg_threads"; "compile"] (S[A "-thread"]); flag ["ocaml"; "pkg_threads"; "link"] (S[A "-thread"]); end (** {1 OCaml Batteries Included} *) module Batteries = struct let before_options () = () let after_rules () = flag ["ocaml"; "link"; "byte"; "use_ocamldoc_info"] (S[A "-I"; A "+ocamldoc"; A "odoc_info.cma"]); flag ["ocaml"; "link"; "native"; "use_ocamldoc_info"] (S[A "-I"; A "+ocamldoc"(*; A "odoc_info.cmxa"*)]); flag ["ocaml"; "docfile"; "use_ocamldoc_info"] (S[A "-I"; A "+ocamldoc"]); flag ["ocaml"; "docdir"; "use_ocamldoc_info"] (S[A "-I"; A "+ocamldoc"]); flag ["ocaml"; "doc"; "use_ocamldoc_info"] (S[A "-I"; A "+ocamldoc"]); (*The command-line for [use_batteries] and [use_batteries_r]*) let cl_use_boilerplate = [A "-package"; A "batteries"] and cl_use_batteries = [A "-package"; A "batteries"] and cl_use_batteries_o = [] (*[cl_use_batteries_o]: extensions which only make sense in original syntax*) and cl_camlp4o = [A"-syntax"; A "camlp4o"] and cl_camlp4r = [A"-syntax"; A "camlp4r"] in let cl_boilerplate_original = cl_use_boilerplate @ cl_camlp4o and cl_boilerplate_revised = cl_use_boilerplate @ cl_camlp4r and cl_batteries_original = cl_use_batteries @ cl_use_batteries_o @ cl_camlp4o and cl_batteries_revised = cl_use_batteries @ cl_camlp4r in (** Tag [use_boilerplate] provides boilerplate syntax extensions, in original syntax*) flag ["ocaml"; "compile"; "use_boilerplate"] & S cl_boilerplate_original ; flag ["ocaml"; "ocamldep"; "use_boilerplate"] & S cl_boilerplate_original ; flag ["ocaml"; "doc"; "use_boilerplate"] & S cl_boilerplate_original ; flag ["ocaml"; "link"; "use_boilerplate"] & S cl_boilerplate_original ; (** Tag [use_boilerplate_r] provides boilerplate syntax extensions, in original syntax*) flag ["ocaml"; "compile"; "use_boilerplate_r"] & S cl_boilerplate_revised ; flag ["ocaml"; "ocamldep"; "use_boilerplate_r"] & S cl_boilerplate_revised ; flag ["ocaml"; "doc"; "use_boilerplate_r"] & S cl_boilerplate_revised ; flag ["ocaml"; "link"; "use_boilerplate_r"] & S cl_boilerplate_revised ; (** Tag [use_batteries] provides both package [batteries] and all syntax extensions, in original syntax. *) flag ["ocaml"; "compile"; "use_batteries"] & S cl_batteries_original ; flag ["ocaml"; "ocamldep"; "use_batteries"] & S cl_batteries_original ; flag ["ocaml"; "doc"; "use_batteries"] & S cl_batteries_original ; flag ["ocaml"; "link"; "use_batteries"] & S cl_batteries_original ; (** Tag [use_batteries_r] provides both package [batteries] and all syntax extensions, in revised syntax. *) flag ["ocaml"; "compile"; "use_batteries_r"] & S cl_batteries_revised; flag ["ocaml"; "ocamldep"; "use_batteries_r"] & S cl_batteries_revised; flag ["ocaml"; "doc"; "use_batteries_r"] & S cl_batteries_revised; flag ["ocaml"; "link"; "use_batteries_r"] & S cl_batteries_revised (* flag ["ocaml"; "compile"; "use_batteries"] & S[A "-verbose"; A"-package"; A "batteries.syntax.full"; A"-syntax"; A "batteries.syntax.full"]; flag ["ocaml"; "ocamldep"; "use_batteries"] & S[A "-verbose"; A"-package"; A "batteries.syntax.full"; A"-syntax"; A "batteries.syntax.full"]; flag ["ocaml"; "doc"; "use_batteries"] & S[A "-verbose"; A"-package"; A "batteries.syntax.full"; A"-syntax"; A "batteries.syntax.full"]; flag ["ocaml"; "link"; "use_batteries"] & S[A "-verbose"; A"-package"; A "batteries.syntax.full"; A"-syntax"; A "batteries.syntax.full"];*) end let _ = dispatch begin function | Before_options -> OCamlFind.before_options (); Batteries.before_options () | After_rules -> OCamlFind.after_rules (); Batteries.after_rules () | _ -> () end (** which ocamlrun -> header print_backtrace -> ajouter "-b" après le header **)
Reference.ml
(* We use OCaml's Map module, specialized to integer keys and integer values, as a reference implementation. *) include Map.Make(Int) (* Define the type [map]. *) type map = int t (* Some boilerplate is required in order to satisfy the signature [S]. *) let union f m1 m2 = union (fun _key v1 v2 -> Some (f v1 v2)) m1 m2
(******************************************************************************) (* *) (* Monolith *) (* *) (* François Pottier *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Lesser General Public License as published by the Free *) (* Software Foundation, either version 3 of the License, or (at your *) (* option) any later version, as described in the file LICENSE. *) (* *) (******************************************************************************)
lin_tests_dsl_thread.ml
(* ********************************************************************** *) (* Tests of in and out channels *) (* ********************************************************************** *) open Lin_tests_dsl_common_io.Lin_tests_dsl_common module IC_thread = Lin_thread.Make(ICConf) [@@alert "-experimental"] module OC_thread = Lin_thread.Make(OCConf) [@@alert "-experimental"] let _ = QCheck_base_runner.run_tests_main [ IC_thread.neg_lin_test ~count:1000 ~name:"Lin DSL In_channel test with Thread"; OC_thread.neg_lin_test ~count:1000 ~name:"Lin DSL Out_channel test with Thread"; ]
(* ********************************************************************** *) (* Tests of in and out channels *) (* ********************************************************************** *)
ppx_log_lib_with_source_pos.mli
open! Core open! Async val log_global_info : string -> unit val log_info : Log.t -> string -> unit
period_repr.mli
type t type period = t include Compare.S with type t := t val encoding : period Data_encoding.t val pp: Format.formatter -> period -> unit val to_seconds : period -> int64 (** [of_second period] fails if period is not positive *) val of_seconds : int64 -> period tzresult (** [of_second period] fails if period is not positive. It should only be used at toplevel for constants. *) val of_seconds_exn : int64 -> period val mult : int32 -> period -> period tzresult val one_second : period val one_minute : period val one_hour : period
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
norm.ml
(* Normalise cycles and name them *) open Printf let arch = ref `PPC let lowercase = ref false let bell = ref None let variant = ref (fun (_:Variant_gen.t) -> false) let typ = ref TypBase.default let args = ref [] let opts = ("-lowercase", Arg.Bool (fun b -> lowercase := b), sprintf "<bool> use lowercase familly names, default %b" !lowercase):: ("-bell",Arg.String (fun f -> bell := Some f; arch := `LISA), "<name> read bell file <name>"):: Util.parse_tag "-arch" (fun tag -> match Archs.parse tag with | None -> false | Some a -> arch := a ; true) Archs.tags "specify architecture":: Util.parse_tag "-variant" (fun tag -> match Variant_gen.parse tag with | None -> false | Some v0 -> let ov = !variant in variant := (fun v -> v = v0 || ov v) ; true) Variant_gen.tags (sprintf "specify variant"):: Util.parse_tag "-type" (fun tag -> match TypBase.parse tag with | None -> false | Some a -> typ := a ; true) TypBase.tags (sprintf "specify base type, default %s" (TypBase.pp !typ)):: [] module type Config = sig val lowercase : bool val sufname : string option val variant : Variant_gen.t -> bool val naturalsize : MachSize.sz end module Make(Co:Config) (A:Fence.S) = struct module E = Edge.Make(Co)(A) module N = Namer.Make(A)(E) module Norm = Normaliser.Make(Co)(E) let zyva es = try let es = List.map E.parse_edge es in let base,es,_ = Norm.normalise_family (E.resolve_edges es) in let name = N.mk_name base ?scope:None es in Printf.printf "%s: %s\n" name (E.pp_edges es) with Misc.Fatal msg -> eprintf "Fatal error: %s\n" msg ; exit 2 end let () = Util.parse_cmdline opts (fun a -> args := a :: !args) let () = let args = List.rev !args in let module Co = struct let lowercase = !lowercase let sufname = None let variant = !variant let naturalsize = TypBase.get_size !typ end in let module Build = Make(Co) in (match !arch with | `X86 -> let module M = Build(X86Arch_gen) in M.zyva | `X86_64 -> assert false | `PPC -> let module M = Build(PPCArch_gen.Make(PPCArch_gen.Config)) in M.zyva | `ARM -> let module M = Build(ARMArch_gen.Make(ARMArch_gen.Config)) in M.zyva | `AArch64 -> let module A = AArch64Arch_gen.Make (struct include AArch64Arch_gen.Config let moreedges = !Config.moreedges end) in let module M = Build(A) in M.zyva | `MIPS -> let module M = Build(MIPSArch_gen.Make(MIPSArch_gen.Config)) in M.zyva | `RISCV -> let module M = Build(RISCVArch_gen.Make(RISCVArch_gen.Config)) in M.zyva | `LISA -> let module BellConfig = Config.ToLisa(Config) in let module M = Build(BellArch_gen.Make(BellConfig)) in M.zyva | `C | `CPP -> let module M = Build(CArch_gen) in M.zyva | `JAVA | `ASL -> assert false) args
(****************************************************************************) (* the diy toolsuite *) (* *) (* Jade Alglave, University College London, UK. *) (* Luc Maranget, INRIA Paris-Rocquencourt, France. *) (* *) (* Copyright 2018-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. *) (****************************************************************************)
lu.c
#include <stdio.h> #include <stdlib.h> #include "flint.h" #include "ulong_extras.h" #include "nmod_vec.h" #include "nmod_mat.h" slong nmod_mat_lu(slong * P, nmod_mat_t A, int rank_check) { slong nrows, ncols, n, cutoff; int nlimbs, bits; nrows = A->r; ncols = A->c; n = FLINT_MIN(nrows, ncols); if (n <= 3) { return nmod_mat_lu_classical(P, A, rank_check); } else { if (n >= 20) { bits = NMOD_BITS(A->mod); if (bits >= FLINT_BITS - 1) cutoff = 80; else if (bits >= FLINT_BITS / 2 - 2) cutoff = 60; else if (bits >= FLINT_BITS / 4 - 1) cutoff = 180; else cutoff = 60; if (n >= cutoff) return nmod_mat_lu_recursive(P, A, rank_check); } nlimbs = _nmod_vec_dot_bound_limbs(n, A->mod); if (nlimbs <= 1 || (nlimbs == 2 && n >= 12) || (nlimbs == 3 && n >= 20)) return nmod_mat_lu_classical_delayed(P, A, rank_check); else return nmod_mat_lu_classical(P, A, rank_check); } }
/* Copyright (C) 2011, 2021 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/>. */
pr7381.ml
(* TEST * expect *) type (_,_) eql = Refl : ('a, 'a) eql;; [%%expect{| type (_, _) eql = Refl : ('a, 'a) eql |}] let f : type t. (int, t) eql * (t, string) eql -> unit = function _ -> . ;; [%%expect{| val f : (int, 't) eql * ('t, string) eql -> unit = <fun> |}] let f : type t. ((int, t) eql * (t, string) eql) option -> unit = function None -> () ;; [%%expect{| val f : ((int, 't) eql * ('t, string) eql) option -> unit = <fun> |}]
(* TEST * expect *)
trace_types.mli
(** trace.proto Types *) (** {2 Types} *) type span_span_kind = | Span_kind_unspecified | Span_kind_internal | Span_kind_server | Span_kind_client | Span_kind_producer | Span_kind_consumer type span_event = { time_unix_nano : int64; name : string; attributes : Common_types.key_value list; dropped_attributes_count : int32; } type span_link = { trace_id : bytes; span_id : bytes; trace_state : string; attributes : Common_types.key_value list; dropped_attributes_count : int32; } type status_status_code = | Status_code_unset | Status_code_ok | Status_code_error type status = { message : string; code : status_status_code; } type span = { trace_id : bytes; span_id : bytes; trace_state : string; parent_span_id : bytes; name : string; kind : span_span_kind; start_time_unix_nano : int64; end_time_unix_nano : int64; attributes : Common_types.key_value list; dropped_attributes_count : int32; events : span_event list; dropped_events_count : int32; links : span_link list; dropped_links_count : int32; status : status option; } type scope_spans = { scope : Common_types.instrumentation_scope option; spans : span list; schema_url : string; } type resource_spans = { resource : Resource_types.resource option; scope_spans : scope_spans list; schema_url : string; } type traces_data = { resource_spans : resource_spans list; } (** {2 Default values} *) val default_span_span_kind : unit -> span_span_kind (** [default_span_span_kind ()] is the default value for type [span_span_kind] *) val default_span_event : ?time_unix_nano:int64 -> ?name:string -> ?attributes:Common_types.key_value list -> ?dropped_attributes_count:int32 -> unit -> span_event (** [default_span_event ()] is the default value for type [span_event] *) val default_span_link : ?trace_id:bytes -> ?span_id:bytes -> ?trace_state:string -> ?attributes:Common_types.key_value list -> ?dropped_attributes_count:int32 -> unit -> span_link (** [default_span_link ()] is the default value for type [span_link] *) val default_status_status_code : unit -> status_status_code (** [default_status_status_code ()] is the default value for type [status_status_code] *) val default_status : ?message:string -> ?code:status_status_code -> unit -> status (** [default_status ()] is the default value for type [status] *) val default_span : ?trace_id:bytes -> ?span_id:bytes -> ?trace_state:string -> ?parent_span_id:bytes -> ?name:string -> ?kind:span_span_kind -> ?start_time_unix_nano:int64 -> ?end_time_unix_nano:int64 -> ?attributes:Common_types.key_value list -> ?dropped_attributes_count:int32 -> ?events:span_event list -> ?dropped_events_count:int32 -> ?links:span_link list -> ?dropped_links_count:int32 -> ?status:status option -> unit -> span (** [default_span ()] is the default value for type [span] *) val default_scope_spans : ?scope:Common_types.instrumentation_scope option -> ?spans:span list -> ?schema_url:string -> unit -> scope_spans (** [default_scope_spans ()] is the default value for type [scope_spans] *) val default_resource_spans : ?resource:Resource_types.resource option -> ?scope_spans:scope_spans list -> ?schema_url:string -> unit -> resource_spans (** [default_resource_spans ()] is the default value for type [resource_spans] *) val default_traces_data : ?resource_spans:resource_spans list -> unit -> traces_data (** [default_traces_data ()] is the default value for type [traces_data] *)
(** trace.proto Types *)
tx_rollup_withdraw_repr.ml
type order = { claimer : Signature.Public_key_hash.t; ticket_hash : Ticket_hash_repr.t; amount : Tx_rollup_l2_qty.t; } type t = order let encoding : t Data_encoding.t = let open Data_encoding in conv (fun {claimer; ticket_hash; amount} -> (claimer, ticket_hash, amount)) (fun (claimer, ticket_hash, amount) -> {claimer; ticket_hash; amount}) (obj3 (req "claimer" Signature.Public_key_hash.encoding) (req "ticket_hash" Ticket_hash_repr.encoding) (req "amount" Tx_rollup_l2_qty.encoding))
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2022 Marigold <contact@marigold.dev> *) (* Copyright (c) 2022 Nomadic Labs <contact@nomadic-labs.com> *) (* Copyright (c) 2022 Oxhead Alpha <info@oxheadalpha.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
tx_rollup_node.mli
type t val create : ?path:string -> ?runner:Runner.t -> ?data_dir:string -> ?addr:string -> ?dormant_mode:bool -> ?color:Log.Color.t -> ?event_pipe:string -> ?name:string -> rollup_id:string -> rollup_genesis:string -> ?operator:string -> ?batch_signer:string -> ?finalize_commitment_signer:string -> ?remove_commitment_signer:string -> ?rejection_signer:string -> Client.t -> Node.t -> t (** Returns the node's endpoint. *) val endpoint : t -> string (** Wait until the node is ready. More precisely, wait until a [node_is_ready] event occurs. If such an event already occurred, return immediately. *) val wait_for_ready : t -> unit Lwt.t (** Wait for a given Tezos chain level. More precisely, wait until the rollup node have successfully validated a block of given [level], received from the Tezos node it is connected to. If such an event already occurred, return immediately. *) val wait_for_tezos_level : t -> int -> int Lwt.t (** Wait for a custom event to occur. Usage: [wait_for_full daemon name filter] If an event named [name] occurs, apply [filter] to its whole json, which is of the form: {[{ "fd-sink-item.v0": { "hostname": "...", "time_stamp": ..., "section": [ ... ], "event": { <name>: ... } } }]} If [filter] returns [None], continue waiting. If [filter] returns [Some x], return [x]. [where] is used as the [where] field of the [Terminated_before_event] exception if the daemon terminates. It should describe the constraint that [filter] applies, such as ["field level exists"]. It is advised to register such event handlers before starting the daemon, as if they occur before being registered, they will not trigger your handler. For instance, you can define a promise with [let x_event = wait_for daemon "x" (fun x -> Some x)] and bind it later with [let* x = x_event]. *) val wait_for_full : ?where:string -> t -> string -> (JSON.t -> 'a option) -> 'a Lwt.t (** Same as [wait_for_full] but ignore metadata from the file descriptor sink. More precisely, [filter] is applied to the value of field ["fd-sink-item.v0"."event".<name>]. If the daemon receives a JSON value that does not match the right JSON structure, it is not given to [filter] and the event is ignored. See [wait_for_full] to know what the JSON value must look like. *) val wait_for : ?where:string -> t -> string -> (JSON.t -> 'a option) -> 'a Lwt.t (** Connected to a tezos node. Returns the name of the configuration file. *) val config_init : t -> string -> string -> string Lwt.t (** [run node] launches the given transaction rollup node. *) val run : t -> unit Lwt.t (** See [Daemon.Make.terminate]. *) val terminate : ?kill:bool -> t -> unit Lwt.t (** Get the RPC address given as [--rpc-addr] to a node. *) val rpc_addr : t -> string module Inbox : sig type l2_context_hash = {irmin_hash : string; tree_hash : string} type message = { message : JSON.t; result : JSON.t; l2_context_hash : l2_context_hash; } type t = {contents : message list; cumulated_size : int} end (* FIXME/TORU: This is a temporary way of querying the node without tx_rollup_client. This aims to be replaced as soon as possible by the dedicated client's RPC. *) module Client : sig val get_inbox : tx_node:t -> block:string -> Inbox.t Lwt.t val get_balance : tx_node:t -> block:string -> ticket_id:string -> tz4_address:string -> int Lwt.t val get_queue : tx_node:t -> JSON.t Lwt.t val get_transaction_in_queue : tx_node:t -> string -> JSON.t Lwt.t val get_block : tx_node:t -> block:string -> JSON.t Lwt.t val get_merkle_proof : tx_node:t -> block:string -> message_pos:string -> JSON.t Lwt.t end
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2022 Nomadic Labs, <contact@nomadic-labs.com> *) (* Copyright (c) 2022 Marigold, <contact@marigold.dev> *) (* Copyright (c) 2022 Oxhead Alpha <info@oxhead-alpha.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
dummy_context.ml
module M = struct type t = unit type key = string list type value = Bytes.t type tree = | module Tree = struct let pp _ _ = assert false let hash _ = assert false let empty _ = assert false let equal _ _ = assert false let is_empty _ = assert false let mem _ _ = assert false let kind _ = assert false let to_value _ = assert false let of_value _ _ = assert false let find _ _ = assert false let add _ _ _ = assert false let remove _ _ = assert false let mem_tree _ _ = assert false let find_tree _ _ = assert false let add_tree _ _ = assert false let clear ?depth:_ _ = assert false let list _ ?offset:_ ?length:_ _ = assert false let fold ?depth:_ _ _ ~order:_ ~init:_ ~f:_ = assert false end include Tree let set_protocol _ _ = assert false let get_protocol _ = assert false let fork_test_chain _ ~protocol:_ ~expiration:_ = assert false let set_hash_version _ _ = assert false let get_hash_version _ = assert false end open Tezos_protocol_environment include Environment_context.Register (M) let empty = Context.make ~ops ~ctxt:() ~kind:Context ~equality_witness ~impl_name:"dummy"
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
bootstrap_storage.mli
val init : Raw_context.t -> typecheck: (Raw_context.t -> Script_repr.t -> ((Script_repr.t * Lazy_storage_diff.diffs option) * Raw_context.t) tzresult Lwt.t) -> ?no_reward_cycles:int -> Parameters_repr.bootstrap_account list -> Parameters_repr.bootstrap_contract list -> (Raw_context.t * Receipt_repr.balance_updates) tzresult Lwt.t val cycle_end : Raw_context.t -> Cycle_repr.t -> Raw_context.t tzresult Lwt.t
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
int63_emul.ml
(* A 63bit integer is a 64bit integer with its bits shifted to the left and its lowest bit set to 0. This is the same kind of encoding as OCaml int on 64bit architecture. The only difference being the lowest bit (immediate bit) set to 1. *) open! Import include Int64_replace_polymorphic_compare module T0 = struct module T = struct type t = int64 [@@deriving_inline compare, hash, sexp, sexp_grammar] let compare = (compare_int64 : t -> t -> int) let (hash_fold_t : Ppx_hash_lib.Std.Hash.state -> t -> Ppx_hash_lib.Std.Hash.state) = hash_fold_int64 and (hash : t -> Ppx_hash_lib.Std.Hash.hash_value) = let func = hash_int64 in fun x -> func x ;; let t_of_sexp = (int64_of_sexp : Sexplib0.Sexp.t -> t) let sexp_of_t = (sexp_of_int64 : t -> Sexplib0.Sexp.t) let (t_sexp_grammar : t Sexplib0.Sexp_grammar.t) = int64_sexp_grammar [@@@end] let hashable : t Hashable.t = { hash; compare; sexp_of_t } end include T include Comparator.Make (T) end module Conv = Int_conversions module W : sig include module type of struct include T0 end type t = int64 val wrap_exn : Caml.Int64.t -> t val wrap_modulo : Caml.Int64.t -> t val unwrap : t -> Caml.Int64.t (** Returns a non-negative int64 that is equal to the input int63 modulo 2^63. *) val unwrap_unsigned : t -> Caml.Int64.t val invariant : t -> unit val add : t -> t -> t val sub : t -> t -> t val neg : t -> t val abs : t -> t val succ : t -> t val pred : t -> t val mul : t -> t -> t val pow : t -> t -> t val div : t -> t -> t val rem : t -> t -> t val popcount : t -> int val bit_not : t -> t val bit_xor : t -> t -> t val bit_or : t -> t -> t val bit_and : t -> t -> t val shift_left : t -> int -> t val shift_right : t -> int -> t val shift_right_logical : t -> int -> t val min_value : t val max_value : t val to_int64 : t -> Caml.Int64.t val of_int64 : Caml.Int64.t -> t option val of_int64_exn : Caml.Int64.t -> t val of_int64_trunc : Caml.Int64.t -> t val compare : t -> t -> int val ceil_pow2 : t -> t val floor_pow2 : t -> t val ceil_log2 : t -> int val floor_log2 : t -> int val is_pow2 : t -> bool val clz : t -> int val ctz : t -> int end = struct include T0 type t = int64 let wrap_exn x = (* Raises if the int64 value does not fit on int63. *) Conv.int64_fit_on_int63_exn x; Caml.Int64.mul x 2L ;; let wrap x = if Conv.int64_is_representable_as_int63 x then Some (Caml.Int64.mul x 2L) else None ;; let wrap_modulo x = Caml.Int64.mul x 2L let unwrap x = Caml.Int64.shift_right x 1 let unwrap_unsigned x = Caml.Int64.shift_right_logical x 1 (* This does not use wrap or unwrap to avoid generating exceptions in the case of overflows. This is to preserve the semantics of int type on 64 bit architecture. *) let f2 f a b = Caml.Int64.mul (f (Caml.Int64.shift_right a 1) (Caml.Int64.shift_right b 1)) 2L ;; let mask = 0xffff_ffff_ffff_fffeL let m x = Caml.Int64.logand x mask let invariant t = assert (m t = t) let add x y = Caml.Int64.add x y let sub x y = Caml.Int64.sub x y let neg x = Caml.Int64.neg x let abs x = Caml.Int64.abs x let one = wrap_exn 1L let succ a = add a one let pred a = sub a one let min_value = m Caml.Int64.min_int let max_value = m Caml.Int64.max_int let bit_not x = m (Caml.Int64.lognot x) let bit_and = Caml.Int64.logand let bit_xor = Caml.Int64.logxor let bit_or = Caml.Int64.logor let shift_left x i = Caml.Int64.shift_left x i let shift_right x i = m (Caml.Int64.shift_right x i) let shift_right_logical x i = m (Caml.Int64.shift_right_logical x i) let pow = f2 Int_math.Private.int63_pow_on_int64 let mul a b = Caml.Int64.mul a (Caml.Int64.shift_right b 1) let div a b = wrap_modulo (Caml.Int64.div a b) let rem a b = Caml.Int64.rem a b let popcount x = Popcount.int64_popcount x let to_int64 t = unwrap t let of_int64 t = wrap t let of_int64_exn t = wrap_exn t let of_int64_trunc t = wrap_modulo t let t_of_sexp x = wrap_exn (int64_of_sexp x) let sexp_of_t x = sexp_of_int64 (unwrap x) let compare (x : t) y = compare x y let is_pow2 x = Int64.is_pow2 (unwrap x) let clz x = (* We run Int64.clz directly on the wrapped int63 value. This is correct because the bits of the int63_emul are left-aligned in the Int64. *) Int64.clz x ;; let ctz x = Int64.ctz (unwrap x) let floor_pow2 x = Int64.floor_pow2 (unwrap x) |> wrap_exn let ceil_pow2 x = Int64.floor_pow2 (unwrap x) |> wrap_exn let floor_log2 x = Int64.floor_log2 (unwrap x) let ceil_log2 x = Int64.ceil_log2 (unwrap x) end open W module T = struct type t = W.t [@@deriving_inline hash, sexp, sexp_grammar] let (hash_fold_t : Ppx_hash_lib.Std.Hash.state -> t -> Ppx_hash_lib.Std.Hash.state) = W.hash_fold_t and (hash : t -> Ppx_hash_lib.Std.Hash.hash_value) = let func = W.hash in fun x -> func x ;; let t_of_sexp = (W.t_of_sexp : Sexplib0.Sexp.t -> t) let sexp_of_t = (W.sexp_of_t : t -> Sexplib0.Sexp.t) let (t_sexp_grammar : t Sexplib0.Sexp_grammar.t) = W.t_sexp_grammar [@@@end] type comparator_witness = W.comparator_witness let comparator = W.comparator let compare = W.compare let invariant = W.invariant (* We don't expect [hash] to follow the behavior of int in 64bit architecture *) let _ = hash let hash (x : t) = Caml.Hashtbl.hash x let hashable : t Hashable.t = { hash; compare; sexp_of_t } let invalid_str x = Printf.failwithf "Int63.of_string: invalid input %S" x () (* "sign" refers to whether the number starts with a '-' "signedness = false" means the rest of the number is parsed as unsigned and then cast to signed with wrap-around modulo 2^i "signedness = true" means no such craziness happens The terminology and the logic is due to the code in byterun/ints.c in ocaml 4.03 ([parse_sign_and_base] function). Signedness equals true for plain decimal number (e.g. 1235, -6789) Signedness equals false in the following cases: - [0xffff], [-0xffff] (hexadecimal representation) - [0b0101], [-0b0101] (binary representation) - [0o1237], [-0o1237] (octal representation) - [0u9812], [-0u9812] (unsigned decimal representation - available from OCaml 4.03) *) let sign_and_signedness x = let len = String.length x in let open Int_replace_polymorphic_compare in let pos, sign = if 0 < len then ( match x.[0] with | '-' -> 1, `Neg | '+' -> 1, `Pos | _ -> 0, `Pos) else 0, `Pos in if pos + 2 < len then ( let c1 = x.[pos] in let c2 = x.[pos + 1] in match c1, c2 with | '0', '0' .. '9' -> sign, true | '0', _ -> sign, false | _ -> sign, true) else sign, true ;; let to_string x = Caml.Int64.to_string (unwrap x) let of_string str = try let sign, signedness = sign_and_signedness str in if signedness then of_int64_exn (Caml.Int64.of_string str) else ( let pos_str = match sign with | `Neg -> String.sub str ~pos:1 ~len:(String.length str - 1) | `Pos -> str in let int64 = Caml.Int64.of_string pos_str in (* unsigned 63-bit int must parse as a positive signed 64-bit int *) if Int64_replace_polymorphic_compare.( < ) int64 0L then invalid_str str; let int63 = wrap_modulo int64 in match sign with | `Neg -> neg int63 | `Pos -> int63) with | _ -> invalid_str str ;; let bswap16 t = wrap_modulo (Int64.bswap16 (unwrap t)) let bswap32 t = wrap_modulo (Int64.bswap32 (unwrap t)) let bswap48 t = wrap_modulo (Int64.bswap48 (unwrap t)) end include T let num_bits = 63 let float_lower_bound = Float0.lower_bound_for_int num_bits let float_upper_bound = Float0.upper_bound_for_int num_bits let shift_right_logical = shift_right_logical let shift_right = shift_right let shift_left = shift_left let bit_not = bit_not let bit_xor = bit_xor let bit_or = bit_or let bit_and = bit_and let popcount = popcount let abs = abs let pred = pred let succ = succ let pow = pow let rem = rem let neg = neg let max_value = max_value let min_value = min_value let minus_one = wrap_exn Caml.Int64.minus_one let one = wrap_exn Caml.Int64.one let zero = wrap_exn Caml.Int64.zero let is_pow2 = is_pow2 let floor_pow2 = floor_pow2 let ceil_pow2 = ceil_pow2 let floor_log2 = floor_log2 let ceil_log2 = ceil_log2 let clz = clz let ctz = ctz let to_float x = Caml.Int64.to_float (unwrap x) let of_float_unchecked x = wrap_modulo (Caml.Int64.of_float x) let of_float t = let open Float_replace_polymorphic_compare in if t >= float_lower_bound && t <= float_upper_bound then wrap_modulo (Caml.Int64.of_float t) else Printf.invalid_argf "Int63.of_float: argument (%f) is out of range or NaN" (Float0.box t) () ;; let of_int64 = of_int64 let of_int64_exn = of_int64_exn let of_int64_trunc = of_int64_trunc let to_int64 = to_int64 include Comparable.With_zero (struct include T let zero = zero end) let between t ~low ~high = low <= t && t <= high let clamp_unchecked t ~min ~max = if t < min then min else if t <= max then t else max let clamp_exn t ~min ~max = assert (min <= max); clamp_unchecked t ~min ~max ;; let clamp t ~min ~max = if min > max then Or_error.error_s (Sexp.message "clamp requires [min <= max]" [ "min", T.sexp_of_t min; "max", T.sexp_of_t max ]) else Ok (clamp_unchecked t ~min ~max) ;; let ( / ) = div let ( * ) = mul let ( - ) = sub let ( + ) = add let ( ~- ) = neg let ( ** ) b e = pow b e let incr r = r := !r + one let decr r = r := !r - one (* We can reuse conversion function from/to int64 here. *) let of_int x = wrap_exn (Conv.int_to_int64 x) let of_int_exn x = of_int x let to_int x = Conv.int64_to_int (unwrap x) let to_int_exn x = Conv.int64_to_int_exn (unwrap x) let to_int_trunc x = Conv.int64_to_int_trunc (unwrap x) let of_int32 x = wrap_exn (Conv.int32_to_int64 x) let of_int32_exn x = of_int32 x let to_int32 x = Conv.int64_to_int32 (unwrap x) let to_int32_exn x = Conv.int64_to_int32_exn (unwrap x) let to_int32_trunc x = Conv.int64_to_int32_trunc (unwrap x) let of_nativeint x = of_int64 (Conv.nativeint_to_int64 x) let of_nativeint_exn x = wrap_exn (Conv.nativeint_to_int64 x) let of_nativeint_trunc x = of_int64_trunc (Conv.nativeint_to_int64 x) let to_nativeint x = Conv.int64_to_nativeint (unwrap x) let to_nativeint_exn x = Conv.int64_to_nativeint_exn (unwrap x) let to_nativeint_trunc x = Conv.int64_to_nativeint_trunc (unwrap x) include Conv.Make (T) include Conv.Make_hex (struct type t = T.t [@@deriving_inline compare, hash] let compare = (T.compare : t -> t -> int) let (hash_fold_t : Ppx_hash_lib.Std.Hash.state -> t -> Ppx_hash_lib.Std.Hash.state) = T.hash_fold_t and (hash : t -> Ppx_hash_lib.Std.Hash.hash_value) = let func = T.hash in fun x -> func x ;; [@@@end] let zero = zero let neg = ( ~- ) let ( < ) = ( < ) let to_string i = (* the use of [unwrap_unsigned] here is important for the case of [min_value] *) Printf.sprintf "%Lx" (unwrap_unsigned i) ;; let of_string s = of_string ("0x" ^ s) let module_name = "Base.Int63.Hex" end) include Pretty_printer.Register (struct type nonrec t = t let to_string x = to_string x let module_name = "Base.Int63" end) module Pre_O = struct let ( + ) = ( + ) let ( - ) = ( - ) let ( * ) = ( * ) let ( / ) = ( / ) let ( ~- ) = ( ~- ) let ( ** ) = ( ** ) include (Int64_replace_polymorphic_compare : Comparisons.Infix with type t := t) let abs = abs let neg = neg let zero = zero let of_int_exn = of_int_exn end module O = struct include Pre_O include Int_math.Make (struct type nonrec t = t include Pre_O let rem = rem let to_float = to_float let of_float = of_float let of_string = T.of_string let to_string = T.to_string end) let ( land ) = bit_and let ( lor ) = bit_or let ( lxor ) = bit_xor let lnot = bit_not let ( lsl ) = shift_left let ( asr ) = shift_right let ( lsr ) = shift_right_logical end include O (* [Int63] and [Int63.O] agree value-wise *) module Repr = struct type emulated = t type ('underlying_type, 'intermediate_type) t = | Int : (int, int) t | Int64 : (int64, emulated) t end let repr = Repr.Int64 (* Include type-specific [Replace_polymorphic_compare] at the end, after including functor application that could shadow its definitions. This is here so that efficient versions of the comparison functions are exported by this module. *) include Int64_replace_polymorphic_compare
(* A 63bit integer is a 64bit integer with its bits shifted to the left and its lowest bit set to 0. This is the same kind of encoding as OCaml int on 64bit architecture. The only difference being the lowest bit (immediate bit) set to 1. *)
dune
(library (name ppx_js) (public_name js_of_ocaml-ppx.as-lib) (synopsis "Js_of_ocaml ppx") (libraries compiler-libs.common ppxlib) (preprocess (pps ppxlib.metaquot))) (rule (targets ppx_js_internal.ml) (action (copy %{dep:../lib_internal/ppx_js_internal.ml} %{targets})))
evtchn.c
#include "bindings.h" #include "hypercall.h" #include "xen/hvm/params.h" /* * Find first bit set in (word). Undefined if (word) is zero. */ static inline unsigned long ffs(unsigned long word) { return __builtin_ffsl(word) - 1; } #define EVTCHN_PORT_MAX 31 struct evtchn_handler { evtchn_handler_fn_t handler; void *arg; }; static struct evtchn_handler evtchn_handlers[EVTCHN_PORT_MAX + 1]; void evtchn_register_handler(evtchn_port_t port, evtchn_handler_fn_t handler, void *arg) { assert(port <= EVTCHN_PORT_MAX); assert(evtchn_handlers[port].handler == NULL); cpu_intr_disable(); evtchn_handlers[port] = (struct evtchn_handler){ .handler = handler, .arg = arg }; cpu_intr_enable(); } evtchn_port_t evtchn_bind_virq(uint32_t virq) { evtchn_port_t port; int rc = hypercall_evtchn_bind_virq(virq, 0, &port); assert (rc == 0); return port; } void evtchn_mask(evtchn_port_t port) { struct shared_info *s = SHARED_INFO(); atomic_sync_bts(port, &s->evtchn_mask[0]); } void evtchn_unmask(evtchn_port_t port) { struct shared_info *s = SHARED_INFO(); int pending = 0; atomic_sync_btc(port, &s->evtchn_mask[0]); pending = sync_bt(port, &s->evtchn_pending[0]); if (pending) { /* * Slow path: * * If pending is set here, then there was a race, and we lost the * upcall. Mask the port again and force an upcall via a call to * hyperspace. * * This should be sufficient for HVM/PVHv2 based on my understanding of * Linux drivers/xen/events/events_2l.c. */ atomic_sync_bts(port, &s->evtchn_mask[0]); hypercall_evtchn_unmask(port); } } static int evtchn_vector_handler(void *arg __attribute__((unused))) __attribute__((used)); /* * Called in interrupt context. */ static int evtchn_vector_handler(void *arg __attribute__((unused))) { struct shared_info *s = SHARED_INFO(); struct vcpu_info *vi = VCPU0_INFO(); vi->evtchn_upcall_pending = 0; /* * Demux events received from Xen. * * pending_l1 is the "outer" per-VCPU selector (evtchn_pending_sel). * pending_l2 is the "inner" system-wide word (evtchn_pending[l1i]). */ xen_ulong_t pending_l1, pending_l2; atomic_sync_xchg(&vi->evtchn_pending_sel, 0, &pending_l1); while (pending_l1 != 0) { xen_ulong_t l1i = ffs(pending_l1); /* * Masking pending_l2 with ~evtchn_mask[l1i] is necessary to get the * *current* masked events; otherwise races like the following * can occur: * * 1. X is generated, upcall scheduled by Xen. * 2. X is masked. * 3. Upcall is delivered. * 4. X fires despite now being masked. * * Notably, this also applies to events generated during early boot, * before evtchn_init() is called (especially from the console driver). * * Re-loading pending_l2 on each iteration of the inner loop ensures * that we continue processing events if new ones are triggered while * we're in the loop. */ while ((pending_l2 = (s->evtchn_pending[l1i] & ~s->evtchn_mask[l1i])) != 0) { xen_ulong_t l2i = ffs(pending_l2); evtchn_port_t port = (l1i * (sizeof(xen_ulong_t) * 8)) + l2i; if (port <= EVTCHN_PORT_MAX && evtchn_handlers[port].handler) evtchn_handlers[port].handler(port, evtchn_handlers[port].arg); else log(ERROR, "Solo5: unhandled event on port 0x%x\n", port); atomic_sync_btc(l2i, &s->evtchn_pending[l1i]); } pending_l1 &= ~(1UL << l1i); } return 1; } /* * Private ABI to allow override of the event channel vector handler * by Mirage/Xen. May change or go away without warning. * * Note that if you override this handler, then solo5_yield() will no longer * work. */ int solo5__xen_evtchn_vector_handler(void *) __attribute__((alias("evtchn_vector_handler"), weak)); void evtchn_init(void) { struct shared_info *s = SHARED_INFO(); /* * Start with all event channels masked. */ for(unsigned e = 0; e < EVTCHN_2L_NR_CHANNELS; e++) atomic_sync_bts(e, &s->evtchn_mask[0]); /* * Register to receive event channel upcalls from Xen via IPI vector #32 which * corresponds to IRQ 0 as understood by intr.c. */ intr_register_irq(0, solo5__xen_evtchn_vector_handler, NULL); int rc = hypercall_set_evtchn_upcall_vector(0, 32); assert(rc == 0); /* * See init_evtchn() in Xen xen/arch/x86/guest/xen/xen.c. */ rc = hypercall_hvm_set_param(HVM_PARAM_CALLBACK_IRQ, 1); assert(rc == 0); }
/* * Copyright (c) 2015-2020 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. */
cached_digest.ml
open Import module Reduced_stats = struct type t = { mtime : float ; size : int ; perm : Unix.file_perm } let to_dyn { mtime; size; perm } = Dyn.Record [ ("mtime", Float mtime); ("size", Int size); ("perm", Int perm) ] let of_unix_stats (stats : Unix.stats) = { mtime = stats.st_mtime; size = stats.st_size; perm = stats.st_perm } let compare { mtime; size; perm } t = let open Ordering.O in let= () = Float.compare mtime t.mtime in let= () = Int.compare size t.size in Int.compare perm t.perm end type file = { mutable digest : Digest.t ; mutable stats : Reduced_stats.t ; mutable stats_checked : int } type t = { mutable checked_key : int ; mutable max_timestamp : float ; table : file Path.Table.t } let db_file = Path.relative Path.build_dir ".digest-db" let dyn_of_file { digest; stats; stats_checked } = Dyn.Record [ ("digest", Digest.to_dyn digest) ; ("stats", Reduced_stats.to_dyn stats) ; ("stats_checked", Int stats_checked) ] let to_dyn { checked_key; max_timestamp; table } = Dyn.Record [ ("checked_key", Int checked_key) ; ("max_timestamp", Float max_timestamp) ; ("table", Path.Table.to_dyn dyn_of_file table) ] module P = Persistent.Make (struct type nonrec t = t let name = "DIGEST-DB" let version = 5 let to_dyn = to_dyn end) let needs_dumping = ref false (* CR-someday amokhov: replace this mutable table with a memoized function. This will probably require splitting this module in two, for dealing with source and target files, respectively. For source files, we receive updates via the file-watching API. For target files, we modify the digests ourselves, without subscribing for file-watching updates. *) let cache = lazy (match P.load db_file with | None -> { checked_key = 0; table = Path.Table.create 1024; max_timestamp = 0. } | Some cache -> cache.checked_key <- cache.checked_key + 1; cache) let get_current_filesystem_time () = let special_path = Path.relative Path.build_dir ".filesystem-clock" in Io.write_file special_path "<dummy>"; (Path.Untracked.stat_exn special_path).st_mtime let wait_for_fs_clock_to_advance () = let t = get_current_filesystem_time () in while get_current_filesystem_time () <= t do (* This is a blocking wait but we don't care too much. This code is only used in the test suite. *) Unix.sleepf 0.01 done let delete_very_recent_entries () = let cache = Lazy.force cache in if !Clflags.wait_for_filesystem_clock then wait_for_fs_clock_to_advance (); let now = get_current_filesystem_time () in match Float.compare cache.max_timestamp now with | Lt -> () | Eq | Gt -> Path.Table.filteri_inplace cache.table ~f:(fun ~key:path ~data -> match Float.compare data.stats.mtime now with | Lt -> true | Gt | Eq -> if !Clflags.debug_digests then Console.print [ Pp.textf "Dropping cached digest for %s because it has exactly the \ same mtime as the file system clock." (Path.to_string_maybe_quoted path) ]; false) let dump () = if !needs_dumping && Path.build_dir_exists () then ( needs_dumping := false; Console.Status_line.with_overlay (Live (fun () -> Pp.hbox (Pp.text "Saving digest db..."))) ~f:(fun () -> delete_very_recent_entries (); P.dump db_file (Lazy.force cache))) let () = at_exit dump let invalidate_cached_timestamps () = (if Lazy.is_val cache then let cache = Lazy.force cache in cache.checked_key <- cache.checked_key + 1); delete_very_recent_entries () let set_max_timestamp cache (stat : Unix.stats) = cache.max_timestamp <- Float.max cache.max_timestamp stat.st_mtime let set_with_stat path digest stat = let cache = Lazy.force cache in needs_dumping := true; set_max_timestamp cache stat; Path.Table.set cache.table path { digest ; stats = Reduced_stats.of_unix_stats stat ; stats_checked = cache.checked_key } let set path digest = (* the caller of [set] ensures that the files exist *) let path = Path.build path in let stat = Path.Untracked.stat_exn path in set_with_stat path digest stat module Digest_result = struct type t = | Ok of Digest.t | No_such_file | Broken_symlink | Cyclic_symlink | Unexpected_kind of File_kind.t | Unix_error of Unix_error.Detailed.t | Error of exn let equal x y = match (x, y) with | Ok x, Ok y -> Digest.equal x y | Ok _, _ | _, Ok _ -> false | No_such_file, No_such_file -> true | No_such_file, _ | _, No_such_file -> false | Broken_symlink, Broken_symlink -> true | Broken_symlink, _ | _, Broken_symlink -> false | Cyclic_symlink, Cyclic_symlink -> true | Cyclic_symlink, _ | _, Cyclic_symlink -> false | Unexpected_kind x, Unexpected_kind y -> File_kind.equal x y | Unexpected_kind _, _ | _, Unexpected_kind _ -> false | Unix_error x, Unix_error y -> Tuple.T3.equal Unix_error.equal String.equal String.equal x y | Unix_error _, _ | _, Unix_error _ -> false | Error x, Error y -> (* Falling back to polymorphic equality check seems OK for this rare case. We could also just return [false] but that would break the reflexivity of the equality check, which doesn't seem nice. *) x = y let to_option = function | Ok t -> Some t | No_such_file | Broken_symlink | Cyclic_symlink | Unexpected_kind _ | Unix_error _ | Error _ -> None let iter t ~f = Option.iter (to_option t) ~f let to_dyn = function | Ok digest -> Dyn.Variant ("Ok", [ Digest.to_dyn digest ]) | No_such_file -> Variant ("No_such_file", []) | Broken_symlink -> Variant ("Broken_symlink", []) | Cyclic_symlink -> Variant ("Cyclic_symlink", []) | Unexpected_kind kind -> Variant ("Unexpected_kind", [ File_kind.to_dyn kind ]) | Unix_error error -> Variant ("Unix_error", [ Unix_error.Detailed.to_dyn error ]) | Error exn -> Variant ("Error", [ String (Printexc.to_string exn) ]) end let digest_path_with_stats ~allow_dirs path stats = match Digest.path_with_stats ~allow_dirs path (Digest.Stats_for_digest.of_unix_stats stats) with | Ok digest -> Digest_result.Ok digest | Unexpected_kind -> Unexpected_kind stats.st_kind | Unix_error (ENOENT, _, _) -> No_such_file | Unix_error other_error -> Unix_error other_error let refresh ~allow_dirs stats path = (* Note that by the time we reach this point, [stats] may become stale due to concurrent processes modifying the [path], so this function can actually return [No_such_file] even if the caller managed to obtain the [stats]. *) let result = digest_path_with_stats ~allow_dirs path stats in Digest_result.iter result ~f:(fun digest -> set_with_stat path digest stats); result let catch_fs_errors f = match f () with | result -> result | exception Unix.Unix_error (error, syscall, arg) -> Digest_result.Unix_error (error, syscall, arg) | exception exn -> Error exn (* Here we make only one [stat] call on the happy path. *) let refresh_without_removing_write_permissions ~allow_dirs path = catch_fs_errors (fun () -> match Path.Untracked.stat_exn path with | stats -> refresh stats ~allow_dirs path | exception Unix.Unix_error (ELOOP, _, _) -> Cyclic_symlink | exception Unix.Unix_error (ENOENT, _, _) -> ( (* Test if this is a broken symlink for better error messages. *) match Path.Untracked.lstat_exn path with | exception Unix.Unix_error (ENOENT, _, _) -> No_such_file | _stats_so_must_be_a_symlink -> Broken_symlink)) (* CR-someday amokhov: We do [lstat] followed by [stat] only because we do not want to remove write permissions from the symbolic link's target, which may be outside of the build directory and not under out control. It seems like it should be possible to avoid paying for two system calls ([lstat] and [stat]) here, e.g., by telling the subsequent [chmod] to not follow symlinks. *) let refresh_and_remove_write_permissions ~allow_dirs path = catch_fs_errors (fun () -> match Path.Untracked.lstat_exn path with | exception Unix.Unix_error (ENOENT, _, _) -> No_such_file | stats -> ( match stats.st_kind with | S_LNK -> ( match Path.Untracked.stat_exn path with | stats -> refresh stats ~allow_dirs:false path | exception Unix.Unix_error (ELOOP, _, _) -> Cyclic_symlink | exception Unix.Unix_error (ENOENT, _, _) -> Broken_symlink) | S_REG -> let perm = Path.Permissions.remove Path.Permissions.write stats.st_perm in Path.chmod ~mode:perm path; (* we know it's a file, so we don't allow directories for safety *) refresh ~allow_dirs:false { stats with st_perm = perm } path | _ -> (* CR-someday amokhov: Shall we proceed if [stats.st_kind = S_DIR]? What about stranger kinds like [S_SOCK]? *) refresh ~allow_dirs stats path)) let refresh ~allow_dirs ~remove_write_permissions path = let path = Path.build path in match remove_write_permissions with | false -> refresh_without_removing_write_permissions ~allow_dirs path | true -> refresh_and_remove_write_permissions ~allow_dirs path let peek_file ~allow_dirs path = let cache = Lazy.force cache in match Path.Table.find cache.table path with | None -> None | Some x -> Some (if x.stats_checked = cache.checked_key then Digest_result.Ok x.digest else (* The [stat_exn] below follows symlinks. *) match Path.Untracked.stat_exn path with | exception Unix.Unix_error (ELOOP, _, _) -> Cyclic_symlink | exception Unix.Unix_error (ENOENT, _, _) -> No_such_file | exception Unix.Unix_error (error, syscall, arg) -> Unix_error (Unix_error.Detailed.create ~syscall ~arg error) | exception exn -> Error exn | stats -> ( let reduced_stats = Reduced_stats.of_unix_stats stats in match Reduced_stats.compare x.stats reduced_stats with | Eq -> (* Even though we're modifying the [stats_checked] field, we don't need to set [needs_dumping := true] here. This is because [checked_key] is incremented every time we load from disk, which makes it so that [stats_checked < checked_key] for all entries after loading, regardless of whether we save the new value here or not. *) x.stats_checked <- cache.checked_key; Ok x.digest | Gt | Lt -> let digest_result = digest_path_with_stats ~allow_dirs path stats in Digest_result.iter digest_result ~f:(fun digest -> if !Clflags.debug_digests then Console.print [ Pp.textf "Re-digested file %s because its stats changed:" (Path.to_string_maybe_quoted path) ; Dyn.pp (Dyn.Record [ ("old_digest", Digest.to_dyn x.digest) ; ("new_digest", Digest.to_dyn digest) ; ("old_stats", Reduced_stats.to_dyn x.stats) ; ("new_stats", Reduced_stats.to_dyn reduced_stats) ]) ]; needs_dumping := true; set_max_timestamp cache stats; x.digest <- digest; x.stats <- reduced_stats; x.stats_checked <- cache.checked_key); digest_result)) let peek_or_refresh_file ~allow_dirs path = match peek_file ~allow_dirs path with | Some digest_result -> digest_result | None -> refresh_without_removing_write_permissions ~allow_dirs path let build_file ~allow_dirs path = peek_or_refresh_file ~allow_dirs (Path.build path) let remove path = let path = Path.build path in let cache = Lazy.force cache in needs_dumping := true; Path.Table.remove cache.table path module Untracked = struct let source_or_external_file = peek_or_refresh_file ~allow_dirs:false let invalidate_cached_timestamp path = let cache = Lazy.force cache in match Path.Table.find cache.table path with | None -> () | Some entry -> (* Make [stats_checked] unequal to [cache.checked_key] so that [peek_file] is forced to re-[stat] the [path]. *) let entry = { entry with stats_checked = cache.checked_key - 1 } in Path.Table.set cache.table path entry end
Hacl_HKDF_Blake2b_256.h
#ifndef __Hacl_HKDF_Blake2b_256_H #define __Hacl_HKDF_Blake2b_256_H #if defined(__cplusplus) extern "C" { #endif #include <string.h> #include "krml/internal/types.h" #include "krml/lowstar_endianness.h" #include "krml/internal/target.h" #include "Hacl_HMAC_Blake2b_256.h" /** Expand pseudorandom key to desired length. @param okm Pointer to `len` bytes of memory where output keying material is written to. @param prk Pointer to at least `HashLen` bytes of memory where pseudorandom key is read from. Usually, this points to the output from the extract step. @param prklen Length of pseudorandom key. @param info Pointer to `infolen` bytes of memory where context and application specific information is read from. Can be a zero-length string. @param infolen Length of context and application specific information. @param len Length of output keying material. */ void Hacl_HKDF_Blake2b_256_expand_blake2b_256( uint8_t *okm, uint8_t *prk, uint32_t prklen, uint8_t *info, uint32_t infolen, uint32_t len ); /** Extract a fixed-length pseudorandom key from input keying material. @param prk Pointer to `HashLen` bytes of memory where pseudorandom key is written to. @param salt Pointer to `saltlen` bytes of memory where salt value is read from. @param saltlen Length of salt value. @param ikm Pointer to `ikmlen` bytes of memory where input keying material is read from. @param ikmlen Length of input keying material. */ void Hacl_HKDF_Blake2b_256_extract_blake2b_256( uint8_t *prk, uint8_t *salt, uint32_t saltlen, uint8_t *ikm, uint32_t ikmlen ); #if defined(__cplusplus) } #endif #define __Hacl_HKDF_Blake2b_256_H_DEFINED #endif
/* MIT License * * Copyright (c) 2016-2022 INRIA, CMU and Microsoft Corporation * Copyright (c) 2022-2023 HACL* Contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */
dune
(executable (name main) (package git-unix) (public_name ogit-http-ls) (libraries digestif.c checkseum.c git-unix cohttp-lwt-unix cmdliner mtime mtime.clock.os fmt.cli fmt.tty logs.cli logs.fmt))
services_registration.ml
open Alpha_context type rpc_context = { block_hash: Block_hash.t ; block_header: Block_header.shell_header ; context: Alpha_context.t ; } let rpc_init ({ block_hash ; block_header ; context } : Updater.rpc_context) = let level = block_header.level in let timestamp = block_header.timestamp in let fitness = block_header.fitness in Alpha_context.prepare ~level ~timestamp ~fitness context >>=? fun context -> return { block_hash ; block_header ; context } let rpc_services = ref (RPC_directory.empty : Updater.rpc_context RPC_directory.t) let register0_fullctxt s f = rpc_services := RPC_directory.register !rpc_services s (fun ctxt q i -> rpc_init ctxt >>=? fun ctxt -> f ctxt q i) let opt_register0_fullctxt s f = rpc_services := RPC_directory.opt_register !rpc_services s (fun ctxt q i -> rpc_init ctxt >>=? fun ctxt -> f ctxt q i) let register0 s f = register0_fullctxt s (fun { context ; _ } -> f context) let register0_noctxt s f = rpc_services := RPC_directory.register !rpc_services s (fun _ q i -> f q i) let register1_fullctxt s f = rpc_services := RPC_directory.register !rpc_services s (fun (ctxt, arg) q i -> rpc_init ctxt >>=? fun ctxt -> f ctxt arg q i) let register1 s f = register1_fullctxt s (fun { context ; _ } x -> f context x) let register1_noctxt s f = rpc_services := RPC_directory.register !rpc_services s (fun (_, arg) q i -> f arg q i) let register2_fullctxt s f = rpc_services := RPC_directory.register !rpc_services s (fun ((ctxt, arg1), arg2) q i -> rpc_init ctxt >>=? fun ctxt -> f ctxt arg1 arg2 q i) let register2 s f = register2_fullctxt s (fun { context ; _ } a1 a2 q i -> f context a1 a2 q i) let get_rpc_services () = let p = RPC_directory.map (fun c -> rpc_init c >>= function | Error _ -> assert false | Ok c -> Lwt.return c.context) (Storage_description.build_directory Alpha_context.description) in RPC_directory.register_dynamic_directory !rpc_services RPC_path.(open_root / "context" / "raw" / "json") (fun _ -> Lwt.return p)
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
main.ml
(* The lexer generator. Command-line parsing. *) open Syntax let ml_automata = ref false let source_name = ref None let output_name = ref None let usage = "usage: ocamllex [options] sourcefile" let print_version_string () = print_string "The OCaml lexer generator, version "; print_string Sys.ocaml_version ; print_newline(); exit 0 let print_version_num () = print_endline Sys.ocaml_version; exit 0; ;; let specs = ["-ml", Arg.Set ml_automata, " Output code that does not use the Lexing module built-in automata \ interpreter"; "-o", Arg.String (fun x -> output_name := Some x), " <file> Set output file name to <file>"; "-q", Arg.Set Common.quiet_mode, " Do not display informational messages"; "-v", Arg.Unit print_version_string, " Print version and exit"; "-version", Arg.Unit print_version_string, " Print version and exit"; "-vnum", Arg.Unit print_version_num, " Print version number and exit"; ] let _ = Arg.parse specs (fun name -> source_name := Some name) usage let main () = let source_name = match !source_name with | None -> Arg.usage specs usage ; exit 2 | Some name -> name in let dest_name = match !output_name with | Some name -> name | None -> if Filename.check_suffix source_name ".mll" then Filename.chop_suffix source_name ".mll" ^ ".ml" else source_name ^ ".ml" in let ic = open_in_bin source_name in let oc = open_out dest_name in let tr = Common.open_tracker dest_name oc in let lexbuf = Lexing.from_channel ic in lexbuf.Lexing.lex_curr_p <- {Lexing.pos_fname = source_name; Lexing.pos_lnum = 1; Lexing.pos_bol = 0; Lexing.pos_cnum = 0}; try let def = Parser.lexer_definition Lexer.main lexbuf in let (entries, transitions) = Lexgen.make_dfa def.entrypoints in if !ml_automata then begin Outputbis.output_lexdef ic oc tr def.header def.refill_handler entries transitions def.trailer end else begin let tables = Compact.compact_tables transitions in Output.output_lexdef ic oc tr def.header def.refill_handler tables entries def.trailer end; close_in ic; close_out oc; Common.close_tracker tr; with exn -> let bt = Printexc.get_raw_backtrace () in close_in ic; close_out oc; Common.close_tracker tr; Sys.remove dest_name; begin match exn with | Cset.Bad -> let p = Lexing.lexeme_start_p lexbuf in Printf.fprintf stderr "File \"%s\", line %d, character %d: character set expected.\n" p.Lexing.pos_fname p.Lexing.pos_lnum (p.Lexing.pos_cnum - p.Lexing.pos_bol) | Parsing.Parse_error -> let p = Lexing.lexeme_start_p lexbuf in Printf.fprintf stderr "File \"%s\", line %d, character %d: syntax error.\n" p.Lexing.pos_fname p.Lexing.pos_lnum (p.Lexing.pos_cnum - p.Lexing.pos_bol) | Lexer.Lexical_error(msg, file, line, col) -> Printf.fprintf stderr "File \"%s\", line %d, character %d: %s.\n" file line col msg | Lexgen.Memory_overflow -> Printf.fprintf stderr "File \"%s\":\n Position memory overflow, too many bindings\n" source_name | Output.Table_overflow -> Printf.fprintf stderr "File \"%s\":\ntransition table overflow, automaton is too big\n" source_name | _ -> Printexc.raise_with_backtrace exn bt end; exit 3 let _ = (* Printexc.catch *) main (); exit 0
(**************************************************************************) (* *) (* OCaml *) (* *) (* Xavier Leroy, projet Cristal, INRIA Rocquencourt *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************)
omake_value_print.ml
(************************************************************************ * Simple printing. *) (* let pp_print_string_list buf sl = *) (* List.iter (fun s -> Format.fprintf buf "@ %s" s) sl *) (* let pp_print_node_list buf l = *) (* List.iter (fun s -> Format.fprintf buf "@ %a" Omake_node.pp_print_node s) l *) (* let pp_print_node_set buf set = *) (* Omake_node.NodeSet.iter (fun s -> Format.fprintf buf "@ %a" Omake_node.pp_print_node s) set *) let pp_print_wild_list buf wl = List.iter (fun w -> Format.fprintf buf "@ %a" Lm_wild.pp_print_wild_in w) wl let pp_print_source buf (_, source) = match source with | Omake_value_type.SourceWild wild -> Lm_wild.pp_print_wild_out buf wild | SourceNode node -> Omake_node.pp_print_node buf node let pp_print_source_list buf sources = List.iter (fun source -> Format.fprintf buf "@ %a" pp_print_source source) sources let pp_print_target buf target = match target with | Omake_value_type.TargetNode node -> Omake_node.pp_print_node buf node | TargetString s -> Lm_printf.pp_print_string buf s (* let pp_print_required buf b = *) (* if b then *) (* Lm_printf.pp_print_char buf '~' *) (* else *) (* Lm_printf.pp_print_char buf '?' *) (************************************************************************ * Path printing. *) let rec pp_print_path buf = function | Omake_value_type.PathVar info -> Omake_ir_print.pp_print_var_info buf info | PathField (path, _obj, v) -> Format.fprintf buf "%a.%a" Lm_symbol.pp_print_symbol v pp_print_path path (************************************************************************ * Arity approximation. *) (* * XXX: TODO: currently keyword args are ignored, we should probably include * them, and also return an ArityRange when some keyword arguments have a default * value defined. See also Bugzilla bug 731. *) let fun_arity _keywords params = Omake_ir.ArityExact (List.length params) let curry_fun_arity curry_args _keywords params _curry_kargs = Omake_ir.ArityExact ((List.length params) - (List.length curry_args)) (************************************************************************ * Value printing. *) let rec pp_print_value buf v = match v with Omake_value_type.ValNone -> Lm_printf.pp_print_string buf "<none>" | ValInt i -> Format.fprintf buf "%d : Int" i | ValFloat x -> Format.fprintf buf "%g : Float" x | ValData s -> Format.fprintf buf "@[<v 3><data \"%s\"> : String@]" (String.escaped s) | ValQuote vl -> Format.fprintf buf "@[<v 3><string%a>@ : String@]" pp_print_value_list vl | ValWhite s -> Format.fprintf buf "'%s' : White" (String.escaped s) | ValString s -> Format.fprintf buf "\"%s\" : Sequence" (String.escaped s) | ValQuoteString (c, vl) -> Format.fprintf buf "@[<v 3><string %c%a%c>@ : String@]" c pp_print_value_list vl c | ValSequence [v] -> pp_print_value buf v | ValSequence vl -> Format.fprintf buf "@[<hv 3><sequence%a>@ : Sequence@]" pp_print_value_list vl | ValArray vl -> Format.fprintf buf "@[<v 3><array%a>@ : Array@]" pp_print_value_list vl | ValMaybeApply (_, v) -> Format.fprintf buf "@[<hv 3>ifdefined(%a)@]" (**) Omake_ir_print.pp_print_var_info v | ValFun (_, keywords, params, _, _) -> Format.fprintf buf "<fun %a>" Omake_ir_print.pp_print_arity (fun_arity keywords params) | ValFunCurry (_, curry_args, keywords, params, _, _, curry_kargs) -> Format.fprintf buf "<curry %a>" Omake_ir_print.pp_print_arity (curry_fun_arity curry_args keywords params curry_kargs) | ValPrim (_, special, _, name) | ValPrimCurry (_, special, name, _, _) -> if special then Format.fprintf buf "<special-function %a>" Lm_symbol.pp_print_symbol name else Format.fprintf buf "<prim-function %a>" Lm_symbol.pp_print_symbol name | ValRules rules -> Format.fprintf buf "<@[<hv 3>rules:"; List.iter (fun erule -> Format.fprintf buf "@ %a" Omake_node.pp_print_node erule) rules; Format.fprintf buf "@]>" | ValDir dir -> Format.fprintf buf "%a : Dir" Omake_node.pp_print_dir dir | ValNode node -> Format.fprintf buf "%a : File" Omake_node.pp_print_node node | ValStringExp (_, e) -> Format.fprintf buf "@[<hv 0>%a : Exp@]" Omake_ir_print.pp_print_string_exp e | ValBody (_, [], [], el, export) -> Format.fprintf buf "@[<v 0>%a%a@ : Body@]" Omake_ir_print.pp_print_exp_list el Omake_ir_print.pp_print_export_info export | ValBody (_, keywords, params, el, export) -> Format.fprintf buf "@[<v 0>%a => %a%a@ : Body@]" Omake_ir_print.pp_print_arity (fun_arity keywords params) Omake_ir_print.pp_print_exp_list el Omake_ir_print.pp_print_export_info export | ValObject env -> pp_print_env buf env | ValMap map -> Format.fprintf buf "@[<hv 3>map"; Omake_value_util.ValueTable.iter (fun v e -> Format.fprintf buf "@ %a@ = %a" pp_print_value v pp_print_value e) map; Format.fprintf buf "@]" | ValChannel (InChannel, _) -> Format.fprintf buf "<channel> : InChannel" | ValChannel (OutChannel, _) -> Format.fprintf buf "<channel> : OutChannel" | ValChannel (InOutChannel, _) -> Format.fprintf buf "<channel> : InOutChannel" | ValClass c -> Format.fprintf buf "@[<hv 3>class"; Lm_symbol.SymbolTable.iter (fun v _ -> Format.fprintf buf "@ %a" Lm_symbol.pp_print_symbol v) c; Format.fprintf buf "@]" | ValCases cases -> Format.fprintf buf "@[<hv 3>cases"; List.iter (fun (v, e1, e2, export) -> Format.fprintf buf "@[<hv 3>%a %a:@ %a%a@]" (**) Lm_symbol.pp_print_symbol v pp_print_value e1 Omake_ir_print.pp_print_exp_list e2 Omake_ir_print.pp_print_export_info export) cases; Format.fprintf buf "@]" | ValVar (_, v) -> Format.fprintf buf "`%a" Omake_ir_print.pp_print_var_info v | ValOther (ValLexer _) -> Format.fprintf buf "<lexer> : Lexer" | ValOther (ValParser _) -> Format.fprintf buf "<parser> : Parser" | ValOther (ValLocation loc) -> Format.fprintf buf "<location %a> : Location" Lm_location.pp_print_location loc | ValOther (ValExitCode code) -> Format.fprintf buf "<exit-code %d> : Int" code | ValOther (ValEnv _) -> Format.fprintf buf "<env>" | ValDelayed { contents = ValValue v } -> Format.fprintf buf "<delayed:value %a>" pp_print_value v | ValDelayed { contents = ValStaticApply (key, v) } -> Format.fprintf buf "<delayed:memo %a::%a>" pp_print_value key Lm_symbol.pp_print_symbol v and pp_print_value_list buf vl = List.iter (fun v -> Format.fprintf buf "@ %a" pp_print_value v) vl (* and pp_print_normal_args buf first args = *) (* match args with *) (* arg :: args -> *) (* if not first then *) (* Format.fprintf buf ",@ "; *) (* pp_print_value buf arg; *) (* pp_print_normal_args buf false args *) (* | [] -> *) (* first *) (* and pp_print_keyword_args buf first kargs = *) (* match kargs with *) (* (v, arg) :: kargs -> *) (* if not first then *) (* Format.fprintf buf ",@ "; *) (* Format.fprintf buf "@[<hv 3>%a =@ %a@]" Lm_symbol.pp_print_symbol v pp_print_value arg; *) (* pp_print_keyword_args buf false kargs *) (* | [] -> *) (* () *) (* and pp_print_value_args buf (args, kargs) = *) (* pp_print_keyword_args buf (pp_print_normal_args buf true args) kargs *) and pp_print_env buf env = let tags = Omake_value_util.venv_get_class env in let env = Lm_symbol.SymbolTable.remove env Omake_value_util.class_sym in Format.fprintf buf "@[<v 3>@[<hv 3>class"; Lm_symbol.SymbolTable.iter (fun v _ -> Format.fprintf buf "@ %a" Lm_symbol.pp_print_symbol v) tags; Format.fprintf buf "@]"; Lm_symbol.SymbolTable.iter (fun v e -> Format.fprintf buf "@ %a = %a" Lm_symbol.pp_print_symbol v pp_print_value e) env; Format.fprintf buf "@]" (************************************************************************ * Simplified printing. *) let rec pp_print_simple_value buf v = match v with Omake_value_type.ValNone -> Lm_printf.pp_print_string buf "<none>" | ValInt i -> Lm_printf.pp_print_int buf i | ValFloat x -> Lm_printf.pp_print_float buf x | ValData s -> Omake_command_type.pp_print_arg buf [ArgData s] | ValWhite s | ValString s -> Omake_command_type.pp_print_arg buf [ArgString s] | ValQuote vl -> Format.fprintf buf "\"%a\"" pp_print_simple_value_list vl | ValQuoteString (c, vl) -> Format.fprintf buf "%c%a%c" c pp_print_simple_value_list vl c | ValSequence vl -> pp_print_simple_value_list buf vl | ValArray vl -> pp_print_simple_arg_list buf vl | ValMaybeApply (_, v) -> Format.fprintf buf "$?(%a)" (**) Omake_ir_print.pp_print_var_info v | ValFun _ -> Lm_printf.pp_print_string buf "<fun>" | ValFunCurry _ -> Lm_printf.pp_print_string buf "<curry>" | ValPrim _ | ValPrimCurry _ -> Lm_printf.pp_print_string buf "<prim>" | ValRules _ -> Lm_printf.pp_print_string buf "<rules>" | ValDir dir -> Omake_node.pp_print_dir buf dir | ValNode node -> Omake_node.pp_print_node buf node | ValStringExp _ -> Lm_printf.pp_print_string buf "<exp>" | ValBody _ -> Lm_printf.pp_print_string buf "<body>" | ValObject _ -> Lm_printf.pp_print_string buf "<object>" | ValMap _ -> Lm_printf.pp_print_string buf "<map>" | ValChannel _ -> Lm_printf.pp_print_string buf "<channel>" | ValClass _ -> Lm_printf.pp_print_string buf "<class>" | ValCases _ -> Lm_printf.pp_print_string buf "<cases>" | ValVar (_, v) -> Format.fprintf buf "`%a" Omake_ir_print.pp_print_var_info v | ValOther (ValLexer _) -> Lm_printf.pp_print_string buf "<lexer>" | ValOther (ValParser _) -> Lm_printf.pp_print_string buf "<parser>" | ValOther (ValLocation _) -> Lm_printf.pp_print_string buf "<location>" | ValOther (ValExitCode i) -> Lm_printf.pp_print_int buf i | ValOther (ValEnv _) -> Lm_printf.pp_print_string buf "<env>" | ValDelayed { contents = ValValue v } -> pp_print_simple_value buf v | ValDelayed { contents = ValStaticApply _ } -> Lm_printf.pp_print_string buf "<static>" and pp_print_simple_value_list buf vl = List.iter (pp_print_simple_value buf) vl and pp_print_simple_arg_list buf vl = match vl with | [] -> () | [v] -> pp_print_simple_value buf v | v :: vl -> pp_print_simple_value buf v; Lm_printf.pp_print_char buf ' '; pp_print_simple_arg_list buf vl let rec pp_print_item buf (x : Omake_value_type.item ) = match x with | AstExp e -> Omake_ast_print.pp_print_exp buf e | IrExp e -> Omake_ir_print.pp_print_exp buf e | Location _ -> () | Symbol v -> Lm_symbol.pp_print_symbol buf v | String s -> Lm_printf.pp_print_string buf s | Value v -> pp_print_value buf v | Error e -> pp_print_exn buf e and pp_print_exn buf (x : Omake_value_type.omake_error )= match x with | SyntaxError s -> Format.fprintf buf "syntax error: %s" s | StringAstError (s, e) -> Format.fprintf buf "@[<hv 3>%s:@ %a@]" s Omake_ast_print.pp_print_simple_exp e | StringError s -> Lm_printf.pp_print_string buf s | StringIntError (s, i) -> Format.fprintf buf "%s: %d" s i | StringStringError (s1, s2) -> Format.fprintf buf "%s: %s" s1 s2 | StringVarError (s, v) -> Format.fprintf buf "%s: %a" s Lm_symbol.pp_print_symbol v | StringMethodError (s, v) -> Format.fprintf buf "%s: %a" s Lm_symbol.pp_print_method_name v | StringDirError (s, n)-> Format.fprintf buf "%s: %a" s Omake_node.pp_print_dir n | StringNodeError (s, n)-> Format.fprintf buf "%s: %a" s Omake_node.pp_print_node n | StringValueError (s, v) -> Format.fprintf buf "@[<hv 3>%s:@ %a@]" s pp_print_value v | StringTargetError (s, t) -> Format.fprintf buf "%s: %a" s pp_print_target t | LazyError printer -> printer buf | UnboundVar v -> Format.fprintf buf "unbound variable: %a" Lm_symbol.pp_print_symbol v | UnboundVarInfo v -> Format.fprintf buf "unbound variable: %a" Omake_ir_print.pp_print_var_info v | UnboundKey v -> Format.fprintf buf "unbound key: %s" v | UnboundValue v -> Format.fprintf buf "unbound value: %a" pp_print_value v | UnboundFun v -> Format.fprintf buf "unbound function: %a" Lm_symbol.pp_print_symbol v | UnboundMethod vl -> Format.fprintf buf "unbound method: %a" Lm_symbol.pp_print_method_name vl | UnboundFieldVar (obj, v) -> Format.fprintf buf "@[<v 3>unbound method '%a', object classes:@ @[<b 3>" Lm_symbol.pp_print_symbol v; Lm_symbol.SymbolTable.iter (fun v _ -> Format.fprintf buf "@ %a" Lm_symbol.pp_print_symbol v) (Omake_value_util.venv_get_class obj); Format.fprintf buf "@]@]" | ArityMismatch (len1, len2) -> Format.fprintf buf "arity mismatch: expected %a args, got %d" Omake_ir_print.pp_print_arity len1 len2 | NotImplemented s -> Format.fprintf buf "not implemented: %s" s | NullCommand -> Lm_printf.pp_print_string buf "invalid null command"
import.ml
include Irmin.Export_for_backends let src = Logs.Src.create "irmin.pack" ~doc:"irmin-pack backend" module Log = (val Logs.src_log src : Logs.LOG) module Int63 = struct include Optint.Int63 let t = Irmin.Type.int63 end type int63 = Int63.t [@@deriving irmin] let ( ++ ) = Int63.add let ( -- ) = Int63.sub
(* * Copyright (c)2018-2021 Tarides <contact@tarides.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
TensorRandom.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2016 Benoit Steiner <benoit.steiner.goog@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_CXX11_TENSOR_TENSOR_RANDOM_H #define EIGEN_CXX11_TENSOR_TENSOR_RANDOM_H namespace Eigen { namespace internal { namespace { EIGEN_DEVICE_FUNC uint64_t get_random_seed() { #ifdef __CUDA_ARCH__ // We don't support 3d kernels since we currently only use 1 and // 2d kernels. assert(threadIdx.z == 0); return clock64() + blockIdx.x * blockDim.x + threadIdx.x + gridDim.x * blockDim.x * (blockIdx.y * blockDim.y + threadIdx.y); #elif defined _WIN32 // Use the current time as a baseline. SYSTEMTIME st; GetSystemTime(&st); int time = st.wSecond + 1000 * st.wMilliseconds; // Mix in a random number to make sure that we get different seeds if // we try to generate seeds faster than the clock resolution. // We need 2 random values since the generator only generate 16 bits at // a time (https://msdn.microsoft.com/en-us/library/398ax69y.aspx) int rnd1 = ::rand(); int rnd2 = ::rand(); uint64_t rnd = (rnd1 | rnd2 << 16) ^ time; return rnd; #elif defined __APPLE__ // Same approach as for win32, except that the random number generator // is better (// https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/random.3.html#//apple_ref/doc/man/3/random). uint64_t rnd = ::random() ^ mach_absolute_time(); return rnd; #else // Augment the current time with pseudo random number generation // to ensure that we get different seeds if we try to generate seeds // faster than the clock resolution. timespec ts; clock_gettime(CLOCK_REALTIME, &ts); uint64_t rnd = ::random() ^ ts.tv_nsec; return rnd; #endif } static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE unsigned PCG_XSH_RS_generator(uint64_t* state) { // TODO: Unify with the implementation in the non blocking thread pool. uint64_t current = *state; // Update the internal state *state = current * 6364136223846793005ULL + 0xda3e39cb94b95bdbULL; // Generate the random output (using the PCG-XSH-RS scheme) return static_cast<unsigned>((current ^ (current >> 22)) >> (22 + (current >> 61))); } static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE uint64_t PCG_XSH_RS_state(uint64_t seed) { seed = seed ? seed : get_random_seed(); return seed * 6364136223846793005ULL + 0xda3e39cb94b95bdbULL; } } // namespace template <typename T> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T RandomToTypeUniform(uint64_t* state) { unsigned rnd = PCG_XSH_RS_generator(state); return static_cast<T>(rnd); } template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Eigen::half RandomToTypeUniform<Eigen::half>(uint64_t* state) { Eigen::half result; // Generate 10 random bits for the mantissa unsigned rnd = PCG_XSH_RS_generator(state); result.x = static_cast<uint16_t>(rnd & 0x3ffu); // Set the exponent result.x |= (static_cast<uint16_t>(15) << 10); // Return the final result return result - Eigen::half(1.0f); } template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float RandomToTypeUniform<float>(uint64_t* state) { typedef union { uint32_t raw; float fp; } internal; internal result; // Generate 23 random bits for the mantissa mantissa const unsigned rnd = PCG_XSH_RS_generator(state); result.raw = rnd & 0x7fffffu; // Set the exponent result.raw |= (static_cast<uint32_t>(127) << 23); // Return the final result return result.fp - 1.0f; } template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double RandomToTypeUniform<double>(uint64_t* state) { typedef union { uint64_t raw; double dp; } internal; internal result; result.raw = 0; // Generate 52 random bits for the mantissa // First generate the upper 20 bits unsigned rnd1 = PCG_XSH_RS_generator(state) & 0xfffffu; // The generate the lower 32 bits unsigned rnd2 = PCG_XSH_RS_generator(state); result.raw = (static_cast<uint64_t>(rnd1) << 32) | rnd2; // Set the exponent result.raw |= (static_cast<uint64_t>(1023) << 52); // Return the final result return result.dp - 1.0; } template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::complex<float> RandomToTypeUniform<std::complex<float> >(uint64_t* state) { return std::complex<float>(RandomToTypeUniform<float>(state), RandomToTypeUniform<float>(state)); } template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::complex<double> RandomToTypeUniform<std::complex<double> >(uint64_t* state) { return std::complex<double>(RandomToTypeUniform<double>(state), RandomToTypeUniform<double>(state)); } template <typename T> class UniformRandomGenerator { public: static const bool PacketAccess = true; // Uses the given "seed" if non-zero, otherwise uses a random seed. EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE UniformRandomGenerator( uint64_t seed = 0) { m_state = PCG_XSH_RS_state(seed); } EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE UniformRandomGenerator( const UniformRandomGenerator& other) { m_state = other.m_state; } template<typename Index> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T operator()(Index i) const { uint64_t local_state = m_state + i; T result = RandomToTypeUniform<T>(&local_state); m_state = local_state; return result; } template<typename Packet, typename Index> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(Index i) const { const int packetSize = internal::unpacket_traits<Packet>::size; EIGEN_ALIGN_MAX T values[packetSize]; uint64_t local_state = m_state + i; for (int j = 0; j < packetSize; ++j) { values[j] = RandomToTypeUniform<T>(&local_state); } m_state = local_state; return internal::pload<Packet>(values); } private: mutable uint64_t m_state; }; template <typename Scalar> struct functor_traits<UniformRandomGenerator<Scalar> > { enum { // Rough estimate for floating point, multiplied by ceil(sizeof(T) / sizeof(float)). Cost = 12 * NumTraits<Scalar>::AddCost * ((sizeof(Scalar) + sizeof(float) - 1) / sizeof(float)), PacketAccess = UniformRandomGenerator<Scalar>::PacketAccess }; }; template <typename T> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T RandomToTypeNormal(uint64_t* state) { // Use the ratio of uniform method to generate numbers following a normal // distribution. See for example Numerical Recipes chapter 7.3.9 for the // details. T u, v, q; do { u = RandomToTypeUniform<T>(state); v = T(1.7156) * (RandomToTypeUniform<T>(state) - T(0.5)); const T x = u - T(0.449871); const T y = numext::abs(v) + T(0.386595); q = x*x + y * (T(0.196)*y - T(0.25472)*x); } while (q > T(0.27597) && (q > T(0.27846) || v*v > T(-4) * numext::log(u) * u*u)); return v/u; } template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::complex<float> RandomToTypeNormal<std::complex<float> >(uint64_t* state) { return std::complex<float>(RandomToTypeNormal<float>(state), RandomToTypeNormal<float>(state)); } template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::complex<double> RandomToTypeNormal<std::complex<double> >(uint64_t* state) { return std::complex<double>(RandomToTypeNormal<double>(state), RandomToTypeNormal<double>(state)); } template <typename T> class NormalRandomGenerator { public: static const bool PacketAccess = true; // Uses the given "seed" if non-zero, otherwise uses a random seed. EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE NormalRandomGenerator(uint64_t seed = 0) { m_state = PCG_XSH_RS_state(seed); } EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE NormalRandomGenerator( const NormalRandomGenerator& other) { m_state = other.m_state; } template<typename Index> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T operator()(Index i) const { uint64_t local_state = m_state + i; T result = RandomToTypeNormal<T>(&local_state); m_state = local_state; return result; } template<typename Packet, typename Index> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(Index i) const { const int packetSize = internal::unpacket_traits<Packet>::size; EIGEN_ALIGN_MAX T values[packetSize]; uint64_t local_state = m_state + i; for (int j = 0; j < packetSize; ++j) { values[j] = RandomToTypeNormal<T>(&local_state); } m_state = local_state; return internal::pload<Packet>(values); } private: mutable uint64_t m_state; }; template <typename Scalar> struct functor_traits<NormalRandomGenerator<Scalar> > { enum { // On average, we need to generate about 3 random numbers // 15 mul, 8 add, 1.5 logs Cost = 3 * functor_traits<UniformRandomGenerator<Scalar> >::Cost + 15 * NumTraits<Scalar>::AddCost + 8 * NumTraits<Scalar>::AddCost + 3 * functor_traits<scalar_log_op<Scalar> >::Cost / 2, PacketAccess = NormalRandomGenerator<Scalar>::PacketAccess }; }; } // end namespace internal } // end namespace Eigen #endif // EIGEN_CXX11_TENSOR_TENSOR_RANDOM_H
dune
(library (name raylib_functions) (package raylib) (modules Raylib_functions) (flags (:standard -w -9-27)) (libraries ctypes.stubs raylib_fixed_types)) (library (name raylib_math) (package raylib) (modules Raylib_math) (flags (:standard -w -9-27)) (libraries ctypes.stubs raylib_fixed_types)) (library (name raygui_functions) (package raygui) (modules Raygui_functions) (flags (:standard -w -9-27)) (libraries ctypes.stubs raygui_fixed_types raylib_fixed_types)) (library (name raylib_rlgl) (package raylib) (modules Raylib_rlgl) (flags (:standard -w -9-27)) (libraries ctypes.stubs rlgl_generated_types raylib_fixed_types))
vote_repr.mli
(** a protocol change proposal *) type proposal = Protocol_hash.t (** votes can be for, against or neutral. Neutral serves to count towards a quorum *) type ballot = Yay | Nay | Pass val ballot_encoding : ballot Data_encoding.t
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
dune
(executables (names person_runner person2_runner person_thing_runner) (libraries pyml))
dune
(executable (name example) (libraries examplelib))
getTrailStatus.mli
open Types type input = GetTrailStatusRequest.t type output = GetTrailStatusResponse.t type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
helpers_services.ml
open Alpha_context type error += Cannot_parse_operation (* `Branch *) let () = register_error_kind `Branch ~id:"operation.cannot_parse" ~title:"Cannot parse operation" ~description:"The operation is ill-formed or for another protocol version" ~pp:(fun ppf () -> Format.fprintf ppf "The operation cannot be parsed") Data_encoding.unit (function Cannot_parse_operation -> Some () | _ -> None) (fun () -> Cannot_parse_operation) let parse_operation (op : Operation.raw) = match Data_encoding.Binary.of_bytes Operation.protocol_data_encoding op.proto with | Some protocol_data -> ok {shell = op.shell; protocol_data} | None -> error Cannot_parse_operation let path = RPC_path.(open_root / "helpers") module Scripts = struct module S = struct open Data_encoding let path = RPC_path.(path / "scripts") let run_code_input_encoding = obj9 (req "script" Script.expr_encoding) (req "storage" Script.expr_encoding) (req "input" Script.expr_encoding) (req "amount" Tez.encoding) (req "chain_id" Chain_id.encoding) (opt "source" Contract.encoding) (opt "payer" Contract.encoding) (opt "gas" z) (dft "entrypoint" string "default") let trace_encoding = def "scripted.trace" @@ list @@ obj3 (req "location" Script.location_encoding) (req "gas" Gas.encoding) (req "stack" (list (obj2 (req "item" Script.expr_encoding) (opt "annot" string)))) let run_code = RPC_service.post_service ~description:"Run a piece of code in the current context" ~query:RPC_query.empty ~input:run_code_input_encoding ~output: (obj3 (req "storage" Script.expr_encoding) (req "operations" (list Operation.internal_operation_encoding)) (opt "big_map_diff" Contract.big_map_diff_encoding)) RPC_path.(path / "run_code") let trace_code = RPC_service.post_service ~description: "Run a piece of code in the current context, keeping a trace" ~query:RPC_query.empty ~input:run_code_input_encoding ~output: (obj4 (req "storage" Script.expr_encoding) (req "operations" (list Operation.internal_operation_encoding)) (req "trace" trace_encoding) (opt "big_map_diff" Contract.big_map_diff_encoding)) RPC_path.(path / "trace_code") let typecheck_code = RPC_service.post_service ~description:"Typecheck a piece of code in the current context" ~query:RPC_query.empty ~input:(obj2 (req "program" Script.expr_encoding) (opt "gas" z)) ~output: (obj2 (req "type_map" Script_tc_errors_registration.type_map_enc) (req "gas" Gas.encoding)) RPC_path.(path / "typecheck_code") let typecheck_data = RPC_service.post_service ~description: "Check that some data expression is well formed and of a given type \ in the current context" ~query:RPC_query.empty ~input: (obj3 (req "data" Script.expr_encoding) (req "type" Script.expr_encoding) (opt "gas" z)) ~output:(obj1 (req "gas" Gas.encoding)) RPC_path.(path / "typecheck_data") let pack_data = RPC_service.post_service ~description: "Computes the serialized version of some data expression using the \ same algorithm as script instruction PACK" ~input: (obj3 (req "data" Script.expr_encoding) (req "type" Script.expr_encoding) (opt "gas" z)) ~output:(obj2 (req "packed" bytes) (req "gas" Gas.encoding)) ~query:RPC_query.empty RPC_path.(path / "pack_data") let run_operation = RPC_service.post_service ~description:"Run an operation without signature checks" ~query:RPC_query.empty ~input: (obj2 (req "operation" Operation.encoding) (req "chain_id" Chain_id.encoding)) ~output:Apply_results.operation_data_and_metadata_encoding RPC_path.(path / "run_operation") let entrypoint_type = RPC_service.post_service ~description:"Return the type of the given entrypoint" ~query:RPC_query.empty ~input: (obj2 (req "script" Script.expr_encoding) (dft "entrypoint" string "default")) ~output:(obj1 (req "entrypoint_type" Script.expr_encoding)) RPC_path.(path / "entrypoint") let list_entrypoints = RPC_service.post_service ~description:"Return the list of entrypoints of the given script" ~query:RPC_query.empty ~input:(obj1 (req "script" Script.expr_encoding)) ~output: (obj2 (dft "unreachable" (Data_encoding.list (obj1 (req "path" (Data_encoding.list Michelson_v1_primitives.prim_encoding)))) []) (req "entrypoints" (assoc Script.expr_encoding))) RPC_path.(path / "entrypoints") end let register () = let open Services_registration in let originate_dummy_contract ctxt script = let ctxt = Contract.init_origination_nonce ctxt Operation_hash.zero in Contract.fresh_contract_from_current_nonce ctxt >>=? fun (ctxt, dummy_contract) -> let balance = match Tez.of_mutez 4_000_000_000_000L with | Some balance -> balance | None -> assert false in Contract.originate ctxt dummy_contract ~balance ~delegate:None ~script:(script, None) >>=? fun ctxt -> return (ctxt, dummy_contract) in register0 S.run_code (fun ctxt () ( code, storage, parameter, amount, chain_id, source, payer, gas, entrypoint ) -> let storage = Script.lazy_expr storage in let code = Script.lazy_expr code in originate_dummy_contract ctxt {storage; code} >>=? fun (ctxt, dummy_contract) -> let (source, payer) = match (source, payer) with | (Some source, Some payer) -> (source, payer) | (Some source, None) -> (source, source) | (None, Some payer) -> (payer, payer) | (None, None) -> (dummy_contract, dummy_contract) in let gas = match gas with | Some gas -> gas | None -> Constants.hard_gas_limit_per_operation ctxt in let ctxt = Gas.set_limit ctxt gas in let step_constants = let open Script_interpreter in {source; payer; self = dummy_contract; amount; chain_id} in Script_interpreter.execute ctxt Readable step_constants ~script:{storage; code} ~entrypoint ~parameter >>=? fun {Script_interpreter.storage; operations; big_map_diff; _} -> return (storage, operations, big_map_diff)) ; register0 S.trace_code (fun ctxt () ( code, storage, parameter, amount, chain_id, source, payer, gas, entrypoint ) -> let storage = Script.lazy_expr storage in let code = Script.lazy_expr code in originate_dummy_contract ctxt {storage; code} >>=? fun (ctxt, dummy_contract) -> let (source, payer) = match (source, payer) with | (Some source, Some payer) -> (source, payer) | (Some source, None) -> (source, source) | (None, Some payer) -> (payer, payer) | (None, None) -> (dummy_contract, dummy_contract) in let gas = match gas with | Some gas -> gas | None -> Constants.hard_gas_limit_per_operation ctxt in let ctxt = Gas.set_limit ctxt gas in let step_constants = let open Script_interpreter in {source; payer; self = dummy_contract; amount; chain_id} in Script_interpreter.trace ctxt Readable step_constants ~script:{storage; code} ~entrypoint ~parameter >>=? fun ( {Script_interpreter.storage; operations; big_map_diff; _}, trace ) -> return (storage, operations, trace, big_map_diff)) ; register0 S.typecheck_code (fun ctxt () (expr, maybe_gas) -> let ctxt = match maybe_gas with | None -> Gas.set_unlimited ctxt | Some gas -> Gas.set_limit ctxt gas in Script_ir_translator.typecheck_code ctxt expr >>=? fun (res, ctxt) -> return (res, Gas.level ctxt)) ; register0 S.typecheck_data (fun ctxt () (data, ty, maybe_gas) -> let ctxt = match maybe_gas with | None -> Gas.set_unlimited ctxt | Some gas -> Gas.set_limit ctxt gas in Script_ir_translator.typecheck_data ctxt (data, ty) >>=? fun ctxt -> return (Gas.level ctxt)) ; register0 S.pack_data (fun ctxt () (expr, typ, maybe_gas) -> let open Script_ir_translator in let ctxt = match maybe_gas with | None -> Gas.set_unlimited ctxt | Some gas -> Gas.set_limit ctxt gas in Lwt.return (parse_packable_ty ctxt ~legacy:true (Micheline.root typ)) >>=? fun (Ex_ty typ, ctxt) -> parse_data ctxt ~legacy:true typ (Micheline.root expr) >>=? fun (data, ctxt) -> Script_ir_translator.pack_data ctxt typ data >>=? fun (bytes, ctxt) -> return (bytes, Gas.level ctxt)) ; register0 S.run_operation (fun ctxt () ({shell; protocol_data = Operation_data protocol_data}, chain_id) -> (* this code is a duplicate of Apply without signature check *) let partial_precheck_manager_contents (type kind) ctxt (op : kind Kind.manager contents) : context tzresult Lwt.t = let (Manager_operation {source; fee; counter; operation; gas_limit; storage_limit}) = op in Lwt.return (Gas.check_limit ctxt gas_limit) >>=? fun () -> let ctxt = Gas.set_limit ctxt gas_limit in Lwt.return (Fees.check_storage_limit ctxt storage_limit) >>=? fun () -> Contract.must_be_allocated ctxt (Contract.implicit_contract source) >>=? fun () -> Contract.check_counter_increment ctxt source counter >>=? fun () -> ( match operation with | Reveal pk -> Contract.reveal_manager_key ctxt source pk | Transaction {parameters; _} -> (* Here the data comes already deserialized, so we need to fake the deserialization to mimic apply *) let arg_bytes = Data_encoding.Binary.to_bytes_exn Script.lazy_expr_encoding parameters in let arg = match Data_encoding.Binary.of_bytes Script.lazy_expr_encoding arg_bytes with | Some arg -> arg | None -> assert false in (* Fail quickly if not enough gas for minimal deserialization cost *) Lwt.return @@ record_trace Apply.Gas_quota_exceeded_init_deserialize @@ Gas.check_enough ctxt (Script.minimal_deserialize_cost arg) >>=? fun () -> (* Fail if not enough gas for complete deserialization cost *) trace Apply.Gas_quota_exceeded_init_deserialize @@ Script.force_decode ctxt arg >>|? fun (_arg, ctxt) -> ctxt | Origination {script; _} -> (* Here the data comes already deserialized, so we need to fake the deserialization to mimic apply *) let script_bytes = Data_encoding.Binary.to_bytes_exn Script.encoding script in let script = match Data_encoding.Binary.of_bytes Script.encoding script_bytes with | Some script -> script | None -> assert false in (* Fail quickly if not enough gas for minimal deserialization cost *) Lwt.return @@ record_trace Apply.Gas_quota_exceeded_init_deserialize @@ ( Gas.consume ctxt (Script.minimal_deserialize_cost script.code) >>? fun ctxt -> Gas.check_enough ctxt (Script.minimal_deserialize_cost script.storage) ) >>=? fun () -> (* Fail if not enough gas for complete deserialization cost *) trace Apply.Gas_quota_exceeded_init_deserialize @@ Script.force_decode ctxt script.code >>=? fun (_code, ctxt) -> trace Apply.Gas_quota_exceeded_init_deserialize @@ Script.force_decode ctxt script.storage >>|? fun (_storage, ctxt) -> ctxt | _ -> return ctxt ) >>=? fun ctxt -> Contract.get_manager_key ctxt source >>=? fun _public_key -> (* signature check unplugged from here *) Contract.increment_counter ctxt source >>=? fun ctxt -> Contract.spend ctxt (Contract.implicit_contract source) fee >>=? fun ctxt -> return ctxt in let rec partial_precheck_manager_contents_list : type kind. Alpha_context.t -> kind Kind.manager contents_list -> context tzresult Lwt.t = fun ctxt contents_list -> match contents_list with | Single (Manager_operation _ as op) -> partial_precheck_manager_contents ctxt op | Cons ((Manager_operation _ as op), rest) -> partial_precheck_manager_contents ctxt op >>=? fun ctxt -> partial_precheck_manager_contents_list ctxt rest in let return contents = return ( Operation_data protocol_data, Apply_results.Operation_metadata {contents} ) in let operation : _ operation = {shell; protocol_data} in let hash = Operation.hash {shell; protocol_data} in let ctxt = Contract.init_origination_nonce ctxt hash in let baker = Signature.Public_key_hash.zero in match protocol_data.contents with | Single (Manager_operation _) as op -> partial_precheck_manager_contents_list ctxt op >>=? fun ctxt -> Apply.apply_manager_contents_list ctxt Optimized baker chain_id op >>= fun (_ctxt, result) -> return result | Cons (Manager_operation _, _) as op -> partial_precheck_manager_contents_list ctxt op >>=? fun ctxt -> Apply.apply_manager_contents_list ctxt Optimized baker chain_id op >>= fun (_ctxt, result) -> return result | _ -> Apply.apply_contents_list ctxt chain_id Optimized shell.branch baker operation operation.protocol_data.contents >>=? fun (_ctxt, result) -> return result) ; register0 S.entrypoint_type (fun ctxt () (expr, entrypoint) -> let ctxt = Gas.set_unlimited ctxt in let legacy = false in let open Script_ir_translator in Lwt.return ( parse_toplevel ~legacy expr >>? fun (arg_type, _, _, root_name) -> parse_ty ctxt ~legacy ~allow_big_map:true ~allow_operation:false ~allow_contract:true arg_type >>? fun (Ex_ty arg_type, _) -> Script_ir_translator.find_entrypoint ~root_name arg_type entrypoint ) >>=? fun (_f, Ex_ty ty) -> unparse_ty ctxt ty >>=? fun (ty_node, _) -> return (Micheline.strip_locations ty_node)) ; register0 S.list_entrypoints (fun ctxt () expr -> let ctxt = Gas.set_unlimited ctxt in let legacy = false in let open Script_ir_translator in Lwt.return ( parse_toplevel ~legacy expr >>? fun (arg_type, _, _, root_name) -> parse_ty ctxt ~legacy ~allow_big_map:true ~allow_operation:false ~allow_contract:true arg_type >>? fun (Ex_ty arg_type, _) -> Script_ir_translator.list_entrypoints ~root_name arg_type ctxt ) >>=? fun (unreachable_entrypoint, map) -> return ( unreachable_entrypoint, Entrypoints_map.fold (fun entry (_, ty) acc -> (entry, Micheline.strip_locations ty) :: acc) map [] )) let run_code ctxt block code (storage, input, amount, chain_id, source, payer, gas, entrypoint) = RPC_context.make_call0 S.run_code ctxt block () (code, storage, input, amount, chain_id, source, payer, gas, entrypoint) let trace_code ctxt block code (storage, input, amount, chain_id, source, payer, gas, entrypoint) = RPC_context.make_call0 S.trace_code ctxt block () (code, storage, input, amount, chain_id, source, payer, gas, entrypoint) let typecheck_code ctxt block = RPC_context.make_call0 S.typecheck_code ctxt block () let typecheck_data ctxt block = RPC_context.make_call0 S.typecheck_data ctxt block () let pack_data ctxt block = RPC_context.make_call0 S.pack_data ctxt block () let run_operation ctxt block = RPC_context.make_call0 S.run_operation ctxt block () let entrypoint_type ctxt block = RPC_context.make_call0 S.entrypoint_type ctxt block () let list_entrypoints ctxt block = RPC_context.make_call0 S.list_entrypoints ctxt block () end module Forge = struct module S = struct open Data_encoding let path = RPC_path.(path / "forge") let operations = RPC_service.post_service ~description:"Forge an operation" ~query:RPC_query.empty ~input:Operation.unsigned_encoding ~output:bytes RPC_path.(path / "operations") let empty_proof_of_work_nonce = MBytes.of_string (String.make Constants_repr.proof_of_work_nonce_size '\000') let protocol_data = RPC_service.post_service ~description:"Forge the protocol-specific part of a block header" ~query:RPC_query.empty ~input: (obj3 (req "priority" uint16) (opt "nonce_hash" Nonce_hash.encoding) (dft "proof_of_work_nonce" (Fixed.bytes Alpha_context.Constants.proof_of_work_nonce_size) empty_proof_of_work_nonce)) ~output:(obj1 (req "protocol_data" bytes)) RPC_path.(path / "protocol_data") end let register () = let open Services_registration in register0_noctxt S.operations (fun () (shell, proto) -> return (Data_encoding.Binary.to_bytes_exn Operation.unsigned_encoding (shell, proto))) ; register0_noctxt S.protocol_data (fun () (priority, seed_nonce_hash, proof_of_work_nonce) -> return (Data_encoding.Binary.to_bytes_exn Block_header.contents_encoding {priority; seed_nonce_hash; proof_of_work_nonce})) module Manager = struct let operations ctxt block ~branch ~source ?sourcePubKey ~counter ~fee ~gas_limit ~storage_limit operations = Contract_services.manager_key ctxt block source >>= function | Error _ as e -> Lwt.return e | Ok revealed -> let ops = List.map (fun (Manager operation) -> Contents (Manager_operation { source; counter; operation; fee; gas_limit; storage_limit; })) operations in let ops = match (sourcePubKey, revealed) with | (None, _) | (_, Some _) -> ops | (Some pk, None) -> let operation = Reveal pk in Contents (Manager_operation { source; counter; operation; fee; gas_limit; storage_limit; }) :: ops in RPC_context.make_call0 S.operations ctxt block () ({branch}, Operation.of_list ops) let reveal ctxt block ~branch ~source ~sourcePubKey ~counter ~fee () = operations ctxt block ~branch ~source ~sourcePubKey ~counter ~fee ~gas_limit:Z.zero ~storage_limit:Z.zero [] let transaction ctxt block ~branch ~source ?sourcePubKey ~counter ~amount ~destination ?(entrypoint = "default") ?parameters ~gas_limit ~storage_limit ~fee () = let parameters = Option.unopt_map ~f:Script.lazy_expr ~default:Script.unit_parameter parameters in operations ctxt block ~branch ~source ?sourcePubKey ~counter ~fee ~gas_limit ~storage_limit [Manager (Transaction {amount; parameters; destination; entrypoint})] let origination ctxt block ~branch ~source ?sourcePubKey ~counter ~balance ?delegatePubKey ~script ~gas_limit ~storage_limit ~fee () = operations ctxt block ~branch ~source ?sourcePubKey ~counter ~fee ~gas_limit ~storage_limit [ Manager (Origination { delegate = delegatePubKey; script; credit = balance; preorigination = None; }) ] let delegation ctxt block ~branch ~source ?sourcePubKey ~counter ~fee delegate = operations ctxt block ~branch ~source ?sourcePubKey ~counter ~fee ~gas_limit:Z.zero ~storage_limit:Z.zero [Manager (Delegation delegate)] end let operation ctxt block ~branch operation = RPC_context.make_call0 S.operations ctxt block () ({branch}, Contents_list (Single operation)) let endorsement ctxt b ~branch ~level () = operation ctxt b ~branch (Endorsement {level}) let proposals ctxt b ~branch ~source ~period ~proposals () = operation ctxt b ~branch (Proposals {source; period; proposals}) let ballot ctxt b ~branch ~source ~period ~proposal ~ballot () = operation ctxt b ~branch (Ballot {source; period; proposal; ballot}) let seed_nonce_revelation ctxt block ~branch ~level ~nonce () = operation ctxt block ~branch (Seed_nonce_revelation {level; nonce}) let double_baking_evidence ctxt block ~branch ~bh1 ~bh2 () = operation ctxt block ~branch (Double_baking_evidence {bh1; bh2}) let double_endorsement_evidence ctxt block ~branch ~op1 ~op2 () = operation ctxt block ~branch (Double_endorsement_evidence {op1; op2}) let empty_proof_of_work_nonce = MBytes.of_string (String.make Constants_repr.proof_of_work_nonce_size '\000') let protocol_data ctxt block ~priority ?seed_nonce_hash ?(proof_of_work_nonce = empty_proof_of_work_nonce) () = RPC_context.make_call0 S.protocol_data ctxt block () (priority, seed_nonce_hash, proof_of_work_nonce) end module Parse = struct module S = struct open Data_encoding let path = RPC_path.(path / "parse") let operations = RPC_service.post_service ~description:"Parse operations" ~query:RPC_query.empty ~input: (obj2 (req "operations" (list (dynamic_size Operation.raw_encoding))) (opt "check_signature" bool)) ~output:(list (dynamic_size Operation.encoding)) RPC_path.(path / "operations") let block = RPC_service.post_service ~description:"Parse a block" ~query:RPC_query.empty ~input:Block_header.raw_encoding ~output:Block_header.protocol_data_encoding RPC_path.(path / "block") end let parse_protocol_data protocol_data = match Data_encoding.Binary.of_bytes Block_header.protocol_data_encoding protocol_data with | None -> failwith "Cant_parse_protocol_data" | Some protocol_data -> return protocol_data let register () = let open Services_registration in register0 S.operations (fun _ctxt () (operations, check) -> map_s (fun raw -> Lwt.return (parse_operation raw) >>=? fun op -> ( match check with | Some true -> return_unit (* FIXME *) (* I.check_signature ctxt *) (* op.protocol_data.signature op.shell op.protocol_data.contents *) | Some false | None -> return_unit ) >>|? fun () -> op) operations) ; register0_noctxt S.block (fun () raw_block -> parse_protocol_data raw_block.protocol_data) let operations ctxt block ?check operations = RPC_context.make_call0 S.operations ctxt block () (operations, check) let block ctxt block shell protocol_data = RPC_context.make_call0 S.block ctxt block () ({shell; protocol_data} : Block_header.raw) end module S = struct open Data_encoding type level_query = {offset : int32} let level_query : level_query RPC_query.t = let open RPC_query in query (fun offset -> {offset}) |+ field "offset" RPC_arg.int32 0l (fun t -> t.offset) |> seal let current_level = RPC_service.get_service ~description: "Returns the level of the interrogated block, or the one of a block \ located `offset` blocks after in the chain (or before when \ negative). For instance, the next block if `offset` is 1." ~query:level_query ~output:Level.encoding RPC_path.(path / "current_level") let levels_in_current_cycle = RPC_service.get_service ~description:"Levels of a cycle" ~query:level_query ~output: (obj2 (req "first" Raw_level.encoding) (req "last" Raw_level.encoding)) RPC_path.(path / "levels_in_current_cycle") end let register () = Scripts.register () ; Forge.register () ; Parse.register () ; let open Services_registration in register0 S.current_level (fun ctxt q () -> let level = Level.current ctxt in return (Level.from_raw ctxt ~offset:q.offset level.level)) ; register0 S.levels_in_current_cycle (fun ctxt q () -> let levels = Level.levels_in_current_cycle ctxt ~offset:q.offset () in match levels with | [] -> raise Not_found | _ -> let first = List.hd (List.rev levels) in let last = List.hd levels in return (first.level, last.level)) let current_level ctxt ?(offset = 0l) block = RPC_context.make_call0 S.current_level ctxt block {offset} () let levels_in_current_cycle ctxt ?(offset = 0l) block = RPC_context.make_call0 S.levels_in_current_cycle ctxt block {offset} ()
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
gluten_lwt.ml
open Lwt.Infix module Buffer = Gluten.Buffer include Gluten_lwt_intf module IO_loop = struct let start : type t fd. (module IO with type socket = fd) -> (module Gluten.RUNTIME with type t = t) -> t -> read_buffer_size:int -> fd -> unit Lwt.t = fun (module Io) (module Runtime) t ~read_buffer_size socket -> let read_buffer = Buffer.create read_buffer_size in let read_loop_exited, notify_read_loop_exited = Lwt.wait () in let rec read_loop () = let rec read_loop_step () = match Runtime.next_read_operation t with | `Read -> Buffer.put ~f:(fun buf ~off ~len k -> Lwt.on_success (Io.read socket buf ~off ~len) k) read_buffer (function | `Eof -> let (_ : int) = Buffer.get read_buffer ~f:(Runtime.read_eof t) in read_loop_step () | `Ok _ -> let (_ : int) = Buffer.get read_buffer ~f:(Runtime.read t) in read_loop_step ()) | `Yield -> Runtime.yield_reader t read_loop | `Close -> Lwt.wakeup_later notify_read_loop_exited (); Io.shutdown_receive socket in Lwt.async (fun () -> Lwt.catch (Lwt.wrap1 read_loop_step) (fun exn -> Runtime.report_exn t exn; Lwt.return_unit)) in let writev = Io.writev socket in let write_loop_exited, notify_write_loop_exited = Lwt.wait () in let rec write_loop () = let rec write_loop_step () = match Runtime.next_write_operation t with | `Write io_vectors -> writev io_vectors >>= fun result -> Runtime.report_write_result t result; write_loop_step () | `Yield -> Runtime.yield_writer t write_loop; Lwt.return_unit | `Close _ -> Lwt.wakeup_later notify_write_loop_exited (); Lwt.return_unit in Lwt.async (fun () -> Lwt.catch write_loop_step (fun exn -> Runtime.report_exn t exn; Lwt.return_unit)) in read_loop (); write_loop (); Lwt.join [ read_loop_exited; write_loop_exited ] >>= fun () -> Io.close socket end module Server (Io : IO) = struct module Server = Gluten.Server type socket = Io.socket type addr = Io.addr let create_connection_handler ~read_buffer_size ~protocol connection _client_addr socket = let connection = Server.create ~protocol connection in IO_loop.start (module Io) (module Server) connection ~read_buffer_size socket let create_upgradable_connection_handler ~read_buffer_size ~protocol ~create_protocol ~request_handler client_addr socket = let connection = Server.create_upgradable ~protocol ~create:create_protocol (request_handler client_addr) in IO_loop.start (module Io) (module Server) connection ~read_buffer_size socket end module Client (Io : IO) = struct module Client_connection = Gluten.Client type socket = Io.socket type t = { connection : Client_connection.t ; socket : socket } let create ~read_buffer_size ~protocol t socket = let connection = Client_connection.create ~protocol t in Lwt.async (fun () -> IO_loop.start (module Io) (module Client_connection) connection ~read_buffer_size socket); Lwt.return { connection; socket } let upgrade t protocol = Client_connection.upgrade_protocol t.connection protocol let shutdown t = Client_connection.shutdown t.connection; Io.close t.socket let is_closed t = Client_connection.is_closed t.connection let socket t = t.socket end
(*---------------------------------------------------------------------------- * Copyright (c) 2018 Inhabited Type LLC. * Copyright (c) 2018 Anton Bachin * Copyright (c) 2019-2020 Antonio N. Monteiro. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the author nor the names of his contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*)
irred_smprime_wang.c
#include "fmpz_mod_mpoly_factor.h" /* return 1: success 0: failed -1: exception (large exps) */ int fmpz_mod_mpoly_factor_irred_smprime_wang( fmpz_mod_mpolyv_t fac, const fmpz_mod_mpoly_t A, const fmpz_mod_mpoly_factor_t lcAfac, const fmpz_mod_mpoly_t lcA, const fmpz_mod_mpoly_ctx_t ctx, flint_rand_t state) { int success; int alphas_tries_remaining, alphabetas_tries_remaining, alphabetas_length; const slong n = ctx->minfo->nvars - 1; slong i, j, k, r; fmpz * alpha; fmpz_mod_poly_struct * alphabetas; fmpz_mod_mpoly_struct * Aevals; slong * degs, * degeval; fmpz_mod_mpolyv_t tfac; fmpz_mod_mpoly_t t, Acopy; fmpz_mod_mpoly_struct * newA; fmpz_mod_poly_t Abfc; fmpz_mod_bpoly_t Ab; fmpz_mod_tpoly_t Abfp; fmpz_mod_mpoly_t m, mpow; fmpz_mod_mpolyv_t new_lcs, lc_divs; FLINT_ASSERT(n > 1); FLINT_ASSERT(A->length > 1); FLINT_ASSERT(fmpz_is_one(A->coeffs + 0)); FLINT_ASSERT(A->bits <= FLINT_BITS); fmpz_mod_mpoly_init(Acopy, ctx); fmpz_mod_mpoly_init(m, ctx); fmpz_mod_mpoly_init(mpow, ctx); fmpz_mod_mpolyv_init(new_lcs, ctx); fmpz_mod_mpolyv_init(lc_divs, ctx); fmpz_mod_poly_init(Abfc, ctx->ffinfo); fmpz_mod_tpoly_init(Abfp, ctx->ffinfo); fmpz_mod_bpoly_init(Ab, ctx->ffinfo); degs = FLINT_ARRAY_ALLOC(n + 1, slong); degeval = FLINT_ARRAY_ALLOC(n + 1, slong); alpha = _fmpz_vec_init(n); alphabetas = FLINT_ARRAY_ALLOC(n, fmpz_mod_poly_struct); Aevals = FLINT_ARRAY_ALLOC(n, fmpz_mod_mpoly_struct); for (i = 0; i < n; i++) { fmpz_mod_poly_init(alphabetas + i, ctx->ffinfo); fmpz_mod_mpoly_init(Aevals + i, ctx); } fmpz_mod_mpolyv_init(tfac, ctx); fmpz_mod_mpoly_init(t, ctx); /* init done */ alphabetas_length = 2; alphas_tries_remaining = 10; fmpz_mod_mpoly_degrees_si(degs, A, ctx); next_alpha: if (--alphas_tries_remaining < 0) { success = 0; goto cleanup; } for (i = 0; i < n; i++) fmpz_mod_rand_not_zero(alpha + i, state, ctx->ffinfo); /* ensure degrees do not drop under evaluation */ for (i = n - 1; i >= 0; i--) { fmpz_mod_mpoly_evaluate_one_fmpz(Aevals + i, i == n - 1 ? A : Aevals + i + 1, i + 1, alpha + i, ctx); fmpz_mod_mpoly_degrees_si(degeval, Aevals + i, ctx); for (j = 0; j <= i; j++) if (degeval[j] != degs[j]) goto next_alpha; } /* make sure univar is squarefree */ fmpz_mod_mpoly_derivative(t, Aevals + 0, 0, ctx); if (!fmpz_mod_mpoly_gcd(t, t, Aevals + 0, ctx)) { success = -1; goto cleanup; } if (!fmpz_mod_mpoly_is_one(t, ctx)) goto next_alpha; alphabetas_tries_remaining = 2 + alphabetas_length; next_alphabetas: if (--alphabetas_tries_remaining < 0) { if (++alphabetas_length > 10) { success = 0; goto cleanup; } goto next_alpha; } for (i = 0; i < n; i++) { fmpz_mod_poly_fit_length(alphabetas + i, alphabetas_length, ctx->ffinfo); fmpz_set(alphabetas[i].coeffs + 0, alpha + i); for (j = 1; j < alphabetas_length; j++) fmpz_mod_rand(alphabetas[i].coeffs + j, state, ctx->ffinfo); _fmpz_mod_poly_set_length(alphabetas + i, alphabetas_length); _fmpz_mod_poly_normalise(alphabetas + i); } _fmpz_mod_mpoly_eval_rest_to_fmpz_mod_bpoly(Ab, A, alphabetas, ctx); success = fmpz_mod_bpoly_factor_smprime(Abfc, Abfp, Ab, 0, ctx->ffinfo); if (!success) { FLINT_ASSERT(0 && "this should not happen"); goto next_alpha; } r = Abfp->length; if (r < 2) { fmpz_mod_mpolyv_fit_length(fac, 1, ctx); fac->length = 1; fmpz_mod_mpoly_set(fac->coeffs + 0, A, ctx); success = 1; goto cleanup; } fmpz_mod_mpolyv_fit_length(lc_divs, r, ctx); lc_divs->length = r; if (lcAfac->num > 0) { success = fmpz_mod_mpoly_factor_lcc_wang(lc_divs->coeffs, lcAfac, Abfc, Abfp->coeffs, r, alphabetas, ctx); if (!success) goto next_alphabetas; } else { for (i = 0; i < r; i++) fmpz_mod_mpoly_one(lc_divs->coeffs + i, ctx); } success = fmpz_mod_mpoly_divides(m, lcA, lc_divs->coeffs + 0, ctx); FLINT_ASSERT(success); for (i = 1; i < r; i++) { success = fmpz_mod_mpoly_divides(m, m, lc_divs->coeffs + i, ctx); FLINT_ASSERT(success); } fmpz_mod_mpoly_pow_ui(mpow, m, r - 1, ctx); if (fmpz_mod_mpoly_is_one(mpow, ctx)) { newA = (fmpz_mod_mpoly_struct *) A; } else { newA = Acopy; fmpz_mod_mpoly_mul(newA, A, mpow, ctx); } if (newA->bits > FLINT_BITS) { success = 0; goto cleanup; } fmpz_mod_mpoly_degrees_si(degs, newA, ctx); fmpz_mod_mpoly_set(t, mpow, ctx); for (i = n - 1; i >= 0; i--) { fmpz_mod_mpoly_evaluate_one_fmpz(t, mpow, i + 1, alpha + i, ctx); fmpz_mod_mpoly_swap(t, mpow, ctx); fmpz_mod_mpoly_mul(Aevals + i, Aevals + i, mpow, ctx); fmpz_mod_mpoly_repack_bits_inplace(Aevals + i, newA->bits, ctx); } fmpz_mod_mpolyv_fit_length(new_lcs, (n + 1)*r, ctx); i = n; for (j = 0; j < r; j++) { fmpz_mod_mpoly_mul(new_lcs->coeffs + i*r + j, lc_divs->coeffs + j, m, ctx); } for (i = n - 1; i >= 0; i--) { for (j = 0; j < r; j++) { fmpz_mod_mpoly_evaluate_one_fmpz(new_lcs->coeffs + i*r + j, new_lcs->coeffs + (i + 1)*r + j, i + 1, alpha + i, ctx); } } fmpz_mod_mpolyv_fit_length(fac, r, ctx); fac->length = r; for (i = 0; i < r; i++) { fmpz_t q; fmpz_init(q); FLINT_ASSERT(fmpz_mod_mpoly_is_fmpz(new_lcs->coeffs + 0*r + i, ctx)); FLINT_ASSERT(fmpz_mod_mpoly_length(new_lcs->coeffs + 0*r + i, ctx) == 1); _fmpz_mod_mpoly_set_fmpz_mod_bpoly_var1_zero(fac->coeffs + i, newA->bits, Abfp->coeffs + i, 0, ctx); FLINT_ASSERT(fac->coeffs[i].length > 0); fmpz_mod_inv(q, fac->coeffs[i].coeffs + 0, ctx->ffinfo); fmpz_mod_mul(q, q, new_lcs->coeffs[0*r + i].coeffs + 0, ctx->ffinfo); fmpz_mod_mpoly_scalar_mul_fmpz_mod_invertible(fac->coeffs + i, fac->coeffs + i, q, ctx); fmpz_clear(q); } fmpz_mod_mpolyv_fit_length(tfac, r, ctx); tfac->length = r; for (k = 1; k <= n; k++) { for (i = 0; i < r; i++) { _fmpz_mod_mpoly_set_lead0(tfac->coeffs + i, fac->coeffs + i, new_lcs->coeffs + k*r + i, ctx); } success = fmpz_mod_mpoly_hlift(k, tfac->coeffs, r, alpha, k < n ? Aevals + k : newA, degs, ctx); if (!success) goto next_alphabetas; fmpz_mod_mpolyv_swap(tfac, fac, ctx); } if (!fmpz_mod_mpoly_is_fmpz(m, ctx)) { for (i = 0; i < r; i++) { /* hlift should not have returned any large bits */ FLINT_ASSERT(fac->coeffs[i].bits <= FLINT_BITS); if (!fmpz_mod_mpolyl_content(t, fac->coeffs + i, 1, ctx)) { success = -1; goto cleanup; } success = fmpz_mod_mpoly_divides(fac->coeffs + i, fac->coeffs + i, t, ctx); FLINT_ASSERT(success); } } for (i = 0; i < r; i++) { /* hlift should not have returned any large bits */ FLINT_ASSERT(fac->coeffs[i].bits <= FLINT_BITS); fmpz_mod_mpoly_make_monic(fac->coeffs + i, fac->coeffs + i, ctx); } success = 1; cleanup: fmpz_mod_mpolyv_clear(new_lcs, ctx); fmpz_mod_mpolyv_clear(lc_divs, ctx); fmpz_mod_poly_clear(Abfc, ctx->ffinfo); fmpz_mod_tpoly_clear(Abfp, ctx->ffinfo); fmpz_mod_bpoly_clear(Ab, ctx->ffinfo); for (i = 0; i < n; i++) { fmpz_mod_mpoly_clear(Aevals + i, ctx); fmpz_mod_poly_clear(alphabetas + i, ctx->ffinfo); } flint_free(alphabetas); _fmpz_vec_clear(alpha, n); flint_free(Aevals); flint_free(degs); flint_free(degeval); fmpz_mod_mpolyv_clear(tfac, ctx); fmpz_mod_mpoly_clear(t, ctx); fmpz_mod_mpoly_clear(Acopy, ctx); fmpz_mod_mpoly_clear(m, ctx); fmpz_mod_mpoly_clear(mpow, ctx); #if FLINT_WANT_ASSERT if (success) { fmpz_mod_mpoly_t prod; fmpz_mod_mpoly_init(prod, ctx); fmpz_mod_mpoly_one(prod, ctx); for (i = 0; i < fac->length; i++) fmpz_mod_mpoly_mul(prod, prod, fac->coeffs + i, ctx); FLINT_ASSERT(fmpz_mod_mpoly_equal(prod, A, ctx)); fmpz_mod_mpoly_clear(prod, ctx); } #endif return success; }
/* Copyright (C) 2020 Daniel Schultz This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
feed_metadata.ml
open Support open General (* Probably we should use a simple timestamp file for the last-checked time and attach the stability ratings to the interface, not the feed. *) type t = { last_checked : float option; user_stability : Stability.t XString.Map.t; } let load config feed_url = match Paths.Config.(first (feed feed_url)) config.paths with | None -> { last_checked = None; user_stability = XString.Map.empty } | Some path -> let root = Qdom.parse_file config.system path in let last_checked = match ZI.get_attribute_opt "last-checked" root with | None -> None | Some time -> Some (float_of_string time) in let stability = ref XString.Map.empty in root |> ZI.iter ~name:"implementation" (fun impl -> let id = ZI.get_attribute "id" impl in match ZI.get_attribute_opt Constants.FeedConfigAttr.user_stability impl with | None -> () | Some s -> stability := XString.Map.add id (Stability.of_string ~from_user:true s) !stability ); { last_checked; user_stability = !stability; } let save config feed_url {last_checked; user_stability} = let feed_path = Paths.Config.(save_path (feed feed_url)) config.paths in let attrs = match last_checked with | None -> Qdom.AttrMap.empty | Some last_checked -> Qdom.AttrMap.singleton "last-checked" (Printf.sprintf "%.0f" last_checked) in let child_nodes = user_stability |> XString.Map.map_bindings (fun id stability -> ZI.make "implementation" ~attrs:( Qdom.AttrMap.singleton Constants.FeedAttr.id id |> Qdom.AttrMap.add_no_ns Constants.FeedConfigAttr.user_stability (Stability.to_string stability) ) ) in let root = ZI.make ~attrs ~child_nodes "feed-preferences" in feed_path |> config.system#atomic_write [Open_wronly; Open_binary] ~mode:0o644 (fun ch -> Qdom.output (`Channel ch |> Xmlm.make_output) root; ) let update config url f = load config url |> f |> save config url let update_last_checked_time config url = update config url (fun t -> {t with last_checked = Some config.system#time}) let stability id t = XString.Map.find_opt id t.user_stability let with_stability id rating t = { t with user_stability = match rating with | None -> XString.Map.remove id t.user_stability | Some rating -> XString.Map.add id rating t.user_stability }
(* Copyright (C) 2020, Thomas Leonard See the README file for details, or visit http://0install.net. *)
misc.mli
(** Miscellaneous useful types and functions {b Warning:} this module is unstable and part of {{!Compiler_libs}compiler-libs}. *) val fatal_error: string -> 'a val fatal_errorf: ('a, Format.formatter, unit, 'b) format4 -> 'a exception Fatal_error val try_finally : ?always:(unit -> unit) -> ?exceptionally:(unit -> unit) -> (unit -> 'a) -> 'a (** [try_finally work ~always ~exceptionally] is designed to run code in [work] that may fail with an exception, and has two kind of cleanup routines: [always], that must be run after any execution of the function (typically, freeing system resources), and [exceptionally], that should be run only if [work] or [always] failed with an exception (typically, undoing user-visible state changes that would only make sense if the function completes correctly). For example: {[ let objfile = outputprefix ^ ".cmo" in let oc = open_out_bin objfile in Misc.try_finally (fun () -> bytecode ++ Timings.(accumulate_time (Generate sourcefile)) (Emitcode.to_file oc modulename objfile); Warnings.check_fatal ()) ~always:(fun () -> close_out oc) ~exceptionally:(fun _exn -> remove_file objfile); ]} If [exceptionally] fail with an exception, it is propagated as usual. If [always] or [exceptionally] use exceptions internally for control-flow but do not raise, then [try_finally] is careful to preserve any exception backtrace coming from [work] or [always] for easier debugging. *) val reraise_preserving_backtrace : exn -> (unit -> unit) -> 'a (** [reraise_preserving_backtrace e f] is (f (); raise e) except that the current backtrace is preserved, even if [f] uses exceptions internally. *) val map_end: ('a -> 'b) -> 'a list -> 'b list -> 'b list (* [map_end f l t] is [map f l @ t], just more efficient. *) val map_left_right: ('a -> 'b) -> 'a list -> 'b list (* Like [List.map], with guaranteed left-to-right evaluation order *) val for_all2: ('a -> 'b -> bool) -> 'a list -> 'b list -> bool (* Same as [List.for_all] but for a binary predicate. In addition, this [for_all2] never fails: given two lists with different lengths, it returns false. *) val replicate_list: 'a -> int -> 'a list (* [replicate_list elem n] is the list with [n] elements all identical to [elem]. *) val list_remove: 'a -> 'a list -> 'a list (* [list_remove x l] returns a copy of [l] with the first element equal to [x] removed. *) val split_last: 'a list -> 'a list * 'a (* Return the last element and the other elements of the given list. *) type ref_and_value = R : 'a ref * 'a -> ref_and_value val protect_refs : ref_and_value list -> (unit -> 'a) -> 'a (** [protect_refs l f] temporarily sets [r] to [v] for each [R (r, v)] in [l] while executing [f]. The previous contents of the references is restored even if [f] raises an exception, without altering the exception backtrace. *) module Stdlib : sig module List : sig type 'a t = 'a list val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int (** The lexicographic order supported by the provided order. There is no constraint on the relative lengths of the lists. *) val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool (** Returns [true] if and only if the given lists have the same length and content with respect to the given equality function. *) val some_if_all_elements_are_some : 'a option t -> 'a t option (** If all elements of the given list are [Some _] then [Some xs] is returned with the [xs] being the contents of those [Some]s, with order preserved. Otherwise return [None]. *) val map2_prefix : ('a -> 'b -> 'c) -> 'a t -> 'b t -> ('c t * 'b t) (** [let r1, r2 = map2_prefix f l1 l2] If [l1] is of length n and [l2 = h2 @ t2] with h2 of length n, r1 is [List.map2 f l1 h1] and r2 is t2. *) val split_at : int -> 'a t -> 'a t * 'a t (** [split_at n l] returns the pair [before, after] where [before] is the [n] first elements of [l] and [after] the remaining ones. If [l] has less than [n] elements, raises Invalid_argument. *) val is_prefix : equal:('a -> 'a -> bool) -> 'a list -> of_:'a list -> bool (** Returns [true] if and only if the given list, with respect to the given equality function on list members, is a prefix of the list [of_]. *) type 'a longest_common_prefix_result = private { longest_common_prefix : 'a list; first_without_longest_common_prefix : 'a list; second_without_longest_common_prefix : 'a list; } val find_and_chop_longest_common_prefix : equal:('a -> 'a -> bool) -> first:'a list -> second:'a list -> 'a longest_common_prefix_result (** Returns the longest list that, with respect to the provided equality function, is a prefix of both of the given lists. The input lists, each with such longest common prefix removed, are also returned. *) end module Option : sig type 'a t = 'a option val print : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit end module Array : sig val exists2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool (** Same as [Array.exists2] from the standard library. *) val for_alli : (int -> 'a -> bool) -> 'a array -> bool (** Same as [Array.for_all] from the standard library, but the function is applied with the index of the element as first argument, and the element itself as second argument. *) val all_somes : 'a option array -> 'a array option end module String : sig include module type of String module Set : Set.S with type elt = string module Map : Map.S with type key = string module Tbl : Hashtbl.S with type key = string val print : Format.formatter -> t -> unit val for_all : (char -> bool) -> t -> bool end external compare : 'a -> 'a -> int = "%compare" end val find_in_path: string list -> string -> string (* Search a file in a list of directories. *) val find_in_path_rel: string list -> string -> string (* Search a relative file in a list of directories. *) val find_in_path_uncap: string list -> string -> string (* Same, but search also for uncapitalized name, i.e. if name is Foo.ml, allow /path/Foo.ml and /path/foo.ml to match. *) val remove_file: string -> unit (* Delete the given file if it exists. Never raise an error. *) val expand_directory: string -> string -> string (* [expand_directory alt file] eventually expands a [+] at the beginning of file into [alt] (an alternate root directory) *) val split_path_contents: ?sep:char -> string -> string list (* [split_path_contents ?sep s] interprets [s] as the value of a "PATH"-like variable and returns the corresponding list of directories. [s] is split using the platform-specific delimiter, or [~sep] if it is passed. Returns the empty list if [s] is empty. *) val create_hashtable: int -> ('a * 'b) list -> ('a, 'b) Hashtbl.t (* Create a hashtable of the given size and fills it with the given bindings. *) val copy_file: in_channel -> out_channel -> unit (* [copy_file ic oc] reads the contents of file [ic] and copies them to [oc]. It stops when encountering EOF on [ic]. *) val copy_file_chunk: in_channel -> out_channel -> int -> unit (* [copy_file_chunk ic oc n] reads [n] bytes from [ic] and copies them to [oc]. It raises [End_of_file] when encountering EOF on [ic]. *) val string_of_file: in_channel -> string (* [string_of_file ic] reads the contents of file [ic] and copies them to a string. It stops when encountering EOF on [ic]. *) val output_to_file_via_temporary: ?mode:open_flag list -> string -> (string -> out_channel -> 'a) -> 'a (* Produce output in temporary file, then rename it (as atomically as possible) to the desired output file name. [output_to_file_via_temporary filename fn] opens a temporary file which is passed to [fn] (name + output channel). When [fn] returns, the channel is closed and the temporary file is renamed to [filename]. *) (** Open the given [filename] for writing (in binary mode), pass the [out_channel] to the given function, then close the channel. If the function raises an exception then [filename] will be removed. *) val protect_writing_to_file : filename:string -> f:(out_channel -> 'a) -> 'a val log2: int -> int (* [log2 n] returns [s] such that [n = 1 lsl s] if [n] is a power of 2*) val align: int -> int -> int (* [align n a] rounds [n] upwards to a multiple of [a] (a power of 2). *) val no_overflow_add: int -> int -> bool (* [no_overflow_add n1 n2] returns [true] if the computation of [n1 + n2] does not overflow. *) val no_overflow_sub: int -> int -> bool (* [no_overflow_sub n1 n2] returns [true] if the computation of [n1 - n2] does not overflow. *) val no_overflow_mul: int -> int -> bool (* [no_overflow_mul n1 n2] returns [true] if the computation of [n1 * n2] does not overflow. *) val no_overflow_lsl: int -> int -> bool (* [no_overflow_lsl n k] returns [true] if the computation of [n lsl k] does not overflow. *) module Int_literal_converter : sig val int : string -> int val int32 : string -> int32 val int64 : string -> int64 val nativeint : string -> nativeint end val chop_extensions: string -> string (* Return the given file name without its extensions. The extensions is the longest suffix starting with a period and not including a directory separator, [.xyz.uvw] for instance. Return the given name if it does not contain an extension. *) val search_substring: string -> string -> int -> int (* [search_substring pat str start] returns the position of the first occurrence of string [pat] in string [str]. Search starts at offset [start] in [str]. Raise [Not_found] if [pat] does not occur. *) val replace_substring: before:string -> after:string -> string -> string (* [replace_substring ~before ~after str] replaces all occurrences of [before] with [after] in [str] and returns the resulting string. *) val rev_split_words: string -> string list (* [rev_split_words s] splits [s] in blank-separated words, and returns the list of words in reverse order. *) val get_ref: 'a list ref -> 'a list (* [get_ref lr] returns the content of the list reference [lr] and reset its content to the empty list. *) val set_or_ignore : ('a -> 'b option) -> 'b option ref -> 'a -> unit (* [set_or_ignore f opt x] sets [opt] to [f x] if it returns [Some _], or leaves it unmodified if it returns [None]. *) val fst3: 'a * 'b * 'c -> 'a val snd3: 'a * 'b * 'c -> 'b val thd3: 'a * 'b * 'c -> 'c val fst4: 'a * 'b * 'c * 'd -> 'a val snd4: 'a * 'b * 'c * 'd -> 'b val thd4: 'a * 'b * 'c * 'd -> 'c val for4: 'a * 'b * 'c * 'd -> 'd module LongString : sig type t = bytes array val create : int -> t val length : t -> int val get : t -> int -> char val set : t -> int -> char -> unit val blit : t -> int -> t -> int -> int -> unit val blit_string : string -> int -> t -> int -> int -> unit val output : out_channel -> t -> int -> int -> unit val input_bytes_into : t -> in_channel -> int -> unit val input_bytes : in_channel -> int -> t end val edit_distance : string -> string -> int -> int option (** [edit_distance a b cutoff] computes the edit distance between strings [a] and [b]. To help efficiency, it uses a cutoff: if the distance [d] is smaller than [cutoff], it returns [Some d], else [None]. The distance algorithm currently used is Damerau-Levenshtein: it computes the number of insertion, deletion, substitution of letters, or swapping of adjacent letters to go from one word to the other. The particular algorithm may change in the future. *) val spellcheck : string list -> string -> string list (** [spellcheck env name] takes a list of names [env] that exist in the current environment and an erroneous [name], and returns a list of suggestions taken from [env], that are close enough to [name] that it may be a typo for one of them. *) val did_you_mean : Format.formatter -> (unit -> string list) -> unit (** [did_you_mean ppf get_choices] hints that the user may have meant one of the option returned by calling [get_choices]. It does nothing if the returned list is empty. The [unit -> ...] thunking is meant to delay any potentially-slow computation (typically computing edit-distance with many things from the current environment) to when the hint message is to be printed. You should print an understandable error message before calling [did_you_mean], so that users get a clear notification of the failure even if producing the hint is slow. *) val cut_at : string -> char -> string * string (** [String.cut_at s c] returns a pair containing the sub-string before the first occurrence of [c] in [s], and the sub-string after the first occurrence of [c] in [s]. [let (before, after) = String.cut_at s c in before ^ String.make 1 c ^ after] is the identity if [s] contains [c]. Raise [Not_found] if the character does not appear in the string @since 4.01 *) val ordinal_suffix : int -> string (** [ordinal_suffix n] is the appropriate suffix to append to the numeral [n] as an ordinal number: [1] -> ["st"], [2] -> ["nd"], [3] -> ["rd"], [4] -> ["th"], and so on. Handles larger numbers (e.g., [42] -> ["nd"]) and the numbers 11--13 (which all get ["th"]) correctly. *) (* Color handling *) module Color : sig type color = | Black | Red | Green | Yellow | Blue | Magenta | Cyan | White ;; type style = | FG of color (* foreground *) | BG of color (* background *) | Bold | Reset type Format.stag += Style of style list val ansi_of_style_l : style list -> string (* ANSI escape sequence for the given style *) type styles = { error: style list; warning: style list; loc: style list; } val default_styles: styles val get_styles: unit -> styles val set_styles: styles -> unit type setting = Auto | Always | Never val default_setting : setting val setup : setting option -> unit (* [setup opt] will enable or disable color handling on standard formatters according to the value of color setting [opt]. Only the first call to this function has an effect. *) val set_color_tag_handling : Format.formatter -> unit (* adds functions to support color tags to the given formatter. *) end (* See the -error-style option *) module Error_style : sig type setting = | Contextual | Short val default_setting : setting end val normalise_eol : string -> string (** [normalise_eol s] returns a fresh copy of [s] with any '\r' characters removed. Intended for pre-processing text which will subsequently be printed on a channel which performs EOL transformations (i.e. Windows) *) val delete_eol_spaces : string -> string (** [delete_eol_spaces s] returns a fresh copy of [s] with any end of line spaces removed. Intended to normalize the output of the toplevel for tests. *) val pp_two_columns : ?sep:string -> ?max_lines:int -> Format.formatter -> (string * string) list -> unit (** [pp_two_columns ?sep ?max_lines ppf l] prints the lines in [l] as two columns separated by [sep] ("|" by default). [max_lines] can be used to indicate a maximum number of lines to print -- an ellipsis gets inserted at the middle if the input has too many lines. Example: {v pp_two_columns ~max_lines:3 Format.std_formatter [ "abc", "hello"; "def", "zzz"; "a" , "bllbl"; "bb" , "dddddd"; ] v} prints {v abc | hello ... bb | dddddd v} *) (** configuration variables *) val show_config_and_exit : unit -> unit val show_config_variable_and_exit : string -> unit val get_build_path_prefix_map: unit -> Build_path_prefix_map.map option (** Returns the map encoded in the [BUILD_PATH_PREFIX_MAP] environment variable. *) val debug_prefix_map_flags: unit -> string list (** Returns the list of [--debug-prefix-map] flags to be passed to the assembler, built from the [BUILD_PATH_PREFIX_MAP] environment variable. *) val print_if : Format.formatter -> bool ref -> (Format.formatter -> 'a -> unit) -> 'a -> 'a (** [print_if ppf flag fmt x] prints [x] with [fmt] on [ppf] if [b] is true. *) type filepath = string type modname = string type crcs = (modname * Digest.t option) list type alerts = string Stdlib.String.Map.t module Magic_number : sig (** a typical magic number is "Caml1999I011"; it is formed of an alphanumeric prefix, here Caml1990I, followed by a version, here 011. The prefix identifies the kind of the versioned data: here the I indicates that it is the magic number for .cmi files. All magic numbers have the same byte length, [magic_length], and this is important for users as it gives them the number of bytes to read to obtain the byte sequence that should be a magic number. Typical user code will look like: {[ let ic = open_in_bin path in let magic = try really_input_string ic Magic_number.magic_length with End_of_file -> ... in match Magic_number.parse magic with | Error parse_error -> ... | Ok info -> ... ]} A given compiler version expects one specific version for each kind of object file, and will fail if given an unsupported version. Because versions grow monotonically, you can compare the parsed version with the expected "current version" for a kind, to tell whether the wrong-magic object file comes from the past or from the future. An example of code block that expects the "currently supported version" of a given kind of magic numbers, here [Cmxa], is as follows: {[ let ic = open_in_bin path in begin try Magic_number.(expect_current Cmxa (get_info ic)) with | Parse_error error -> ... | Unexpected error -> ... end; ... ]} Parse errors distinguish inputs that are [Not_a_magic_number str], which are likely to come from the file being completely different, and [Truncated str], raised by headers that are the (possibly empty) prefix of a valid magic number. Unexpected errors correspond to valid magic numbers that are not the one expected, either because it corresponds to a different kind, or to a newer or older version. The helper functions [explain_parse_error] and [explain_unexpected_error] will generate a textual explanation of each error, for use in error messages. @since 4.11.0 *) type native_obj_config = { flambda : bool; } (** native object files have a format and magic number that depend on certain native-compiler configuration parameters. This configuration space is expressed by the [native_obj_config] type. *) val native_obj_config : native_obj_config (** the native object file configuration of the active/configured compiler. *) type version = int type kind = | Exec | Cmi | Cmo | Cma | Cmx of native_obj_config | Cmxa of native_obj_config | Cmxs | Cmt | Ast_impl | Ast_intf type info = { kind: kind; version: version; (** Note: some versions of the compiler use the same [version] suffix for all kinds, but others use different versions counters for different kinds. We may only assume that versions are growing monotonically (not necessarily always by one) between compiler versions. *) } type raw = string (** the type of raw magic numbers, such as "Caml1999A027" for the .cma files of OCaml 4.10 *) (** {3 Parsing magic numbers} *) type parse_error = | Truncated of string | Not_a_magic_number of string val explain_parse_error : kind option -> parse_error -> string (** Produces an explanation for a parse error. If no kind is provided, we use an unspecific formulation suggesting that any compiler-produced object file would have been satisfying. *) val parse : raw -> (info, parse_error) result (** Parses a raw magic number *) val read_info : in_channel -> (info, parse_error) result (** Read a raw magic number from an input channel. If the data read [str] is not a valid magic number, it can be recovered from the [Truncated str | Not_a_magic_number str] payload of the [Error parse_error] case. If parsing succeeds with an [Ok info] result, we know that exactly [magic_length] bytes have been consumed from the input_channel. If you also wish to enforce that the magic number is at the current version, see {!read_current_info} below. *) val magic_length : int (** all magic numbers take the same number of bytes *) (** {3 Checking that magic numbers are current} *) type 'a unexpected = { expected : 'a; actual : 'a } type unexpected_error = | Kind of kind unexpected | Version of kind * version unexpected val check_current : kind -> info -> (unit, unexpected_error) result (** [check_current kind info] checks that the provided magic [info] is the current version of [kind]'s magic header. *) val explain_unexpected_error : unexpected_error -> string (** Provides an explanation of the [unexpected_error]. *) type error = | Parse_error of parse_error | Unexpected_error of unexpected_error val read_current_info : expected_kind:kind option -> in_channel -> (info, error) result (** Read a magic number as [read_info], and check that it is the current version as its kind. If the [expected_kind] argument is [None], any kind is accepted. *) (** {3 Information on magic numbers} *) val string_of_kind : kind -> string (** a user-printable string for a kind, eg. "exec" or "cmo", to use in error messages. *) val human_name_of_kind : kind -> string (** a user-meaningful name for a kind, eg. "executable file" or "bytecode object file", to use in error messages. *) val current_raw : kind -> raw (** the current magic number of each kind *) val current_version : kind -> version (** the current version of each kind *) (** {3 Raw representations} Mainly for internal usage and testing. *) type raw_kind = string (** the type of raw magic numbers kinds, such as "Caml1999A" for .cma files *) val parse_kind : raw_kind -> kind option (** parse a raw kind into a kind *) val raw_kind : kind -> raw_kind (** the current raw representation of a kind. In some cases the raw representation of a kind has changed over compiler versions, so other files of the same kind may have different raw kinds. Note that all currently known cases are parsed correctly by [parse_kind]. *) val raw : info -> raw (** A valid raw representation of the magic number. Due to past and future changes in the string representation of magic numbers, we cannot guarantee that the raw strings returned for past and future versions actually match the expectations of those compilers. The representation is accurate for current versions, and it is correctly parsed back into the desired version by the parsing functions above. *) (**/**) val all_kinds : kind list end
(**************************************************************************) (* *) (* OCaml *) (* *) (* Xavier Leroy, projet Cristal, INRIA Rocquencourt *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************)
roll_storage.ml
open Misc type error += | Consume_roll_change (* `Permanent *) | No_roll_for_delegate (* `Permanent *) | No_roll_snapshot_for_cycle of Cycle_repr.t (* `Permanent *) | Unregistered_delegate of Signature.Public_key_hash.t (* `Permanent *) let () = let open Data_encoding in (* Consume roll change *) register_error_kind `Permanent ~id:"contract.manager.consume_roll_change" ~title:"Consume roll change" ~description:"Change is not enough to consume a roll." ~pp:(fun ppf () -> Format.fprintf ppf "Not enough change to consume a roll.") empty (function Consume_roll_change -> Some () | _ -> None) (fun () -> Consume_roll_change) ; (* No roll for delegate *) register_error_kind `Permanent ~id:"contract.manager.no_roll_for_delegate" ~title:"No roll for delegate" ~description:"Delegate has no roll." ~pp:(fun ppf () -> Format.fprintf ppf "Delegate has no roll.") empty (function No_roll_for_delegate -> Some () | _ -> None) (fun () -> No_roll_for_delegate) ; (* No roll snapshot for cycle *) register_error_kind `Permanent ~id:"contract.manager.no_roll_snapshot_for_cycle" ~title:"No roll snapshot for cycle" ~description:"A snapshot of the rolls distribution does not exist for this cycle." ~pp:(fun ppf c -> Format.fprintf ppf "A snapshot of the rolls distribution does not exist for cycle %a" Cycle_repr.pp c) (obj1 (req "cycle" Cycle_repr.encoding)) (function No_roll_snapshot_for_cycle c-> Some c | _ -> None) (fun c -> No_roll_snapshot_for_cycle c) ; (* Unregistered delegate *) register_error_kind `Permanent ~id:"contract.manager.unregistered_delegate" ~title:"Unregistered delegate" ~description:"A contract cannot be delegated to an unregistered delegate" ~pp:(fun ppf k-> Format.fprintf ppf "The provided public key (with hash %a) is \ \ not registered as valid delegate key." Signature.Public_key_hash.pp k) (obj1 (req "hash" Signature.Public_key_hash.encoding)) (function Unregistered_delegate k -> Some k | _ -> None) (fun k -> Unregistered_delegate k) let get_contract_delegate c contract = Storage.Contract.Delegate.get_option c contract let delegate_pubkey ctxt delegate = Storage.Contract.Manager.get_option ctxt (Contract_repr.implicit_contract delegate) >>=? function | None | Some (Manager_repr.Hash _) -> fail (Unregistered_delegate delegate) | Some (Manager_repr.Public_key pk) -> return pk let clear_cycle c cycle = Storage.Roll.Snapshot_for_cycle.get c cycle >>=? fun index -> Storage.Roll.Snapshot_for_cycle.delete c cycle >>=? fun c -> Storage.Roll.Last_for_snapshot.delete (c, cycle) index >>=? fun c -> Storage.Roll.Owner.delete_snapshot c (cycle, index) >>= fun c -> return c let fold ctxt ~f init = Storage.Roll.Next.get ctxt >>=? fun last -> let rec loop ctxt roll acc = acc >>=? fun acc -> if Roll_repr.(roll = last) then return acc else Storage.Roll.Owner.get_option ctxt roll >>=? function | None -> loop ctxt (Roll_repr.succ roll) (return acc) | Some delegate -> loop ctxt (Roll_repr.succ roll) (f roll delegate acc) in loop ctxt Roll_repr.first (return init) let snapshot_rolls_for_cycle ctxt cycle = Storage.Roll.Snapshot_for_cycle.get ctxt cycle >>=? fun index -> Storage.Roll.Snapshot_for_cycle.set ctxt cycle (index + 1) >>=? fun ctxt -> Storage.Roll.Owner.snapshot ctxt (cycle, index) >>=? fun ctxt -> Storage.Roll.Next.get ctxt >>=? fun last -> Storage.Roll.Last_for_snapshot.init (ctxt, cycle) index last >>=? fun ctxt -> return ctxt let freeze_rolls_for_cycle ctxt cycle = Storage.Roll.Snapshot_for_cycle.get ctxt cycle >>=? fun max_index -> Storage.Seed.For_cycle.get ctxt cycle >>=? fun seed -> let rd = Seed_repr.initialize_new seed [MBytes.of_string "roll_snapshot"] in let seq = Seed_repr.sequence rd 0l in let selected_index = Seed_repr.take_int32 seq (Int32.of_int max_index) |> fst |> Int32.to_int in Storage.Roll.Snapshot_for_cycle.set ctxt cycle selected_index >>=? fun ctxt -> fold_left_s (fun ctxt index -> if Compare.Int.(index = selected_index) then return ctxt else Storage.Roll.Owner.delete_snapshot ctxt (cycle, index) >>= fun ctxt -> Storage.Roll.Last_for_snapshot.delete (ctxt, cycle) index >>=? fun ctxt -> return ctxt ) ctxt Misc.(0 --> (max_index - 1)) >>=? fun ctxt -> return ctxt (* Roll selection *) module Random = struct let int32_to_bytes i = let b = MBytes.create 4 in MBytes.set_int32 b 0 i; b let level_random seed use level = let position = level.Level_repr.cycle_position in Seed_repr.initialize_new seed [MBytes.of_string ("level "^use^":"); int32_to_bytes position] let owner c kind level offset = let cycle = level.Level_repr.cycle in Seed_storage.for_cycle c cycle >>=? fun random_seed -> let rd = level_random random_seed kind level in let sequence = Seed_repr.sequence rd (Int32.of_int offset) in Storage.Roll.Snapshot_for_cycle.get c cycle >>=? fun index -> Storage.Roll.Last_for_snapshot.get (c, cycle) index >>=? fun bound -> let rec loop sequence = let roll, sequence = Roll_repr.random sequence ~bound in Storage.Roll.Owner.Snapshot.get_option c ((cycle, index), roll) >>=? function | None -> loop sequence | Some delegate -> return delegate in Storage.Roll.Owner.snapshot_exists c (cycle, index) >>= fun snapshot_exists -> fail_unless snapshot_exists (No_roll_snapshot_for_cycle cycle) >>=? fun () -> loop sequence end let baking_rights_owner c level ~priority = Random.owner c "baking" level priority let endorsement_rights_owner c level ~slot = Random.owner c "endorsement" level slot let traverse_rolls ctxt head = let rec loop acc roll = Storage.Roll.Successor.get_option ctxt roll >>=? function | None -> return (List.rev acc) | Some next -> loop (next :: acc) next in loop [head] head let get_rolls ctxt delegate = Storage.Roll.Delegate_roll_list.get_option ctxt delegate >>=? function | None -> return_nil | Some head_roll -> traverse_rolls ctxt head_roll let count_rolls ctxt delegate = Storage.Roll.Delegate_roll_list.get_option ctxt delegate >>=? function | None -> return 0 | Some head_roll -> let rec loop acc roll = Storage.Roll.Successor.get_option ctxt roll >>=? function | None -> return acc | Some next -> loop (succ acc) next in loop 1 head_roll let get_change c delegate = Storage.Roll.Delegate_change.get_option c delegate >>=? function | None -> return Tez_repr.zero | Some change -> return change module Delegate = struct let fresh_roll c = Storage.Roll.Next.get c >>=? fun roll -> Storage.Roll.Next.set c (Roll_repr.succ roll) >>=? fun c -> return (roll, c) let get_limbo_roll c = Storage.Roll.Limbo.get_option c >>=? function | None -> fresh_roll c >>=? fun (roll, c) -> Storage.Roll.Limbo.init c roll >>=? fun c -> return (roll, c) | Some roll -> return (roll, c) let consume_roll_change c delegate = let tokens_per_roll = Constants_storage.tokens_per_roll c in Storage.Roll.Delegate_change.get c delegate >>=? fun change -> trace Consume_roll_change (Lwt.return Tez_repr.(change -? tokens_per_roll)) >>=? fun new_change -> Storage.Roll.Delegate_change.set c delegate new_change let recover_roll_change c delegate = let tokens_per_roll = Constants_storage.tokens_per_roll c in Storage.Roll.Delegate_change.get c delegate >>=? fun change -> Lwt.return Tez_repr.(change +? tokens_per_roll) >>=? fun new_change -> Storage.Roll.Delegate_change.set c delegate new_change let pop_roll_from_delegate c delegate = recover_roll_change c delegate >>=? fun c -> (* beginning: delegate : roll -> successor_roll -> ... limbo : limbo_head -> ... *) Storage.Roll.Limbo.get_option c >>=? fun limbo_head -> Storage.Roll.Delegate_roll_list.get_option c delegate >>=? function | None -> fail No_roll_for_delegate | Some roll -> Storage.Roll.Owner.delete c roll >>=? fun c -> Storage.Roll.Successor.get_option c roll >>=? fun successor_roll -> Storage.Roll.Delegate_roll_list.set_option c delegate successor_roll >>= fun c -> (* delegate : successor_roll -> ... roll ------^ limbo : limbo_head -> ... *) Storage.Roll.Successor.set_option c roll limbo_head >>= fun c -> (* delegate : successor_roll -> ... roll ------v limbo : limbo_head -> ... *) Storage.Roll.Limbo.init_set c roll >>= fun c -> (* delegate : successor_roll -> ... limbo : roll -> limbo_head -> ... *) return (roll, c) let create_roll_in_delegate c delegate delegate_pk = consume_roll_change c delegate >>=? fun c -> (* beginning: delegate : delegate_head -> ... limbo : roll -> limbo_successor -> ... *) Storage.Roll.Delegate_roll_list.get_option c delegate >>=? fun delegate_head -> get_limbo_roll c >>=? fun (roll, c) -> Storage.Roll.Owner.init c roll delegate_pk >>=? fun c -> Storage.Roll.Successor.get_option c roll >>=? fun limbo_successor -> Storage.Roll.Limbo.set_option c limbo_successor >>= fun c -> (* delegate : delegate_head -> ... roll ------v limbo : limbo_successor -> ... *) Storage.Roll.Successor.set_option c roll delegate_head >>= fun c -> (* delegate : delegate_head -> ... roll ------^ limbo : limbo_successor -> ... *) Storage.Roll.Delegate_roll_list.init_set c delegate roll >>= fun c -> (* delegate : roll -> delegate_head -> ... limbo : limbo_successor -> ... *) return c let ensure_inited c delegate = Storage.Roll.Delegate_change.mem c delegate >>= function | true -> return c | false -> Storage.Roll.Delegate_change.init c delegate Tez_repr.zero let is_inactive c delegate = Storage.Contract.Inactive_delegate.mem c (Contract_repr.implicit_contract delegate) >>= fun inactive -> if inactive then return inactive else Storage.Contract.Delegate_desactivation.get_option c (Contract_repr.implicit_contract delegate) >>=? function | Some last_active_cycle -> let { Level_repr.cycle = current_cycle } = Raw_context.current_level c in return Cycle_repr.(last_active_cycle < current_cycle) | None -> (* This case is only when called from `set_active`, when creating a contract. *) return_false let add_amount c delegate amount = ensure_inited c delegate >>=? fun c -> let tokens_per_roll = Constants_storage.tokens_per_roll c in Storage.Roll.Delegate_change.get c delegate >>=? fun change -> Lwt.return Tez_repr.(amount +? change) >>=? fun change -> Storage.Roll.Delegate_change.set c delegate change >>=? fun c -> delegate_pubkey c delegate >>=? fun delegate_pk -> let rec loop c change = if Tez_repr.(change < tokens_per_roll) then return c else Lwt.return Tez_repr.(change -? tokens_per_roll) >>=? fun change -> create_roll_in_delegate c delegate delegate_pk >>=? fun c -> loop c change in is_inactive c delegate >>=? fun inactive -> if inactive then return c else loop c change >>=? fun c -> Storage.Roll.Delegate_roll_list.get_option c delegate >>=? fun rolls -> match rolls with | None -> return c | Some _ -> Storage.Active_delegates_with_rolls.add c delegate >>= fun c -> return c let remove_amount c delegate amount = let tokens_per_roll = Constants_storage.tokens_per_roll c in let rec loop c change = if Tez_repr.(amount <= change) then return (c, change) else pop_roll_from_delegate c delegate >>=? fun (_, c) -> Lwt.return Tez_repr.(change +? tokens_per_roll) >>=? fun change -> loop c change in Storage.Roll.Delegate_change.get c delegate >>=? fun change -> is_inactive c delegate >>=? fun inactive -> begin if inactive then return (c, change) else loop c change >>=? fun (c, change) -> Storage.Roll.Delegate_roll_list.get_option c delegate >>=? fun rolls -> match rolls with | None -> Storage.Active_delegates_with_rolls.del c delegate >>= fun c -> return (c, change) | Some _ -> return (c, change) end >>=? fun (c, change) -> Lwt.return Tez_repr.(change -? amount) >>=? fun change -> Storage.Roll.Delegate_change.set c delegate change let set_inactive ctxt delegate = ensure_inited ctxt delegate >>=? fun ctxt -> let tokens_per_roll = Constants_storage.tokens_per_roll ctxt in Storage.Roll.Delegate_change.get ctxt delegate >>=? fun change -> Storage.Contract.Inactive_delegate.add ctxt (Contract_repr.implicit_contract delegate) >>= fun ctxt -> Storage.Active_delegates_with_rolls.del ctxt delegate >>= fun ctxt -> let rec loop ctxt change = Storage.Roll.Delegate_roll_list.get_option ctxt delegate >>=? function | None -> return (ctxt, change) | Some _roll -> pop_roll_from_delegate ctxt delegate >>=? fun (_, ctxt) -> Lwt.return Tez_repr.(change +? tokens_per_roll) >>=? fun change -> loop ctxt change in loop ctxt change >>=? fun (ctxt, change) -> Storage.Roll.Delegate_change.set ctxt delegate change >>=? fun ctxt -> return ctxt let set_active ctxt delegate = is_inactive ctxt delegate >>=? fun inactive -> let current_cycle = (Raw_context.current_level ctxt).cycle in let preserved_cycles = Constants_storage.preserved_cycles ctxt in (* When the delegate is new or inactive, she will become active in `1+preserved_cycles`, and we allow `preserved_cycles` for the delegate to start baking. When the delegate is active, we only give her at least `preserved_cycles` after the current cycle before to be deactivated. *) Storage.Contract.Delegate_desactivation.get_option ctxt (Contract_repr.implicit_contract delegate) >>=? fun current_expiration -> let expiration = match current_expiration with | None -> Cycle_repr.add current_cycle (1+2*preserved_cycles) | Some current_expiration -> let delay = if inactive then (1+2*preserved_cycles) else 1+preserved_cycles in let updated = Cycle_repr.add current_cycle delay in Cycle_repr.max current_expiration updated in Storage.Contract.Delegate_desactivation.init_set ctxt (Contract_repr.implicit_contract delegate) expiration >>= fun ctxt -> if not inactive then return ctxt else begin ensure_inited ctxt delegate >>=? fun ctxt -> let tokens_per_roll = Constants_storage.tokens_per_roll ctxt in Storage.Roll.Delegate_change.get ctxt delegate >>=? fun change -> Storage.Contract.Inactive_delegate.del ctxt (Contract_repr.implicit_contract delegate) >>= fun ctxt -> delegate_pubkey ctxt delegate >>=? fun delegate_pk -> let rec loop ctxt change = if Tez_repr.(change < tokens_per_roll) then return ctxt else Lwt.return Tez_repr.(change -? tokens_per_roll) >>=? fun change -> create_roll_in_delegate ctxt delegate delegate_pk >>=? fun ctxt -> loop ctxt change in loop ctxt change >>=? fun ctxt -> Storage.Roll.Delegate_roll_list.get_option ctxt delegate >>=? fun rolls -> match rolls with | None -> return ctxt | Some _ -> Storage.Active_delegates_with_rolls.add ctxt delegate >>= fun ctxt -> return ctxt end end module Contract = struct let add_amount c contract amount = get_contract_delegate c contract >>=? function | None -> return c | Some delegate -> Delegate.add_amount c delegate amount let remove_amount c contract amount = get_contract_delegate c contract >>=? function | None -> return c | Some delegate -> Delegate.remove_amount c delegate amount end let init ctxt = Storage.Roll.Next.init ctxt Roll_repr.first let init_first_cycles ctxt = let preserved = Constants_storage.preserved_cycles ctxt in (* Precompute rolls for cycle (0 --> preserved_cycles) *) List.fold_left (fun ctxt c -> ctxt >>=? fun ctxt -> let cycle = Cycle_repr.of_int32_exn (Int32.of_int c) in Storage.Roll.Snapshot_for_cycle.init ctxt cycle 0 >>=? fun ctxt -> snapshot_rolls_for_cycle ctxt cycle >>=? fun ctxt -> freeze_rolls_for_cycle ctxt cycle) (return ctxt) (0 --> preserved) >>=? fun ctxt -> let cycle = Cycle_repr.of_int32_exn (Int32.of_int (preserved + 1)) in (* Precomputed a snapshot for cycle (preserved_cycles + 1) *) Storage.Roll.Snapshot_for_cycle.init ctxt cycle 0 >>=? fun ctxt -> snapshot_rolls_for_cycle ctxt cycle >>=? fun ctxt -> (* Prepare storage for storing snapshots for cycle (preserved_cycles+2) *) let cycle = Cycle_repr.of_int32_exn (Int32.of_int (preserved + 2)) in Storage.Roll.Snapshot_for_cycle.init ctxt cycle 0 >>=? fun ctxt -> return ctxt let snapshot_rolls ctxt = let current_level = Raw_context.current_level ctxt in let preserved = Constants_storage.preserved_cycles ctxt in let cycle = Cycle_repr.add current_level.cycle (preserved+2) in snapshot_rolls_for_cycle ctxt cycle let cycle_end ctxt last_cycle = let preserved = Constants_storage.preserved_cycles ctxt in begin match Cycle_repr.sub last_cycle preserved with | None -> return ctxt | Some cleared_cycle -> clear_cycle ctxt cleared_cycle end >>=? fun ctxt -> let frozen_roll_cycle = Cycle_repr.add last_cycle (preserved+1) in freeze_rolls_for_cycle ctxt frozen_roll_cycle >>=? fun ctxt -> Storage.Roll.Snapshot_for_cycle.init ctxt (Cycle_repr.succ (Cycle_repr.succ frozen_roll_cycle)) 0 >>=? fun ctxt -> return ctxt let update_tokens_per_roll ctxt new_tokens_per_roll = let constants = Raw_context.constants ctxt in let old_tokens_per_roll = constants.tokens_per_roll in Raw_context.patch_constants ctxt begin fun constants -> { constants with Constants_repr.tokens_per_roll = new_tokens_per_roll } end >>= fun ctxt -> let decrease = Tez_repr.(new_tokens_per_roll < old_tokens_per_roll) in begin if decrease then Lwt.return Tez_repr.(old_tokens_per_roll -? new_tokens_per_roll) else Lwt.return Tez_repr.(new_tokens_per_roll -? old_tokens_per_roll) end >>=? fun abs_diff -> Storage.Delegates.fold ctxt (Ok ctxt) begin fun pkh ctxt -> Lwt.return ctxt >>=? fun ctxt -> count_rolls ctxt pkh >>=? fun rolls -> Lwt.return Tez_repr.(abs_diff *? Int64.of_int rolls) >>=? fun amount -> if decrease then Delegate.add_amount ctxt pkh amount else Delegate.remove_amount ctxt pkh amount end
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
dune
(cram (deps (glob_files bin/*.exe)))
discover.mli
rpc_server.ml
open Async open Amqp_client_async let handler (h, s) = Log.Global.info "Recieved request: %s" s; return (h, s) let start = Connection.connect ~id:"fugmann" "localhost" >>= fun connection -> Log.Global.info "Connection started"; Connection.open_channel ~id:"test" Channel.no_confirm connection >>= fun channel -> Log.Global.info "Channel opened"; Queue.declare channel ~arguments:[Rpc.Server.queue_argument] "rpc.server.echo_reply" >>= fun queue -> Rpc.Server.start channel queue handler >>= fun _server -> Log.Global.info "Listening for requsts"; return () let _ = Scheduler.go ()
search.ml
(** The "0install search" command *) open Options open Zeroinstall.General open Support open Support.Common module Q = Support.Qdom module U = Support.Utils module Msg = Support.Qdom.Empty let handle options flags args = let config = options.config in let tools = options.tools in options.tools#set_use_gui `No; (* There's no GUI for searches; using it just disabled the progress indicator. *) Support.Argparse.iter_options flags (function | #common_option as o -> Common_options.process_common_option options o ); if args = [] then raise (Support.Argparse.Usage_error 1); match config.mirror with | None -> Safe_exn.failf "No mirror configured; search is unavailable" | Some mirror -> let url = mirror ^ "/search/?q=" ^ Zeroinstall.Http.escape (String.concat " " args) in log_info "Fetching %s..." url; Lwt_main.run begin U.with_switch @@ fun switch -> let downloader = tools#download_pool#with_monitor tools#ui#watcher#monitor in Zeroinstall.Downloader.download downloader ~switch url >>= function | `Aborted_by_user -> Lwt.return () | `Network_failure msg -> Safe_exn.failf "%s" msg | `Tmpfile path -> let results = U.read_file config.system path in Lwt_switch.turn_off switch >>= fun () -> let root = `String (0, results) |> Xmlm.make_input |> Q.parse_input (Some url) in Msg.check_tag "results" root; let print fmt = Format.fprintf options.stdout (fmt ^^ "@.") in let first = ref true in root |> Msg.iter ~name:"result" (fun child -> if !first then first := false else print ""; print "%s" (Msg.get_attribute "uri" child); let score = Msg.get_attribute "score" child in let summary = ref "" in child |> Msg.iter ~name:"summary" (fun elem -> summary := elem.Q.last_text_inside ); print " %s - %s [%s%%]" (Msg.get_attribute "name" child) !summary score ); Lwt.return () end
(* Copyright (C) 2013, Thomas Leonard * See the README file for details, or visit http://0install.net. *)
local_store.mli
(** This module provides some facilities for creating references (and hash tables) which can easily be snapshoted and restored to an arbitrary version. It is used throughout the frontend (read: typechecker), to register all (well, hopefully) the global state. Thus making it easy for tools like Merlin to go back and forth typechecking different files. *) (** {1 Creators} *) val s_ref : 'a -> 'a ref (** Similar to {!val:Stdlib.ref}, except the allocated reference is registered into the store. *) val s_table : ('a -> 'b) -> 'a -> 'b ref (** Used to register hash tables. Those also need to be placed into refs to be easily swapped out, but one can't just "snapshot" the initial value to create fresh instances, so instead an initializer is required. Use it like this: {[ let my_table = s_table Hashtbl.create 42 ]} *) (** {1 State management} Note: all the following functions are currently unused inside the compiler codebase. Merlin is their only user at the moment. *) type store val fresh : unit -> store (** Returns a fresh instance of the store. The first time this function is called, it snapshots the value of all the registered references, later calls to [fresh] will return instances initialized to those values. *) val with_store : store -> (unit -> 'a) -> 'a (** [with_store s f] resets all the registered references to the value they have in [s] for the run of [f]. If [f] updates any of the registered refs, [s] is updated to remember those changes. *) val reset : unit -> unit (** Resets all the references to the initial snapshot (i.e. to the same values that new instances start with). *) val is_bound : unit -> bool (** Returns [true] when a store is active (i.e. when called from the callback passed to {!with_store}), [false] otherwise. *)
(**************************************************************************) (* *) (* OCaml *) (* *) (* Frederic Bour, Tarides *) (* Thomas Refis, Tarides *) (* *) (* Copyright 2020 Tarides *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************)
dune
(library (name cbor) (public_name cbor) (wrapped false) (libraries ocplib-endian))
array_dom.mli
type map_info = { bi_ind_ty : Ground.Ty.t; bi_val_ty : Ground.Ty.t; a_val_ty : Ground.Ty.t; f_arity : int; } type t = { reads : Node.S.t; map_parents : map_info Ground.M.t } val equal : t -> t -> bool val pp : Format.formatter -> t -> unit val show : t -> string val is_singleton : 'a -> 'b -> 'c option val key : t Dom.Kind.t val inter : 'a -> t -> t -> t option val set_dom : Egraph.wt -> Node.t -> t -> unit val upd_dom : Egraph.wt -> Node.t -> t -> unit val register_hook_new_read : Egraph.wt -> (Egraph.wt -> Node.t -> map_info Ground.M.t -> unit) -> unit val add_read : Egraph.wt -> Node.t -> Node.t -> unit val register_hook_new_map_parent : Egraph.wt -> (Egraph.wt -> Ground.t -> Node.S.t -> map_info -> unit) -> unit val add_map_parent : Egraph.wt -> Node.t -> Ground.t -> map_info -> unit
(*************************************************************************) (* This file is part of Colibri2. *) (* *) (* Copyright (C) 2014-2021 *) (* CEA (Commissariat à l'énergie atomique et aux énergies *) (* alternatives) *) (* OCamlPro *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) (* Lesser General Public License as published by the Free Software *) (* Foundation, version 2.1. *) (* *) (* It 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. *) (* *) (* See the GNU Lesser General Public License version 2.1 *) (* for more details (enclosed in the file licenses/LGPLv2.1). *) (*************************************************************************)
js-sexp.ml
let () = f x [%sexp_of int] y ;; (* y *) let z = some_function [%sexp_of foo] ;; let z = some_function argument let d = print_sexp [%sexp_of unit] ()
t-borel_transform.c
#include "acb_poly.h" int main() { slong iter; flint_rand_t state; flint_printf("borel_transform...."); fflush(stdout); flint_randinit(state); for (iter = 0; iter < 500 * arb_test_multiplier(); iter++) { acb_poly_t a, b, c, d; slong n, prec; acb_poly_init(a); acb_poly_init(b); acb_poly_init(c); acb_poly_init(d); n = n_randint(state, 30); prec = n_randint(state, 200); acb_poly_randtest(a, state, n, prec, 10); acb_poly_randtest(b, state, n, prec, 10); acb_poly_randtest(c, state, n, prec, 10); acb_poly_borel_transform(b, a, prec); acb_poly_inv_borel_transform(c, b, prec); if (!acb_poly_contains(c, a)) { flint_printf("FAIL (containment)\n\n"); flint_abort(); } acb_poly_set(d, a); acb_poly_borel_transform(d, d, prec); if (!acb_poly_equal(d, b)) { flint_printf("FAIL (aliasing 1)\n\n"); flint_abort(); } acb_poly_set(d, b); acb_poly_inv_borel_transform(d, d, prec); if (!acb_poly_equal(d, c)) { flint_printf("FAIL (aliasing 2)\n\n"); flint_abort(); } acb_poly_clear(a); acb_poly_clear(b); acb_poly_clear(c); acb_poly_clear(d); } 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/>. */
sail_failure.c
#include "sail_failure.h" void sail_match_failure(sail_string msg) { fprintf(stderr, "Pattern match failure in %s\n", msg); exit(EXIT_FAILURE); } unit sail_assert(bool b, sail_string msg) { if (b) return UNIT; fprintf(stderr, "Assertion failed: %s\n", msg); exit(EXIT_FAILURE); }
/****************************************************************************/ /* Sail */ /* */ /* Sail and the Sail architecture models here, comprising all files and */ /* directories except the ASL-derived Sail code in the aarch64 directory, */ /* are subject to the BSD two-clause licence below. */ /* */ /* The ASL derived parts of the ARMv8.3 specification in */ /* aarch64/no_vector and aarch64/full are copyright ARM Ltd. */ /* */ /* Copyright (c) 2013-2021 */ /* Kathyrn Gray */ /* Shaked Flur */ /* Stephen Kell */ /* Gabriel Kerneis */ /* Robert Norton-Wright */ /* Christopher Pulte */ /* Peter Sewell */ /* Alasdair Armstrong */ /* Brian Campbell */ /* Thomas Bauereiss */ /* Anthony Fox */ /* Jon French */ /* Dominic Mulligan */ /* Stephen Kell */ /* Mark Wassell */ /* Alastair Reid (Arm Ltd) */ /* */ /* All rights reserved. */ /* */ /* This work was partially supported by EPSRC grant EP/K008528/1 <a */ /* href="http://www.cl.cam.ac.uk/users/pes20/rems">REMS: Rigorous */ /* Engineering for Mainstream Systems</a>, an ARM iCASE award, EPSRC IAA */ /* KTF funding, and donations from Arm. This project has received */ /* funding from the European Research Council (ERC) under the European */ /* Union’s Horizon 2020 research and innovation programme (grant */ /* agreement No 789108, ELVER). */ /* */ /* This software was developed by SRI International and the University of */ /* Cambridge Computer Laboratory (Department of Computer Science and */ /* Technology) under DARPA/AFRL contracts FA8650-18-C-7809 ("CIFV") */ /* and FA8750-10-C-0237 ("CTSRD"). */ /* */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. Redistributions in binary form must reproduce the above copyright */ /* notice, this list of conditions and the following disclaimer in */ /* the documentation and/or other materials provided with the */ /* distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' */ /* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED */ /* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A */ /* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR */ /* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, */ /* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT */ /* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF */ /* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND */ /* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */ /* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT */ /* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF */ /* SUCH DAMAGE. */ /****************************************************************************/
dune
(library (public_name ezjs_d3pie) (modules_without_implementation d3pie_types) (modules d3pie_types d3pie) (preprocess (pps js_of_ocaml-ppx)) (libraries js_of_ocaml))
dune
(library (public_name toc) (libraries omd fmt logs astring))
mempool.mli
(** Tezos Shell Module - Mempool, a.k.a. the operations safe to be broadcast. *) type t = { known_valid : Operation_hash.t list; (** A valid sequence of operations on top of the current head. *) pending : Operation_hash.Set.t; (** Set of known not-invalid operation. *) } type mempool = t val encoding : mempool Data_encoding.t val bounded_encoding : ?max_operations:int -> unit -> mempool Data_encoding.t (** Empty mempool. *) val empty : mempool (** [is_empty mempool] returns true if and only if [mempool] is empty. *) val is_empty : mempool -> bool (** [cons_valid oph t] prepends [oph] to the [known_valid] field of [t]. *) val cons_valid : Operation_hash.t -> mempool -> mempool (** Remove an operation from all the fields of a mempool. *) val remove : Operation_hash.t -> mempool -> mempool
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
Set.mli
open Sigs (**The lattice of sets. The ordering is set inclusion. Therefore, the empty set is the bottom element. *) module Set (X : sig type t val empty: t val equal: t -> t -> bool end) : PROPERTY with type property = X.t
(******************************************************************************) (* *) (* Fix *) (* *) (* François Pottier, Inria Paris *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Library General Public License version 2, with a *) (* special exception on linking, as described in the file LICENSE. *) (* *) (******************************************************************************)
bgp.mli
(** Evaluation of Basic Graph Patterns (BGP). *) module type P = sig type g type term val term : Term.term -> term val compare : term -> term -> int val rdfterm : term -> Term.term val subjects : unit -> term list val objects : unit -> term list val find : ?sub:term -> ?pred:term-> ?obj:term -> unit -> (term * term * term) list end module type S = sig val eval_bgp : Sparql_algebra.triple list -> Sparql_ms.Multimu.t end module Make : functor (P : P) -> S
(*********************************************************************************) (* OCaml-RDF *) (* *) (* Copyright (C) 2012-2021 Institut National de Recherche en Informatique *) (* et en Automatique. All rights reserved. *) (* *) (* This program is free software; you can redistribute it and/or modify *) (* it under the terms of the GNU Lesser General Public License version *) (* 3 as published by the Free Software Foundation. *) (* *) (* 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 General Public License for more details. *) (* *) (* You should have received a copy of the GNU 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 *) (* *) (* Contact: Maxence.Guesdon@inria.fr *) (* *) (*********************************************************************************)
t-set_nmod_mat.c
#ifdef T #include "templates.h" #include <stdio.h> #include <stdlib.h> #include "ulong_extras.h" #include "long_extras.h" int main(void) { int i, result; FLINT_TEST_INIT(state); flint_printf("set_nmod_mat... "); fflush(stdout); /* Check conversion of identity matrix */ for (i = 0; i < 200 * flint_test_multiplier(); i++) { TEMPLATE(T, ctx_t) ctx; TEMPLATE(T, mat_t) a; nmod_mat_t m; slong r, c; TEMPLATE(T, ctx_randtest)(ctx, state); r = n_randint(state, 10); c = n_randint(state, 10); TEMPLATE(T, mat_init)(a, r, c, ctx); TEMPLATE(T, mat_randtest)(a, state, ctx); nmod_mat_init(m, r, c, fmpz_get_ui(TEMPLATE(T, ctx_prime)(ctx))); nmod_mat_one(m); TEMPLATE(T, mat_set_nmod_mat)(a, m, ctx); result = (TEMPLATE(T, mat_is_one)(a, ctx)); if (!result) { flint_printf("FAIL:\n\n"); flint_printf("a = "), TEMPLATE(T, mat_print)(a, ctx), flint_printf("\n"); fflush(stdout); flint_abort(); } nmod_mat_clear(m); TEMPLATE(T, mat_clear)(a, ctx); TEMPLATE(T, ctx_clear)(ctx); } FLINT_TEST_CLEANUP(state); flint_printf("PASS\n"); return EXIT_SUCCESS; } #endif
/* Copyright (C) 2012 Sebastian Pancratz Copyright (C) 2012 Andres Goens Copyright (C) 2013 Mike Hansen Copyright (C) 2021 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/>. */
js-list.ml
(* mixed list styles *) let cases = [ Group ("publishing", [ basic_pre2 ~name; ]); (* I think this line and the 2 preceding ones are indented one space too few by ocp-indent *) Group ("recovery", [ basic_pre2 ~name ]); ]
(* mixed list styles *) let cases =
cle_indexfunctions.h
#ifndef CLE_INDEXFUNCTIONS #define CLE_INDEXFUNCTIONS #include <clb_simple_stuff.h> #include <clb_objtrees.h> #include <cle_patterns.h> #include <cle_termtops.h> /*---------------------------------------------------------------------*/ /* Data type declarations */ /*---------------------------------------------------------------------*/ typedef enum { IndexNoIndex = 0, IndexArity = 1, IndexSymbol = 2, IndexTop = 4, IndexAltTop = 8, IndexCSTop = 16, IndexESTop = 32, IndexIdentity = 64, IndexEmpty = 128 }IndexType; typedef struct indextermcell { Term_p term; /* Usually has reference if malloced() */ PatternSubst_p subst; /* Shared, necessary for object-tree comparison */ long key; /* The returned index number */ }IndexTermCell, *IndexTerm_p; /* Operations on index: - insert(term, patternsubst) -> value >=0, - find(term, patternsubst) -> value or -1 All values should populate 0...max{values} somewhat densely */ typedef struct tsmindexcell { long ident; IndexType type; int depth; long count; TB_p bank; /* Shared, only here for convenience */ PatternSubst_p subst; /* Ditto */ union { PTree_p t_index; /* Map IndexTerms onto index number */ NumTree_p n_index; /* Map f_codes onto number */ } tree; }TSMIndexCell, *TSMIndex_p; #define IndexDynamicDepth 0 /*---------------------------------------------------------------------*/ /* Exported Functions and Variables */ /*---------------------------------------------------------------------*/ extern char* IndexFunNames[]; #define IndexTermCellAlloc() (IndexTermCell*)SizeMalloc(sizeof(IndexTermCell)) #define IndexTermCellFree(junk) SizeFree(junk, sizeof(IndexTermCell)) int GetIndexType(char* name); IndexTerm_p IndexTermAlloc(Term_p term, PatternSubst_p subst, long key); void IndexTermFree(IndexTerm_p junk, TB_p bank); int IndexTermCompareFun(const void* term1, const void* term2); #define TSMIndexCellAlloc() (TSMIndexCell*)SizeMalloc(sizeof(TSMIndexCell)) #define TSMIndexCellFree(junk) SizeFree(junk, sizeof(TSMIndexCell)) TSMIndex_p TSMIndexAlloc(IndexType type, int depth, TB_p bank, PatternSubst_p subst); void TSMIndexFree(TSMIndex_p junk); long TSMIndexFind(TSMIndex_p index, Term_p term, PatternSubst_p subst); long TSMIndexInsert(TSMIndex_p index, Term_p term); void TSMIndexPrint(FILE* out, TSMIndex_p index, int depth); #endif /*---------------------------------------------------------------------*/ /* End of File */ /*---------------------------------------------------------------------*/
/*----------------------------------------------------------------------- File : cle_indexfunctions.h Author: Stephan Schulz Contents Functions and data types realizing simple index functions. 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. Created: Wed Aug 4 15:36:51 MET DST 1999 -----------------------------------------------------------------------*/
trace_stat_summary_utils.ml
type histo = (float * int) list [@@deriving repr] type curve = float list [@@deriving repr] let snap_to_integer ~significant_digits v = if significant_digits < 0 then invalid_arg "significant_digits should be greater or equal to zero."; if not @@ Float.is_finite v then v else if Float.is_integer v then v else (* This scope is about choosing between [v] and [Float.round v]. *) let significant_digits = float_of_int significant_digits in let v' = Float.round v in if v' = 0. then (* Do not snap numbers close to 0. *) v else let round_distance = Float.abs (v -. v') in assert (round_distance <= 0.5); (* The smaller [round_distance], the greater [significant_digits']. *) let significant_digits' = -.Float.log10 round_distance in assert (significant_digits' > 0.); if significant_digits' >= significant_digits then v' else v let pp_six_digits_with_spacer ppf v = let s = Printf.sprintf "%.6f" v in let len = String.length s in let a = String.sub s 0 (len - 3) in let b = String.sub s (len - 3) 3 in Format.fprintf ppf "%s_%s" a b let create_pp_real ?(significant_digits = 7) examples = let examples = List.map (snap_to_integer ~significant_digits) examples in let all_integer = List.for_all (fun v -> Float.is_integer v || not (Float.is_finite v)) examples in let absmax = List.fold_left (fun acc v -> if not @@ Float.is_finite acc then v else if not @@ Float.is_finite v then acc else Float.abs v |> max acc) Float.neg_infinity examples in let finite_pp = if absmax /. 1e12 >= 10. then fun ppf v -> Format.fprintf ppf "%.3f T" (v /. 1e12) else if absmax /. 1e9 >= 10. then fun ppf v -> Format.fprintf ppf "%.3f G" (v /. 1e9) else if absmax /. 1e6 >= 10. then fun ppf v -> Format.fprintf ppf "%.3f M" (v /. 1e6) else if absmax /. 1e3 >= 10. then fun ppf v -> Format.fprintf ppf "%#d" (Float.round v |> int_of_float) else if all_integer then fun ppf v -> Format.fprintf ppf "%#d" (Float.round v |> int_of_float) else if absmax /. 1. >= 10. then fun ppf v -> Format.fprintf ppf "%.3f" v else if absmax /. 1e-3 >= 10. then pp_six_digits_with_spacer else fun ppf v -> Format.fprintf ppf "%.3e" v in fun ppf v -> if Float.is_nan v then Format.fprintf ppf "n/a" else if Float.is_infinite v then Format.fprintf ppf "%f" v else finite_pp ppf v let create_pp_seconds examples = let absmax = List.fold_left (fun acc v -> if not @@ Float.is_finite acc then v else if not @@ Float.is_finite v then acc else Float.abs v |> max acc) Float.neg_infinity examples in let finite_pp = if absmax >= 60. then fun ppf v -> Mtime.Span.pp_float_s ppf v else if absmax < 100. *. 1e-12 then fun ppf v -> Format.fprintf ppf "%.3e s" v else if absmax < 100. *. 1e-9 then fun ppf v -> Format.fprintf ppf "%.3f ns" (v *. 1e9) else if absmax < 100. *. 1e-6 then fun ppf v -> Format.fprintf ppf "%.3f \xc2\xb5s" (v *. 1e6) else if absmax < 100. *. 1e-3 then fun ppf v -> Format.fprintf ppf "%.3f ms" (v *. 1e3) else fun ppf v -> Format.fprintf ppf "%.3f s" v in fun ppf v -> if Float.is_nan v then Format.fprintf ppf "n/a" else if Float.is_infinite v then Format.fprintf ppf "%f" v else finite_pp ppf v let pp_percent ppf v = if not @@ Float.is_finite v then Format.fprintf ppf "%4f" v else if v = 0. then Format.fprintf ppf " 0%%" else if v < 10. /. 100. then Format.fprintf ppf "%3.1f%%" (v *. 100.) else if v < 1000. /. 100. then Format.fprintf ppf "%3.0f%%" (v *. 100.) else if v < 1000. then Format.fprintf ppf "%3.0fx" v else if v < 9.5e9 then ( let long_repr = Printf.sprintf "%.0e" v in assert (String.length long_repr = 5); Format.fprintf ppf "%ce%cx" long_repr.[0] long_repr.[4]) else Format.fprintf ppf "++++" let weekly_stats = Tezos_history_metrics.weekly_stats let approx_value_count_of_block_count value_of_row ?(first_block_idx = 0) wished_block_count = let end_block_idx = first_block_idx + wished_block_count in let blocks_of_row (_, _, _, v) = v in let fold (week_block0_idx, acc_value, acc_blocks) row = let week_blocks = blocks_of_row row in let week_value = value_of_row row in assert (acc_blocks <= wished_block_count); let nextweek_block0_idx = week_block0_idx + week_blocks in let kept_block_count = let left = if first_block_idx >= nextweek_block0_idx then `After else if first_block_idx <= week_block0_idx then `Before else `Inside in let right = if end_block_idx >= nextweek_block0_idx then `After else if end_block_idx <= week_block0_idx then `Before else `Inside in match (left, right) with | `After, `After -> 0 | `Before, `Before -> 0 | `Before, `After -> week_blocks | `Inside, `After -> first_block_idx - week_block0_idx | `Inside, `Inside -> end_block_idx - first_block_idx | `Before, `Inside -> wished_block_count - acc_blocks | `Inside, `Before -> assert false | `After, (`Before | `Inside) -> assert false in assert (kept_block_count >= 0); assert (kept_block_count <= week_blocks); let kept_tx_count = let f = float_of_int in f week_value /. f week_blocks *. f kept_block_count |> Float.round |> int_of_float in assert (kept_tx_count >= 0); assert (kept_tx_count <= week_value); let acc_blocks' = acc_blocks + kept_block_count in let acc_value' = acc_value + kept_tx_count in (nextweek_block0_idx, acc_value', acc_blocks') in let _, acc_value, acc_blocks = List.fold_left fold (0, 0, 0) weekly_stats in assert (acc_blocks <= wished_block_count); if acc_blocks = wished_block_count then acc_value else (* Extrapolate for the following weeks *) let latest_weeks_tx_count, latest_weeks_block_count = match List.rev weekly_stats with | rowa :: rowb :: rowc :: _ -> let value = List.map value_of_row [ rowa; rowb; rowc ] |> List.fold_left ( + ) 0 in let blocks = List.map blocks_of_row [ rowa; rowb; rowc ] |> List.fold_left ( + ) 0 in (value, blocks) | _ -> assert false in let missing_blocks = wished_block_count - acc_blocks in let missing_value = let f = float_of_int in f latest_weeks_tx_count /. f latest_weeks_block_count *. f missing_blocks |> Float.round |> int_of_float in acc_value + missing_value let approx_transaction_count_of_block_count = approx_value_count_of_block_count (fun (_, txs, _, _) -> txs) let approx_operation_count_of_block_count = approx_value_count_of_block_count (fun (_, _, ops, _) -> ops) module Exponential_moving_average = struct type t = { momentum : float; relevance_threshold : float; opp_momentum : float; hidden_state : float; void_fraction : float; } let create ?(relevance_threshold = 1.) momentum = if momentum < 0. || momentum >= 1. then invalid_arg "Wrong momentum"; if relevance_threshold < 0. || relevance_threshold > 1. then invalid_arg "Wrong relevance_threshold"; { momentum; relevance_threshold; opp_momentum = 1. -. momentum; hidden_state = 0.; void_fraction = 1.; } let from_half_life ?relevance_threshold hl = if hl < 0. then invalid_arg "Wrong half life"; create ?relevance_threshold (if hl = 0. then 0. else log 0.5 /. hl |> exp) let from_half_life_ratio ?relevance_threshold hl_ratio step_count = if hl_ratio < 0. then invalid_arg "Wrong half life ratio"; if step_count < 0. then invalid_arg "Wront step count"; step_count *. hl_ratio |> from_half_life ?relevance_threshold let momentum ema = ema.momentum let hidden_state ema = ema.hidden_state let void_fraction ema = ema.void_fraction let is_relevant ema = ema.void_fraction < ema.relevance_threshold let peek_exn ema = if is_relevant ema then ema.hidden_state /. (1. -. ema.void_fraction) else failwith "Can't peek an irrelevant EMA" let peek_or_nan ema = if is_relevant ema then ema.hidden_state /. (1. -. ema.void_fraction) else Float.nan let update ema sample = let hidden_state = (* The first term is the "forget" term, the second one is the "remember" term. *) (ema.momentum *. ema.hidden_state) +. (ema.opp_momentum *. sample) in let void_fraction = (* [update] decreases the quantity of "void". *) ema.momentum *. ema.void_fraction in { ema with hidden_state; void_fraction } let update_batch ema sample sample_size = if sample_size <= 0. then invalid_arg "Wrong sample_size"; let momentum = ema.momentum ** sample_size in let opp_momentum = 1. -. momentum in (* From this point, the code is identical to [update]. *) let hidden_state = (ema.hidden_state *. momentum) +. (sample *. opp_momentum) in let void_fraction = ema.void_fraction *. momentum in { ema with hidden_state; void_fraction } (** [peek ema] is equal to [forget ema |> peek]. Modulo floating point imprecisions and relevance changes. Proof: {v v0 = hs0 / (1 - vf0) v1 = hs1 / (1 - vf1) hs1 = mom * hs0 vf1 = mom * vf0 + (1 - mom) hs0 / (1 - vf0) = hs1 / (1 - vf1) hs0 / (1 - vf0) = (mom * hs0) / (1 - (mom * vf0 + (1 - mom))) hs0 / (1 - vf0) = (mom * hs0) / (1 - (mom * vf0 + 1 - mom)) hs0 / (1 - vf0) = (mom * hs0) / (1 + (-mom * vf0 - 1 + mom)) hs0 / (1 - vf0) = (mom * hs0) / (1 - mom * vf0 - 1 + mom) hs0 / (1 - vf0) = (mom * hs0) / ( -mom * vf0 + mom) hs0 / (1 - vf0) = (hs0) / ( -1 * vf0 + 1) hs0 / (1 - vf0) = hs0 / (1 - vf0) v0 = v1 v} *) let forget ema = let hidden_state = ema.momentum *. ema.hidden_state in let void_fraction = (* [forget] increases the quantity of "void". Where [update] does: [ema.m * ema.vf + ema.opp_m * 0], [forget] does: [ema.m * ema.vf + ema.opp_m * 1]. *) (ema.momentum *. ema.void_fraction) +. ema.opp_momentum in { ema with hidden_state; void_fraction } let forget_batch ema sample_size = if sample_size <= 0. then invalid_arg "Wrong sample_size"; let momentum = ema.momentum ** sample_size in let opp_momentum = 1. -. momentum in (* From this point, the code is identical to [forget]. *) let hidden_state = ema.hidden_state *. momentum in let void_fraction = (ema.void_fraction *. momentum) +. opp_momentum in { ema with hidden_state; void_fraction } let map ?relevance_threshold momentum vec0 = List.fold_left (fun (ema, rev_result) v0 -> let ema = update ema v0 in let v1 = peek_or_nan ema in (ema, v1 :: rev_result)) (create ?relevance_threshold momentum, []) vec0 |> snd |> List.rev end module Resample = struct let should_sample ~i0 ~len0 ~i1 ~len1 = assert (len0 >= 2); assert (len1 >= 2); assert (i0 < len0); assert (i0 >= 0); assert (i1 >= 0); if i1 >= len1 then `Out_of_bounds else let i0 = float_of_int i0 in let len0 = float_of_int len0 in let i1 = float_of_int i1 in let len1 = float_of_int len1 in let progress0_left = (i0 -. 1.) /. (len0 -. 1.) in let progress0_right = i0 /. (len0 -. 1.) in let progress1 = i1 /. (len1 -. 1.) in if progress1 <= progress0_left then `Before else if progress1 <= progress0_right then ( let where_in_interval = (progress1 -. progress0_left) /. (progress0_right -. progress0_left) in assert (where_in_interval > 0.); assert (where_in_interval <= 1.); `Inside where_in_interval) else `After type acc = { mode : [ `Interpolate | `Next_neighbor ]; len0 : int; len1 : int; i0 : int; i1 : int; prev_v0 : float; rev_samples : curve; } let create_acc mode ~len0 ~len1 ~v00 = let mode = (mode :> [ `Interpolate | `Next_neighbor ]) in if len0 < 2 then invalid_arg "Can't resample curves below 2 points"; if len1 < 2 then invalid_arg "Can't resample curves below 2 points"; { mode; len0; len1; i0 = 1; i1 = 1; prev_v0 = v00; rev_samples = [ v00 ] } let accumulate ({ mode; len0; len1; i0; i1; prev_v0; rev_samples } as acc) v0 = assert (i0 >= 1); assert (i1 >= 1); if i0 >= len0 then failwith "Accumulate called to much"; if i1 >= len1 then failwith "Accumulate called to much"; let rec aux i1 rev_samples = match should_sample ~len1 ~i0 ~len0 ~i1 with | `Inside where_inside -> if i1 = len1 - 1 then ( assert (i0 = len0 - 1); assert (where_inside = 1.)); let v1 = match mode with | `Next_neighbor -> v0 | `Interpolate when where_inside = 1. -> (* Optimisation in case of nan *) v0 | `Interpolate -> prev_v0 +. (where_inside *. (v0 -. prev_v0)) in aux (i1 + 1) (v1 :: rev_samples) | `After -> (i1, rev_samples) | `Before -> assert false | `Out_of_bounds -> assert (i0 = len0 - 1); assert (i1 = len1); (i1, rev_samples) in let i1, rev_samples = aux i1 rev_samples in { acc with i0 = i0 + 1; i1; prev_v0 = v0; rev_samples } let finalise { len1; rev_samples; _ } = if List.length rev_samples <> len1 then failwith "Finalise called too soon"; List.rev rev_samples let resample_vector mode vec0 len1 = let len0 = List.length vec0 in if len0 < 2 then invalid_arg "Can't resample curves below 2 points"; let v00, vec0 = match vec0 with hd :: tl -> (hd, tl) | _ -> assert false in let acc = create_acc mode ~len0 ~len1 ~v00 in List.fold_left accumulate acc vec0 |> finalise end module Variable_summary = struct type t = { max_value : float * int; min_value : float * int; mean : float; diff : float; distribution : histo; evolution : curve; } [@@deriving repr] type acc = { (* Accumulators *) first_value : float; last_value : float; max_value : float * int; min_value : float * int; sum_value : float; value_count : int; distribution : Bentov.histogram; rev_evolution : curve; ma : Exponential_moving_average.t; next_in_idx : int; next_out_idx : int; (* Constants *) in_period_count : int; out_sample_count : int; evolution_resampling_mode : [ `Interpolate | `Prev_neighbor | `Next_neighbor ]; scale : [ `Linear | `Log ]; } let create_acc ~evolution_smoothing ~evolution_resampling_mode ~distribution_bin_count ~scale ~in_period_count ~out_sample_count = if in_period_count < 2 then invalid_arg "in_period_count should be greater than 1"; if out_sample_count < 2 then invalid_arg "out_sample_count should be greater than 1"; { first_value = Float.nan; last_value = Float.nan; max_value = (Float.nan, 0); min_value = (Float.nan, 0); sum_value = 0.; value_count = 0; distribution = Bentov.create distribution_bin_count; rev_evolution = []; ma = (match evolution_smoothing with | `None -> Exponential_moving_average.create 0. | `Ema (half_life_ratio, relevance_threshold) -> Exponential_moving_average.from_half_life_ratio ~relevance_threshold half_life_ratio (float_of_int in_period_count)); next_in_idx = 0; next_out_idx = 0; in_period_count; out_sample_count; evolution_resampling_mode; scale; } let accumulate acc occurences_of_variable_in_period = let xs = occurences_of_variable_in_period in let xs = List.filter (fun v -> not (Float.is_nan v)) xs in let i = acc.next_in_idx in let sample_count = List.length xs |> float_of_int in assert (i < acc.in_period_count); let accumulate_in_sample (first, last, ((topv, _) as top), ((botv, _) as bot), histo, ma) v = let first = if Float.is_nan first then v else first in let last = if Float.is_nan v then last else v in let top = if Float.is_nan topv || topv < v then (v, i) else top in let bot = if Float.is_nan botv || botv > v then (v, i) else bot in let v = match acc.scale with | `Linear -> v | `Log -> if Float.is_infinite v then v else if v <= 0. then failwith "Input samples to a Variable_summary should be > 0. when \ scale=`Log." else Float.log v in let histo = Bentov.add v histo in let ma = Exponential_moving_average.update_batch ma v (1. /. sample_count) in (first, last, top, bot, histo, ma) in let first_value, last_value, max_value, min_value, distribution, ma = List.fold_left accumulate_in_sample ( acc.first_value, acc.last_value, acc.max_value, acc.min_value, acc.distribution, acc.ma ) xs in let ma = if sample_count = 0. then Exponential_moving_average.forget ma else ma in let rev_evolution, next_out_idx = let rec aux rev_samples next_out_idx = match Resample.should_sample ~i0:i ~len0:acc.in_period_count ~i1:next_out_idx ~len1:acc.out_sample_count with | `Before -> assert false | `Inside where_in_block -> let out_sample = let v_after = Exponential_moving_average.peek_or_nan ma in if where_in_block = 1. then v_after else ( assert (where_in_block > 0.); assert (next_out_idx > 0); let v_before = Exponential_moving_average.peek_or_nan acc.ma in match acc.evolution_resampling_mode with | `Prev_neighbor -> v_before | `Next_neighbor -> v_after | `Interpolate -> v_before +. ((v_after -. v_before) *. where_in_block)) in aux (out_sample :: rev_samples) (next_out_idx + 1) | `After | `Out_of_bounds -> (rev_samples, next_out_idx) in aux acc.rev_evolution acc.next_out_idx in { acc with first_value; last_value; max_value; min_value; sum_value = List.fold_left ( +. ) acc.sum_value xs; value_count = acc.value_count + List.length xs; distribution; rev_evolution; ma; next_in_idx = acc.next_in_idx + 1; next_out_idx; } let finalise acc = assert (acc.next_out_idx = acc.out_sample_count); assert (acc.next_out_idx = List.length acc.rev_evolution); assert (acc.next_in_idx = acc.in_period_count); let f = match acc.scale with `Linear -> Fun.id | `Log -> Float.exp in let distribution = let open Bentov in bins acc.distribution |> List.map (fun b -> (f b.center, b.count)) in let evolution = List.rev_map f acc.rev_evolution in { max_value = acc.max_value; min_value = acc.min_value; mean = acc.sum_value /. float_of_int acc.value_count; diff = acc.last_value -. acc.first_value; distribution; evolution; } end module Parallel_folders = struct type ('row, 'acc, 'v) folder = { acc : 'acc; accumulate : 'acc -> 'row -> 'acc; finalise : 'acc -> 'v; } let folder acc accumulate finalise = { acc; accumulate; finalise } type ('res, 'row, 'v) folders = | F0 : ('res, 'row, 'res) folders | F1 : ('row, 'acc, 'v) folder * ('res, 'row, 'rest) folders -> ('res, 'row, 'v -> 'rest) folders type ('res, 'row, 'f, 'rest) open_t = ('res, 'row, 'rest) folders -> 'f * ('res, 'row, 'f) folders let open_ : 'f -> ('res, 'row, 'f, 'f) open_t = fun constructor folders -> (constructor, folders) let app : type res f v rest acc row. (res, row, f, v -> rest) open_t -> (row, acc, v) folder -> (res, row, f, rest) open_t = fun open_t folder folders -> open_t (F1 (folder, folders)) let ( |+ ) = app type ('res, 'row) t = T : 'f * ('res, 'row, 'f) folders -> ('res, 'row) t let seal : type res row f. (res, row, f, res) open_t -> (res, row) t = fun open_t -> let constructor, folders = open_t F0 in T (constructor, folders) let accumulate : type res row. (res, row) t -> row -> (res, row) t = fun (T (constructor, folders)) row -> let rec aux : type v. (res, row, v) folders -> (res, row, v) folders = function | F0 -> F0 | F1 (folder, t) as f -> ( let acc = folder.acc in let acc' = folder.accumulate acc row in let t' = aux t in (* Avoid reallocating [F1] and [folder] when possible. *) match (acc == acc', t == t') with | true, true -> f | true, false -> F1 (folder, t') | false, (true | false) -> F1 ({ folder with acc = acc' }, t')) in let folders = aux folders in T (constructor, folders) let finalise : type res row. (res, row) t -> res = let rec aux : type c. (res, row, c) folders -> c -> res = function | F0 -> Fun.id | F1 (f, fs) -> fun constructor -> let v = f.finalise f.acc in let finalise_remaining = aux fs in let constructor = constructor v in finalise_remaining constructor in fun (T (constructor, folders)) -> aux folders constructor end
(* * Copyright (c) 2018-2021 Tarides <contact@tarides.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
dune
(executable (name test) (libraries alcotest ezgzip qcheck)) (alias (name runtest) (deps (:< test.exe)) (action (run %{<} --color=always)))
dune
(coq.theory (name C) (package C) (theories B))
crt_init.c
#include "dlog.h" ulong dlog_crt_init(dlog_crt_t t, ulong a, ulong mod, ulong n, ulong num) { int k; n_factor_t fac; ulong * M, * u; ulong cost = 0; n_factor_init(&fac); n_factor(&fac, n, 1); t->num = fac.num; nmod_init(&t->mod,mod); nmod_init(&t->n, n); M = t->expo = flint_malloc(t->num * sizeof(ulong)); u = t->crt_coeffs = flint_malloc(t->num * sizeof(ulong)); t->pre = flint_malloc(t->num * sizeof(dlog_precomp_struct)); for (k = 0; k < t->num; k++) { ulong p, e, mk; p = fac.p[k]; e = fac.exp[k]; if (0 && mod % p == 0) { flint_printf("dlog_crt_init: modulus must be prime to order.\n"); flint_abort(); } mk = n_pow(p, e); M[k] = n / mk; u[k] = nmod_mul(M[k], n_invmod(M[k] % mk, mk), t->n); /* depends on the power */ #if 0 flint_printf("[sub-crt -- init for size %wu mod %wu]\n", mk, mod); #endif dlog_precomp_pe_init(t->pre + k, nmod_pow_ui(a, M[k], t->mod), mod, p, e, mk, num); cost += t->pre[k].cost; } #if 0 if (cost > 500) flint_printf("[crt init for size %wu mod %wu -> cost %wu]\n", n,mod,cost); #endif return cost; }
/* Copyright (C) 2016 Pascal Molin 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/>. */
removeTagsFromResource.ml
open Types open Aws type input = RemoveTagsFromResourceMessage.t type output = TagListMessage.t type error = Errors_internal.t let service = "elasticache" let signature_version = Request.V4 let to_http service region req = let uri = Uri.add_query_params (Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region))) (List.append [("Version", ["2015-02-02"]); ("Action", ["RemoveTagsFromResource"])] (Util.drop_empty (Uri.query_of_encoded (Query.render (RemoveTagsFromResourceMessage.to_query req))))) in (`POST, uri, []) let of_http body = try let xml = Ezxmlm.from_string body in let resp = Util.option_bind (Xml.member "RemoveTagsFromResourceResponse" (snd xml)) (Xml.member "RemoveTagsFromResourceResult") in try Util.or_error (Util.option_bind resp TagListMessage.parse) (let open Error in BadResponse { body; message = "Could not find well formed TagListMessage." }) with | Xml.RequiredFieldMissing msg -> let open Error in `Error (BadResponse { body; message = ("Error parsing TagListMessage - missing field in body or children: " ^ msg) }) with | Failure msg -> `Error (let open Error in BadResponse { body; message = ("Error parsing xml: " ^ msg) }) let parse_error code err = let errors = [] @ Errors_internal.common in match Errors_internal.of_string err with | Some var -> if (List.mem var errors) && ((match Errors_internal.to_http_code var with | Some var -> var = code | None -> true)) then Some var else None | None -> None
dune
(test (name patcher) (modules patcher) (libraries opam-core))
test_fuzzing_list.ml
open Test_fuzzing_tests open Qcheck2_helpers module ListWithBase = struct type 'a elt = 'a include Support.Lib.List let of_list = Fun.id let to_list = Fun.id let name = "List" let pp = Format.pp_print_list Format.pp_print_int end module type F = functor (S : module type of ListWithBase) -> sig val tests : QCheck2.Test.t list end let wrap (name, (module Test : F)) = let module M = Test (ListWithBase) in (name, qcheck_wrap M.tests) let () = let name = "Test_fuzzing_list" in let tests = [ (* Test internal consistency *) ("TestIterFold", (module TestIterFold : F)); ("TestRevMapRevMap", (module TestRevMapRevMap : F)); ("TestRevConcatMapRevConcatMap", (module TestRevConcatMapRevConcatMap : F)); ("TestConcatMapConcatMap", (module TestConcatMapConcatMap : F)); ("Filters", (module TestFilters : F)); ("Partitions", (module TestPartitions : F)); ("PartitionMap", (module TestPartitionMap : F)); (* Test consistency with Stdlib *) ("ExistForall", (module TestExistForallAgainstStdlibList : F)); ("Filter", (module TestFilterAgainstStdlibList : F)); ("Filterp", (module TestFilterpAgainstStdlibList : F)); ("Filteri", (module TestFilteriAgainstStdlibList : F)); ("Filterip", (module TestFilteripAgainstStdlibList : F)); ("Filtermap", (module TestFiltermapAgainstStdlibList : F)); ("Filtermapp", (module TestFiltermappAgainstStdlibList : F)); ("Concatmap", (module TestConcatmapAgainstStdlibList : F)); ("Concatmapp", (module TestConcatmappAgainstStdlibList : F)); ("Fold", (module TestFoldAgainstStdlibList : F)); ("FoldRight", (module TestFoldRightAgainstStdlibList : F)); ("FoldLeftMap", (module TestFoldLeftMapAgainstStdlibList : F)); ("Iter", (module TestIterAgainstStdlibList : F)); ("Iteri", (module TestIteriAgainstStdlibList : F)); ("Iterp", (module TestIterMonotoneAgainstStdlibList : F)); ("Map", (module TestMapAgainstStdlibList : F)); ("Mapp", (module TestMappAgainstStdlibList : F)); ("Find", (module TestFindStdlibList : F)); ("FindMap", (module TestFindMapStdlibList : F)); ("Partition", (module TestPartitionStdlibList : F)); ("Double", (module TestDoubleTraversorsStdlibList : F)); ] in let tests = List.map wrap tests in Alcotest.run name tests
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2020 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
noLevelNorTLBI.ml
type level let levels = [] let pp_level _ = assert false module TLBI = struct type op let pp_op = fun _ -> Printf.sprintf "no notion of TLBI op in arch" let is_at_level _lvl _op = assert false let inv_all _ = false end
(****************************************************************************) (* the diy toolsuite *) (* *) (* Jade Alglave, University College London, UK. *) (* Luc Maranget, INRIA Paris-Rocquencourt, France. *) (* *) (* Copyright 2020-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. *) (****************************************************************************)
Unit_matcher.ml
open Common (*****************************************************************************) (* Purpose *) (*****************************************************************************) (* Unit tests exercising just the semgrep patterns part *) (*****************************************************************************) (* Simple tests defined inline *) (*****************************************************************************) (* TODO: * - we could add unit tests for the range returned by match_sts_sts * - we could add unit tests for the code dealing with equivalences *) let tests ~any_gen_of_string = [ ( "sgrep(generic) features", fun () -> (* spec: pattern string, code string, should_match boolean *) let triples = [ (* right now any_gen_of_string use the Python sgrep_spatch_pattern * parser so the syntax below must be valid Python code *) (* ------------ *) (* spacing *) (* ------------ *) (* basic string-match of course *) ("foo(1,2)", "foo(1,2)", true); ("foo(1,3)", "foo(1,2)", false); (* matches even when space or newline differs *) ("foo(1,2)", "foo(1, 2)", true); ("foo(1,2)", "foo(1,\n 2)", true); (* matches even when have comments in the middle *) ("foo(1,2)", "foo(1, #foo\n 2)", true); (* ------------ *) (* metavariables *) (* ------------ *) (* for identifiers *) ("import $X", "import Foo", true); ("x.$X", "x.foo", true); (* for expressions *) ("foo($X)", "foo(1)", true); ("foo($X)", "foo(1+1)", true); (* for lvalues *) ("$X.method()", "foo.method()", true); ("$X.method()", "foo.bar.method()", true); (* "linear" patterns, a la Prolog *) ("$X & $X", "(a | b) & (a | b)", true); ("foo($X, $X)", "foo(a, a)", true); ("foo($X, $X)", "foo(a, b)", false); (* metavariable on function name *) ("$X(1,2)", "foo(1,2)", true); (* metavariable on method call *) ("$X.foo()", "Bar.foo()", true); (* should not match infix expressions though, even if those * are transformed internally in Calls *) ("$X(...)", "a+b", false); (* metavariable for statements *) ("if(True): $S\n", "if(True): return 1\n", true); (* metavariable for entity definitions *) ("def $X(): return 1\n", "def foo(): return 1\n", true); (* metavariable for parameter *) ("def foo($A, b): return 1\n", "def foo(x, b): return 1\n", true); (* metavariable string for identifiers *) (* "foo('X');", "foo('a_func');", true; *) (* many arguments metavariables *) (* "foo($MANYARGS);", "foo(1,2,3);", true; *) (* ------------ *) (* '...' *) (* ------------ *) (* '...' in funcall *) ("foo(...)", "foo()", true); ("foo(...)", "foo(1)", true); ("foo(...)", "foo(1,2)", true); ("foo($X,...)", "foo(1,2)", true); (* ... also match when there is no additional arguments *) ("foo($X,...)", "foo(1)", true); ("foo(..., 3, ...)", "foo(1,2,3,4)", true); (* ... in more complex expressions *) ("strstr(...) == False", "strstr(x)==False", true); (* in strings *) ("foo(\"...\")", "foo(\"this is a long string\")", true); (* "foo(\"...\");", "foo(\"a string\" . \"another string\");", true;*) (* for stmts *) ( "if True: foo(); ...; bar()\n", "if True: foo(); foobar(); bar()\n", true ); (* for parameters *) ("def foo(...): ...\n", "def foo(a, b): return a+b\n", true); ( "def foo(..., foo=..., ...): ...\n", "def foo(a, b, foo = 1, bar = 2): return a+b\n", true ); (* "class Foo { ... }", "class Foo { int x; }", true; *) (* '...' in arrays *) (* "foo($X, array(...));", "foo(1, array(2, 3));", true; *) (* ------------ *) (* Misc isomorphisms *) (* ------------ *) (* flexible keyword argument matching, the order does not matter *) ("foo(kwd1=$X, kwd2=$Y)", "foo(kwd2=1, kwd1=3)", true); (* regexp matching in strings *) ("foo(\"=~/a+/\")", "foo(\"aaaa\")", true); ("foo(\"=~/a+/\")", "foo(\"bbbb\")", false) (* "new Foo(...);","new Foo;", true; *); ] in triples |> List.iter (fun (spattern, scode, should_match) -> try let pattern = any_gen_of_string spattern in let code = any_gen_of_string scode in let cache = None in let lang = Lang.Python in let config = Config_semgrep.default_config in let env = Matching_generic.empty_environment cache lang config in let matches_with_env = Match_patterns.match_any_any pattern code env in if should_match then Alcotest.(check bool) (spf "pattern:|%s| should match |%s" spattern scode) true (matches_with_env <> []) else Alcotest.(check bool) (spf "pattern:|%s| should not match |%s" spattern scode) true (matches_with_env =*= []) with | Parsing.Parse_error -> failwith (spf "problem parsing %s or %s" spattern scode)) ); ]
dune
(library (name ezAPI) (public_name ez_api) (modules arg param req path mime meth err security service doc url error_codes ezAPI) (libraries lwt ezEncoding ezDebug ezLwtSys uuidm)) (library (name ezAPIJS) (public_name ez_api.js) (optional) (modules) (libraries ezAPI ezjsonm_js ezDebug_js ezLwtSys_js))
Wasm.h
//===- Wasm.h - Wasm object file format -------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines manifest constants for the wasm object file format. // See: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md // //===----------------------------------------------------------------------===// #ifndef LLVM_BINARYFORMAT_WASM_H #define LLVM_BINARYFORMAT_WASM_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" namespace llvm { namespace wasm { // Object file magic string. const char WasmMagic[] = {'\0', 'a', 's', 'm'}; // Wasm binary format version const uint32_t WasmVersion = 0x1; // Wasm linking metadata version const uint32_t WasmMetadataVersion = 0x2; // Wasm uses a 64k page size const uint32_t WasmPageSize = 65536; struct WasmObjectHeader { StringRef Magic; uint32_t Version; }; struct WasmDylinkInfo { uint32_t MemorySize; // Memory size in bytes uint32_t MemoryAlignment; // P2 alignment of memory uint32_t TableSize; // Table size in elements uint32_t TableAlignment; // P2 alignment of table std::vector<StringRef> Needed; // Shared library depenedencies }; struct WasmProducerInfo { std::vector<std::pair<std::string, std::string>> Languages; std::vector<std::pair<std::string, std::string>> Tools; std::vector<std::pair<std::string, std::string>> SDKs; }; struct WasmFeatureEntry { uint8_t Prefix; std::string Name; }; struct WasmExport { StringRef Name; uint8_t Kind; uint32_t Index; }; struct WasmLimits { uint8_t Flags; uint32_t Initial; uint32_t Maximum; }; struct WasmTable { uint8_t ElemType; WasmLimits Limits; }; struct WasmInitExpr { uint8_t Opcode; union { int32_t Int32; int64_t Int64; int32_t Float32; int64_t Float64; uint32_t Global; } Value; }; struct WasmGlobalType { uint8_t Type; bool Mutable; }; struct WasmGlobal { uint32_t Index; WasmGlobalType Type; WasmInitExpr InitExpr; StringRef SymbolName; // from the "linking" section }; struct WasmEventType { // Kind of event. Currently only WASM_EVENT_ATTRIBUTE_EXCEPTION is possible. uint32_t Attribute; uint32_t SigIndex; }; struct WasmEvent { uint32_t Index; WasmEventType Type; StringRef SymbolName; // from the "linking" section }; struct WasmImport { StringRef Module; StringRef Field; uint8_t Kind; union { uint32_t SigIndex; WasmGlobalType Global; WasmTable Table; WasmLimits Memory; WasmEventType Event; }; }; struct WasmLocalDecl { uint8_t Type; uint32_t Count; }; struct WasmFunction { uint32_t Index; std::vector<WasmLocalDecl> Locals; ArrayRef<uint8_t> Body; uint32_t CodeSectionOffset; uint32_t Size; uint32_t CodeOffset; // start of Locals and Body StringRef SymbolName; // from the "linking" section StringRef DebugName; // from the "name" section uint32_t Comdat; // from the "comdat info" section }; struct WasmDataSegment { uint32_t InitFlags; uint32_t MemoryIndex; // present if InitFlags & WASM_SEGMENT_HAS_MEMINDEX WasmInitExpr Offset; // present if InitFlags & WASM_SEGMENT_IS_PASSIVE == 0 ArrayRef<uint8_t> Content; StringRef Name; // from the "segment info" section uint32_t Alignment; uint32_t LinkerFlags; uint32_t Comdat; // from the "comdat info" section }; struct WasmElemSegment { uint32_t TableIndex; WasmInitExpr Offset; std::vector<uint32_t> Functions; }; // Represents the location of a Wasm data symbol within a WasmDataSegment, as // the index of the segment, and the offset and size within the segment. struct WasmDataReference { uint32_t Segment; uint32_t Offset; uint32_t Size; }; struct WasmRelocation { uint8_t Type; // The type of the relocation. uint32_t Index; // Index into either symbol or type index space. uint64_t Offset; // Offset from the start of the section. int64_t Addend; // A value to add to the symbol. }; struct WasmInitFunc { uint32_t Priority; uint32_t Symbol; }; struct WasmSymbolInfo { StringRef Name; uint8_t Kind; uint32_t Flags; StringRef ImportModule; // For undefined symbols the module of the import StringRef ImportName; // For undefined symbols the name of the import union { // For function or global symbols, the index in function or global index // space. uint32_t ElementIndex; // For a data symbols, the address of the data relative to segment. WasmDataReference DataRef; }; }; struct WasmFunctionName { uint32_t Index; StringRef Name; }; struct WasmLinkingData { uint32_t Version; std::vector<WasmInitFunc> InitFunctions; std::vector<StringRef> Comdats; std::vector<WasmSymbolInfo> SymbolTable; }; enum : unsigned { WASM_SEC_CUSTOM = 0, // Custom / User-defined section WASM_SEC_TYPE = 1, // Function signature declarations WASM_SEC_IMPORT = 2, // Import declarations WASM_SEC_FUNCTION = 3, // Function declarations WASM_SEC_TABLE = 4, // Indirect function table and other tables WASM_SEC_MEMORY = 5, // Memory attributes WASM_SEC_GLOBAL = 6, // Global declarations WASM_SEC_EXPORT = 7, // Exports WASM_SEC_START = 8, // Start function declaration WASM_SEC_ELEM = 9, // Elements section WASM_SEC_CODE = 10, // Function bodies (code) WASM_SEC_DATA = 11, // Data segments WASM_SEC_DATACOUNT = 12, // Data segment count WASM_SEC_EVENT = 13 // Event declarations }; // Type immediate encodings used in various contexts. enum : unsigned { WASM_TYPE_I32 = 0x7F, WASM_TYPE_I64 = 0x7E, WASM_TYPE_F32 = 0x7D, WASM_TYPE_F64 = 0x7C, WASM_TYPE_V128 = 0x7B, WASM_TYPE_FUNCREF = 0x70, WASM_TYPE_FUNC = 0x60, WASM_TYPE_NORESULT = 0x40, // for blocks with no result values }; // Kinds of externals (for imports and exports). enum : unsigned { WASM_EXTERNAL_FUNCTION = 0x0, WASM_EXTERNAL_TABLE = 0x1, WASM_EXTERNAL_MEMORY = 0x2, WASM_EXTERNAL_GLOBAL = 0x3, WASM_EXTERNAL_EVENT = 0x4, }; // Opcodes used in initializer expressions. enum : unsigned { WASM_OPCODE_END = 0x0b, WASM_OPCODE_CALL = 0x10, WASM_OPCODE_LOCAL_GET = 0x20, WASM_OPCODE_GLOBAL_GET = 0x23, WASM_OPCODE_GLOBAL_SET = 0x24, WASM_OPCODE_I32_STORE = 0x36, WASM_OPCODE_I32_CONST = 0x41, WASM_OPCODE_I64_CONST = 0x42, WASM_OPCODE_F32_CONST = 0x43, WASM_OPCODE_F64_CONST = 0x44, WASM_OPCODE_I32_ADD = 0x6a, }; // Opcodes used in synthetic functions. enum : unsigned { WASM_OPCODE_IF = 0x04, WASM_OPCODE_ELSE = 0x05, WASM_OPCODE_DROP = 0x1a, WASM_OPCODE_MISC_PREFIX = 0xfc, WASM_OPCODE_MEMORY_INIT = 0x08, WASM_OPCODE_DATA_DROP = 0x09, WASM_OPCODE_ATOMICS_PREFIX = 0xfe, WASM_OPCODE_ATOMIC_NOTIFY = 0x00, WASM_OPCODE_I32_ATOMIC_WAIT = 0x01, WASM_OPCODE_I32_ATOMIC_STORE = 0x17, WASM_OPCODE_I32_RMW_CMPXCHG = 0x48, }; enum : unsigned { WASM_LIMITS_FLAG_HAS_MAX = 0x1, WASM_LIMITS_FLAG_IS_SHARED = 0x2, }; enum : unsigned { WASM_SEGMENT_IS_PASSIVE = 0x01, WASM_SEGMENT_HAS_MEMINDEX = 0x02, }; // Feature policy prefixes used in the custom "target_features" section enum : uint8_t { WASM_FEATURE_PREFIX_USED = '+', WASM_FEATURE_PREFIX_REQUIRED = '=', WASM_FEATURE_PREFIX_DISALLOWED = '-', }; // Kind codes used in the custom "name" section enum : unsigned { WASM_NAMES_FUNCTION = 0x1, WASM_NAMES_LOCAL = 0x2, }; // Kind codes used in the custom "linking" section enum : unsigned { WASM_SEGMENT_INFO = 0x5, WASM_INIT_FUNCS = 0x6, WASM_COMDAT_INFO = 0x7, WASM_SYMBOL_TABLE = 0x8, }; // Kind codes used in the custom "linking" section in the WASM_COMDAT_INFO enum : unsigned { WASM_COMDAT_DATA = 0x0, WASM_COMDAT_FUNCTION = 0x1, }; // Kind codes used in the custom "linking" section in the WASM_SYMBOL_TABLE enum WasmSymbolType : unsigned { WASM_SYMBOL_TYPE_FUNCTION = 0x0, WASM_SYMBOL_TYPE_DATA = 0x1, WASM_SYMBOL_TYPE_GLOBAL = 0x2, WASM_SYMBOL_TYPE_SECTION = 0x3, WASM_SYMBOL_TYPE_EVENT = 0x4, }; // Kinds of event attributes. enum WasmEventAttribute : unsigned { WASM_EVENT_ATTRIBUTE_EXCEPTION = 0x0, }; const unsigned WASM_SYMBOL_BINDING_MASK = 0x3; const unsigned WASM_SYMBOL_VISIBILITY_MASK = 0xc; const unsigned WASM_SYMBOL_BINDING_GLOBAL = 0x0; const unsigned WASM_SYMBOL_BINDING_WEAK = 0x1; const unsigned WASM_SYMBOL_BINDING_LOCAL = 0x2; const unsigned WASM_SYMBOL_VISIBILITY_DEFAULT = 0x0; const unsigned WASM_SYMBOL_VISIBILITY_HIDDEN = 0x4; const unsigned WASM_SYMBOL_UNDEFINED = 0x10; const unsigned WASM_SYMBOL_EXPORTED = 0x20; const unsigned WASM_SYMBOL_EXPLICIT_NAME = 0x40; const unsigned WASM_SYMBOL_NO_STRIP = 0x80; #define WASM_RELOC(name, value) name = value, enum : unsigned { #include "WasmRelocs.def" }; #undef WASM_RELOC // Subset of types that a value can have enum class ValType { I32 = WASM_TYPE_I32, I64 = WASM_TYPE_I64, F32 = WASM_TYPE_F32, F64 = WASM_TYPE_F64, V128 = WASM_TYPE_V128, }; struct WasmSignature { SmallVector<ValType, 1> Returns; SmallVector<ValType, 4> Params; // Support empty and tombstone instances, needed by DenseMap. enum { Plain, Empty, Tombstone } State = Plain; WasmSignature(SmallVector<ValType, 1> &&InReturns, SmallVector<ValType, 4> &&InParams) : Returns(InReturns), Params(InParams) {} WasmSignature() = default; }; // Useful comparison operators inline bool operator==(const WasmSignature &LHS, const WasmSignature &RHS) { return LHS.State == RHS.State && LHS.Returns == RHS.Returns && LHS.Params == RHS.Params; } inline bool operator!=(const WasmSignature &LHS, const WasmSignature &RHS) { return !(LHS == RHS); } inline bool operator==(const WasmGlobalType &LHS, const WasmGlobalType &RHS) { return LHS.Type == RHS.Type && LHS.Mutable == RHS.Mutable; } inline bool operator!=(const WasmGlobalType &LHS, const WasmGlobalType &RHS) { return !(LHS == RHS); } std::string toString(WasmSymbolType type); std::string relocTypetoString(uint32_t type); bool relocTypeHasAddend(uint32_t type); } // end namespace wasm } // end namespace llvm #endif
term_sets.h
/* * SUPPORT TO BUILD SETS OF TERMS */ /* * A term set is implemented using the int_hset data structure. * This module provides a wrapper to construct and fill a int_hset * with terms. */ #ifndef __TERM_SETS_H #define __TERM_SETS_H #include <stdint.h> #include "terms/terms.h" #include "utils/int_hash_sets.h" /* * Build the set that contains terms a[0 ... n-1] * - a may contain several times the same term. * - duplicates are ignored */ extern int_hset_t *new_term_set(uint32_t n, const term_t *a); /* * Delete a set constructed by the previous function */ extern void free_term_set(int_hset_t *s); /* * Initialize set: * - initial content = all terms in a[0 ... n-1] */ extern void init_term_set(int_hset_t *set, uint32_t n, const term_t *a); /* * Delete a set of terms: */ static inline void delete_term_set(int_hset_t *set) { delete_int_hset(set); } #endif /* __TERM_SETS_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. */
aigprop.h
#ifndef BZLA_AIGPROP_H_INCLUDED #define BZLA_AIGPROP_H_INCLUDED #include "bzlaaig.h" #include "utils/bzlahashint.h" #include "utils/bzlahashptr.h" #include "utils/bzlamem.h" #include "utils/bzlarng.h" #define BZLA_AIGPROP_UNKNOWN 0 #define BZLA_AIGPROP_SAT 10 #define BZLA_AIGPROP_UNSAT 20 struct BzlaAIGProp { BzlaAIGMgr *amgr; BzlaIntHashTable *roots; BzlaIntHashTable *unsatroots; BzlaIntHashTable *score; BzlaIntHashTable *model; BzlaIntHashTable *parents; BzlaMemMgr *mm; BzlaRNG *rng; uint32_t loglevel; uint32_t seed; uint32_t use_restarts; uint32_t use_bandit; uint64_t nprops; struct { uint32_t moves; uint64_t props; uint32_t restarts; } stats; struct { double sat; double update_cone; double update_cone_reset; double update_cone_model_gen; double update_cone_compute_score; } time; }; typedef struct BzlaAIGProp BzlaAIGProp; BzlaAIGProp *bzla_aigprop_new_aigprop(BzlaAIGMgr *amgr, uint32_t loglevel, uint32_t seed, uint32_t use_restarts, uint32_t use_bandit, uint64_t nprops); BzlaAIGProp *bzla_aigprop_clone_aigprop(BzlaAIGMgr *clone, BzlaAIGProp *aprop); void bzla_aigprop_delete_aigprop(BzlaAIGProp *aprop); int32_t bzla_aigprop_get_assignment_aig(BzlaAIGProp *aprop, BzlaAIG *aig); void bzla_aigprop_generate_model(BzlaAIGProp *aprop, bool reset); int32_t bzla_aigprop_sat(BzlaAIGProp *aprop, BzlaIntHashTable *roots); #if 0 void bzla_aigprop_print_stats (BzlaAIGProp * aprop); void bzla_aigprop_print_time_stats (BzlaAIGProp * aprop); #endif #endif
/*** * Bitwuzla: Satisfiability Modulo Theories (SMT) solver. * * This file is part of Bitwuzla. * * Copyright (C) 2007-2022 by the authors listed in the AUTHORS file. * * See COPYING for more information on using this software. */
pkcs11_CBC_ENCRYPT_DATA_PARAMS.ml
(** Helper to define [CK_*_CBC_ENCRYPT_DATA_PARAMS] *) open Ctypes open Ctypes_helpers module type HIGHER = sig type t = { iv : string ; data : string } [@@deriving ord, yojson] end module type PARAM = sig val name : string val size : int end module Make (Param : PARAM) (Higher : HIGHER) = struct type _t type t = _t structure let t : t typ = structure Param.name let iv_size = Param.size let ( -: ) typ label = smart_field t label typ let iv = array iv_size Pkcs11_CK_BYTE.typ -: "iv" let pData = Reachable_ptr.typ Pkcs11_CK_BYTE.typ -: "pData" let length = ulong -: "length" let () = seal t let make u = let open Higher in let t = make t in (* Build the variable length string *) make_string u.data t length pData; (* Copy the fixed length string *) if String.length u.iv <> iv_size then invalid_arg "CBC_ENCRYPT_DATA_PARAMS: invalid IV size."; string_copy u.iv iv_size (CArray.start (getf t iv)); t let view t = let open Higher in { iv = string_from_carray (getf t iv) ; data = string_from_ptr ~length:(getf t length |> Unsigned.ULong.to_int) (Reachable_ptr.getf t pData) } end module CK_DES_CBC_ENCRYPT_DATA_PARAMS = Make (struct let name = "CK_DES_CBC_ENCRYPT_DATA_PARAMS" let size = 8 end) (P11_des_cbc_encrypt_data_params) module CK_AES_CBC_ENCRYPT_DATA_PARAMS = Make (struct let name = "CK_AES_CBC_ENCRYPT_DATA_PARAMS" let size = 16 end) (P11_aes_cbc_encrypt_data_params)
(** Helper to define [CK_*_CBC_ENCRYPT_DATA_PARAMS] *)
dune
(library (name dagger) (public_name prbnmcn-dagger) (modules dagger RNG log_space intf dist foldable incremental_monad cps_monad traced_monad resampling population_monad stateful_sampling_monad sequential_monad identity_monad lmh_generic lmh_inference lmh_incremental_inference smc_inference) (ocamlopt_flags -O3 (-warn-error -39)) (libraries pringo prbnmcn-cgrph)) (documentation (package prbnmcn-dagger) (mld_files index) )