filename
stringlengths 3
67
| data
stringlengths 0
58.3M
| license
stringlengths 0
19.5k
|
---|---|---|
degenerate_pslg.ml |
open Bigarray
module M = Mesh_triangle
let rectangle_pslg a1 b1 a2 b2 =
let points = Array2.of_array float64 fortran_layout
[| [| a1; a2; a2; a1 |];
[| b1; b1; b2; b2 |] |] in
let seg = Array2.of_array int fortran_layout [| [| 1; 2; 3; 4 |];
[| 2; 3; 4; 1 |] |] in
M.pslg points seg
let rectangle =
M.triangulate (rectangle_pslg 0. 1. 0. 1.) ~verbose:`VV
| |
dune |
(tests
(names test testba)
(libraries extunix ounit2 str))
| |
manager_repr.mli | (* Tezos Protocol Implementation - Low level Repr. of Managers' keys *)
(** The public key of the manager of a contract is reveled only after the
first operation. At Origination time, the manager provides only the hash
of its public key that is stored in the contract. When the public key
is actually revealed, the public key instead of the hash of the key *)
type manager_key =
| Hash of Signature.Public_key_hash.t
| Public_key of Signature.Public_key.t
type t = manager_key
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. *)
(* *)
(*****************************************************************************)
|
cron.ml |
(** Cron is a task scheduler standardized by POSIX. *)
(* Excerpt from POSIX
[https://pubs.opengroup.org/onlinepubs/9699919799/utilities/crontab.html]
Each of these patterns can be either an <asterisk> (meaning all
valid values), an element, or a list of elements separated by
<comma> characters. An element shall be either a number or two
numbers separated by a <hyphen-minus> (meaning an inclusive
range). The specification of days can be made by two fields (day of
the month and day of the week). If month, day of month, and day of
week are all <asterisk> characters, every day shall be matched. If
either the month or day of month is specified as an element or
list, but the day of week is an <asterisk>, the month and day of
month fields shall specify the days that match. If both month and
day of month are specified as an <asterisk>, but day of week is an
element or list, then only the specified days of the week
match. Finally, if either the month or day of month is specified as
an element or list, and the day of week is also specified as an
element or list, then any day matching either the month and day of
month, or the day of week, shall be matched. *)
type field =
| All
| List of element list
and element =
| Single of int
| Range of int * int
type entry = {
minute : field;
hour : field;
day_of_the_month : field;
month_of_the_year : field;
day_of_the_week : field;
command : string;
}
type t = entry list
let entries t = t
let make t = t
exception InvalidElement of string * int
type validator = int -> unit
let single validate v =
validate v;
Single v
let range validate start stop =
validate start;
validate stop;
Range (start, stop)
let valid_range what start stop k =
if not ((k >= start) && (k <= stop)) then
raise (InvalidElement (what, k))
let valid_minute = valid_range "minute" 0 59
let valid_hour = valid_range "hour" 0 23
let valid_day_of_the_month = valid_range "day of the month" 1 31
let valid_month_of_the_year = valid_range "month of the year" 1 12
let valid_day_of_the_week = valid_range "day of the week" 0 6
let make_entry
?(minute = All)
?(hour = All)
?(day_of_the_month = All)
?(month_of_the_year = All)
?(day_of_the_week = All)
command =
{ minute; hour; day_of_the_week; day_of_the_month; month_of_the_year;
command }
let minute e = e.minute
let hour e = e.hour
let day_of_the_month e = e.day_of_the_month
let month_of_the_year e = e.month_of_the_year
let day_of_the_week e = e.day_of_the_week
exception ParseError of int * string
let blanks = Str.regexp " +"
let error ?(lineno=0) msg =
raise (ParseError (lineno, msg))
let invalid_field f =
error (Printf.sprintf "`%s' is an invalid field." f)
let parse_element valid e =
match Str.(split (regexp "-") e) with
| [d] ->
(try single valid (int_of_string d) with _ -> invalid_field e)
| [start; stop] ->
(try
let start = int_of_string start
and stop = int_of_string stop in
range valid start stop
with _ -> invalid_field e)
| _ ->
invalid_field e
let parse_field valid f =
match Str.(split (regexp ",") f) with
| [] -> assert false (* By split. *)
| ["*"] -> All
| elements -> List (List.map (parse_element valid) elements)
let entry_of_string s =
match Str.(split blanks s) with
| minute :: hour :: day_of_the_month :: month_of_the_year :: day_of_the_week
:: command ->
let command =
String.concat " " command
and minute =
parse_field valid_minute minute
and hour =
parse_field valid_hour hour
and day_of_the_month =
parse_field valid_day_of_the_month day_of_the_month
and month_of_the_year =
parse_field valid_month_of_the_year month_of_the_year
and day_of_the_week =
parse_field valid_day_of_the_week day_of_the_week
in
make_entry
~minute ~hour ~day_of_the_month ~month_of_the_year ~day_of_the_week
command
| _ ->
Printf.eprintf "%s\n" s;
error "Invalid number of fields: there must be 6, separated by blanks."
let string_of_element = function
| Single k -> string_of_int k
| Range (start, stop) -> Printf.sprintf "%d-%d" start stop
let string_of_field = function
| All -> "*"
| List es -> String.concat "," (List.map string_of_element es)
let string_of_entry e =
let field a e = string_of_field (a e) in
String.concat " " [
field minute e; field hour e; field day_of_the_month e;
field month_of_the_year e; field day_of_the_week e;
e.command
]
let crontab_of_string input =
let maybe_entry_of_string lineno s =
let blank_line s = (String.length s = 0) in
let comment s = (s.[0] = '#') in
if blank_line s || comment s then [] else [
try entry_of_string s
with ParseError (_, msg) -> raise (ParseError (lineno, msg))
]
in
let lines = Str.(split (regexp "\n") input) in
List.(flatten (mapi maybe_entry_of_string lines))
let string_of_crontab t =
String.concat "\n" (List.map string_of_entry t) ^ "\n"
exception CrontabError of Unix.process_status
let crontab_command user =
Printf.sprintf "crontab %s"
(match user with None -> "" | Some u -> "-u " ^ u)
let crontab_result = function
| (lines, Unix.WEXITED 0) -> lines
| (_, Unix.WEXITED 1) -> ""
| (_, status) -> raise (CrontabError status)
let crontab ?user mode options =
let command = Printf.sprintf "%s %s" (crontab_command user) options in
let (cout, cin) as cs = Unix.open_process command in
begin match mode with
| `Read ->
X.read_all (Buffer.create 13) cout
| `Write lines ->
output_string cin lines;
""
end
|> fun out -> (out, Unix.close_process cs)
|> crontab_result
let crontab_install ?user crontable =
crontab ?user (`Write (string_of_crontab crontable)) "-" |> ignore
let crontab_get ?user () =
crontab ?user `Read "-l" |> crontab_of_string
let crontab_remove ?user () =
crontab ?user `Read "-r" |> ignore
let crontab_insert_entry ?user entry =
let table = crontab_get ?user () in
if not (List.mem entry table) then
crontab_install ?user (entry :: table)
let crontab_remove_entry ?user entry =
let table = crontab_get ?user () in
if not (List.mem entry table) then
raise Not_found
else
let table, _ = List.partition (( <> ) entry) table in
crontab_install ?user table
let version = Version.current
| (* This file is part of ocaml-crontab.
*
* Copyright (C) 2019 Yann Régis-Gianas
*
* ocaml-crontab is distributed under the terms of the MIT license. See the
* included LICENSE file for details. *) |
oo_sfml_network.mli | (** *)
(** {{:https://www.sfml-dev.org/documentation/2.5.1/group__network.php}
Online documentation for the network module} *)
type ip_address_src =
[ `FromBytes of char * char * char * char
| `FromInteger of int32
| `FromString of string
| `GetLocalAddress
| `GetPublicAddress of Oo_sfml_system.time
| `LocalHost ]
class ip_address :
ip_address_src ->
object
val address : SFIpAddress.t
method t : SFIpAddress.t
method to_integer : unit -> int32
method to_string : unit -> string
end
type write_value =
[ `Bool of bool
| `Double of float
| `Float of float
| `Int16 of int
| `Int31 of int
| `Int32 of int32
| `Int8 of int
| `String of string
| `Uint16 of int
| `Uint8 of int ]
type read_value =
[ `inBool
| `inDouble
| `inFloat
| `inInt16
| `inInt31
| `inInt32
| `inInt8
| `inString
| `inUint16
| `inUint8 ]
class packet :
object
val packet : SFPacket.t
method append : data:string -> unit
method can_read : bool
method clear : unit -> unit
method end_of_packet : bool
method get_data : unit -> string
method read : read_value list -> write_value list
method read_bool : unit -> bool
method read_double : unit -> float
method read_float : unit -> float
method read_int16 : unit -> int
method read_int31 : unit -> int
method read_int32 : unit -> int32
method read_int8 : unit -> int
method read_string : unit -> string
method read_uint16 : unit -> int
method read_uint8 : unit -> int
method t : SFPacket.t
method write : write_value list -> unit
method write_bool : bool -> unit
method write_double : float -> unit
method write_float : float -> unit
method write_int16 : int -> unit
method write_int31 : int -> unit
method write_int32 : int32 -> unit
method write_int64 : int64 -> unit
method write_int8 : int -> unit
method write_string : string -> unit
method write_uint16 : int -> unit
method write_uint8 : int -> unit
end
class tcp_socket :
object
val socket : SFTcpSocket.t
method connect :
port:int -> address:SFIpAddress.t -> timeout:SFTime.t -> unit -> unit
method destroy : unit -> unit
method receive : unit -> string
method receive_buf : buf:bytes -> int
method receive_packet : packet:packet -> unit
method send : data:string -> unit
method send_packet : packet:packet -> unit
method send_sub : data:string -> ofs:int -> len:int -> unit
method set_blocking : blocking:bool -> unit
method t : SFTcpSocket.t
end
class udp_socket :
object
val socket : SFUdpSocket.t
method bind : port:int -> ?address:SFIpAddress.t -> unit
method destroy : unit -> unit
method receive : data:bytes -> int * SFIpAddress.t * int
method receive_packet : packet:packet -> SFIpAddress.t * int
method send : data:string -> address:SFIpAddress.t -> port:int -> unit
method send_packet :
packet:packet -> address:SFIpAddress.t -> port:int -> unit
method set_blocking : blocking:bool -> unit
method t : SFUdpSocket.t
method unbind : unit -> unit
end
class http_request :
object
val request : SFHttp.Request.t
method destroy : unit -> unit
method set_body : body:string -> unit
method set_field : field:string -> value:string -> unit
method set_http_version : major:int -> minor:int -> unit
method set_method : SFHttp.http_method -> unit
method set_uri : uri:string -> unit
method t : SFHttp.Request.t
end
class http_response :
SFHttp.Response.t ->
object
val response : SFHttp.Response.t
method body : string
method destroy : unit -> unit
method get_field : field:string -> string
method major_http_version : int
method minor_http_version : int
method status : SFHttp.status
end
class http :
object
val http : SFHttp.t
method destroy : unit -> unit
method send_request :
request:http_request ->
?timeout:Oo_sfml_system.time -> unit -> http_response
method set_host : host:string -> ?port:int -> unit -> unit
end
class response :
SFFtp.response ->
object
val resp : SFFtp.response
method destroy : unit -> unit
method get_message : unit -> string
method get_status : unit -> SFFtp.status
method is_ok : unit -> bool
end
class directory_response :
SFFtp.directoryResponse ->
object
val dir_resp : SFFtp.directoryResponse
method destroy : unit -> unit
method get_directory : unit -> string
method get_message : unit -> string
method get_status : unit -> SFFtp.status
method is_ok : unit -> bool
end
class listing_response :
'a ->
object
val lst_resp : 'a
method destroy : unit -> SFFtp.listingResponse -> unit
method get_listing : unit -> SFFtp.listingResponse -> string array
method get_message : unit -> SFFtp.listingResponse -> string
method get_status : unit -> SFFtp.listingResponse -> SFFtp.status
method is_ok : unit -> SFFtp.listingResponse -> bool
end
class ftp :
object
val ftp : SFFtp.ftp
method change_directory : directory:string -> response
method connect :
server:ip_address ->
?port:int -> ?timeout:Oo_sfml_system.time -> unit -> response
method create_directory : name:string -> response
method delete_directory : name:string -> response
method delete_file : name:string -> response
method destroy : unit -> unit
method disconnect : unit -> response
method download :
distantFile:string ->
destPath:string -> mode:SFFtp.transferMode -> response
method get_directory_listing : directory:string -> listing_response
method get_working_directory : unit -> directory_response
method keep_alive : unit -> response
method login :
SFFtp.ftp -> userName:string -> password:string -> response
method login_anonymous : unit -> response
method parent_directory : unit -> response
method rename_file : file:string -> newName:string -> response
method send_command : command:string -> parameter:string -> response
method upload :
localFile:string ->
destPath:string -> mode:SFFtp.transferMode -> response
end
| (** *)
(** {{:https://www.sfml-dev.org/documentation/2.5.1/group__network.php} |
ref.ml | (* For documentation please refer to the [Tezos_wasmer] module. *)
open Api
(* TODO: https://gitlab.com/tezos/tezos/-/issues/4026
Ensure that ownership and lifetime of [Types.Ref.t] is respected.
*)
type t = Ref of Types.Ref.t Ctypes.ptr
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2022 TriliTech <contact@trili.tech> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
ppx_main.ml |
open Mparsetree.Ast_cur
open Std
let error = Util.error
module List = CCListLabels
module U = Std.Util
module Extract_types = struct
type enum_entry = {
cdecl : constructor_declaration;
enum_cname : string;
}
type enum_type =
| Enum_normal
| Enum_bitmask
| Enum_both
type enum = {
ename : string;
el : enum_entry list;
ename_c : string;
enum_type : enum_type;
etypedef : bool;
edecl : type_declaration;
eunexpected : Marshal_types.expr option;
eunexpected_bits : Marshal_types.expr option;
}
type field = {
field_name : string;
field_expr : expression;
field_cname : string;
field_loc : Ast_helper.loc;
}
type struct_type =
| Union
| Struct_normal
| Struct_record
| Struct_both
type structure = {
sname : string;
sl : field list;
sname_c : string;
stypedef : bool;
stype : struct_type;
sloc : Ast_helper.loc;
}
type ctyp =
| Enum of enum
| Struct of structure
end
module Extract : sig
include module type of struct
include Extract_types
end
val variable_from_pattern_constr : pattern -> string option * bool
val variable_from_pattern : pattern -> string option
val fun_def :
lookup:string ->
bool ->
core_type ->
expression * (arg_label * expression) list * bool
val constant_string : expression -> string option
val type_decl : rec_flag -> type_declaration list -> ctyp list
end = struct
let rec variable_from_pattern_constr a =
match a.ppat_desc with
| Ppat_var { txt = "" | "_"; _ } -> (None, false)
| Ppat_var s -> (Some s.txt, false)
| Ppat_constraint (s, _) -> (fst (variable_from_pattern_constr s), true)
| _ -> (None, false)
let variable_from_pattern a = variable_from_pattern_constr a |> fst
let unsupported_typ loc = error ~loc "type description not supported"
let check_no_attribs = function
| [] -> ()
| a :: _ ->
error ~loc:a.attr_loc "unsupported attribute: %S" a.attr_name.txt
let check_no_attribs_t t = check_no_attribs t.ptyp_attributes
let remove_attrib str l = List.filter l ~f:(fun x -> x.attr_name.txt <> str)
let get_remove name attr =
let at =
List.exists attr ~f:(fun x ->
if x.attr_name.txt <> name then false
else
match x.attr_payload with
| PStr [] -> true
| _ -> error ~loc:x.attr_loc "surprising content in %s" name)
in
(at, if not at then attr else remove_attrib name attr)
let rec is_simple = function
| Lident _ -> true
| Ldot (t, _) -> is_simple t
| Lapply _ -> false
let rec type_to_ctype ~lookup typ =
match typ.ptyp_desc with
| Ptyp_constr (({ txt; _ } as a), []) when is_simple txt ->
check_no_attribs_t typ;
let c =
match (lookup, txt) with
| Some l, Lident l' when l = l' -> true
| _ -> false
in
(Ast_helper.Exp.ident ~loc:a.loc a, c)
| Ptyp_constr ({ txt = Lident "ptr"; loc }, [ a ]) ->
check_no_attribs_t typ;
let p, c = type_to_ctype ~lookup a in
(([%expr Ctypes.ptr [%e p]] [@metaloc loc]), c)
| Ptyp_constr ({ txt = Lident "ptr_opt"; loc }, [ a ]) ->
check_no_attribs_t typ;
let p, c = type_to_ctype ~lookup a in
(([%expr Ctypes.ptr_opt [%e p]] [@metaloc loc]), c)
| Ptyp_constr ({ txt = Lident "static_funptr"; loc }, [ a ]) ->
check_no_attribs_t typ;
let t, c = type_to_ctype_fn ~lookup a in
(([%expr Ctypes.static_funptr [%e t]] [@metaloc loc]), c)
| Ptyp_constr
({ txt = Lident (("funptr" | "funptr_opt") as ns); loc }, [ a ]) ->
U.with_loc loc @@ fun () ->
let t, c = type_to_ctype_fn ~lookup a in
let check_errno, at = get_remove "check_errno" typ.ptyp_attributes in
let runtime_lock, at = get_remove "release_runtime_lock" at in
let thread_registration, at = get_remove "thread_registration" at in
check_no_attribs at;
let h = function true -> [%expr true] | false -> [%expr false] in
let f =
match ns with
| "funptr_opt" -> [%expr Foreign.funptr_opt]
| _ -> [%expr Foreign.funptr]
in
( [%expr
[%e f] ~check_errno:[%e h check_errno]
~runtime_lock:[%e h runtime_lock]
~thread_registration:[%e h thread_registration] [%e t]],
c )
| _ -> unsupported_typ typ.ptyp_loc
and type_to_ctype_fn ~lookup typ =
let loc = typ.ptyp_loc in
check_no_attribs_t typ;
match typ.ptyp_desc with
| Ptyp_arrow
( Nolabel,
({ ptyp_desc = Ptyp_constr _; _ } as t1),
({ ptyp_desc = Ptyp_constr _; _ } as t2) ) ->
let t1, c1 = type_to_ctype ~lookup t1
and t2, c2 = type_to_ctype ~lookup t2 in
(([%expr [%e t1] @-> returning [%e t2]] [@metaloc loc]), c1 || c2)
| Ptyp_arrow
( Nolabel,
({ ptyp_desc = Ptyp_constr _; _ } as t1),
({ ptyp_desc = Ptyp_arrow _; _ } as t2) ) ->
let t1, c1 = type_to_ctype ~lookup t1
and t2, c2 = type_to_ctype_fn ~lookup t2 in
(([%expr [%e t1] @-> [%e t2]] [@metaloc loc]), c1 || c2)
| _ -> error ~loc "unsupported Ctypes.fn definition"
let rec fun_def ~lookup is_inline accu found typ =
let loc = typ.ptyp_loc in
let type_conf is_inline t =
let is_ocaml_typ, attribs = get_remove "ocaml_type" t.ptyp_attributes in
if is_ocaml_typ = false || is_inline = false then type_to_ctype ~lookup t
else
let () = check_no_attribs attribs in
let t = { t with ptyp_attributes = attribs } in
let e = U.marshal_to_str_expr t in
(([%expr Ctypes.ppxc__private_ocaml_typ [%e e]] [@metaloc loc]), false)
in
match typ.ptyp_desc with
| Ptyp_constr _ ->
if accu = [] then error ~loc "function expected";
let r, f = type_conf is_inline typ in
(r, List.rev accu, f || found)
| Ptyp_arrow (l, t1, t2) ->
check_no_attribs_t typ;
let t1', found' = type_conf is_inline t1 in
(match l with
| Nolabel | Labelled _ -> ()
| Optional _ ->
error ~loc:t1.ptyp_loc "optional parameters are not supported");
fun_def is_inline ~lookup ((l, t1') :: accu) (found' || found) t2
| _ -> unsupported_typ typ.ptyp_loc
let fun_def ~lookup i t = fun_def ~lookup:(Some lookup) i [] false t
let constant_string e =
match e.pexp_desc with
| Pexp_constant (Pconst_string (s, _, _)) -> Some s
| _ -> None
let get_cname ~def l =
let res =
List.find_map l ~f:(fun x ->
if x.attr_name.txt <> "cname" then None
else
match x.attr_payload with
| PStr
[
{
pstr_desc =
Pstr_eval
( {
pexp_desc = Pexp_constant (Pconst_string (x, _, _));
_;
},
[] );
_;
};
] ->
Some x
| _ -> error ~loc:x.attr_loc "unsupported expression in cname")
in
match res with None -> (def, l) | Some x -> (x, remove_attrib "cname" l)
let get_unexpected unexpected l =
let res =
List.find_map l ~f:(fun x ->
if x.attr_name.txt <> unexpected then None
else
match x.attr_payload with
| PStr
[
{
pstr_desc =
Pstr_eval (({ pexp_desc = Pexp_fun _; _ } as e), []);
_;
};
] ->
Some e
| _ ->
error ~loc:x.attr_loc "unsupported expression in %s" unexpected)
in
match res with
| None -> (None, l)
| Some _ as x -> (x, remove_attrib unexpected l)
let get_unexpected_bits = get_unexpected "unexpected_bits"
let get_unexpected = get_unexpected "unexpected"
include Extract_types
let extract_enum_entry = function
| {
pcd_name;
pcd_args = Pcstr_tuple [];
pcd_res = None;
pcd_loc = _;
pcd_attributes;
} as whole ->
let name = pcd_name.txt in
let cname, attribs = get_cname ~def:name pcd_attributes in
check_no_attribs attribs;
let cdecl = { whole with pcd_attributes = [] } in
{ cdecl; enum_cname = cname }
| { pcd_loc; _ } -> error ~loc:pcd_loc "Unsupported constructor type"
let extract_field lookup
{ pld_name; pld_mutable; pld_type; pld_loc; pld_attributes } =
if pld_mutable <> Immutable then
error ~loc:pld_loc "only immutable is possible";
let field_name = pld_name.txt in
let field_expr, field_recursive = type_to_ctype ~lookup pld_type in
if field_recursive then
error ~loc:pld_loc "recursive record views (%s) are not possible"
field_name;
let field_cname, attribs = get_cname ~def:field_name pld_attributes in
check_no_attribs attribs;
{ field_name; field_expr; field_cname; field_loc = pld_loc }
let type_decl rec' = function
| {
ptype_name;
ptype_params = [];
ptype_cstrs = [];
ptype_private = Public;
ptype_manifest = _;
ptype_attributes;
ptype_kind = Ptype_variant (_ :: _ as l);
ptype_loc;
} as whole ->
let ename = ptype_name.txt in
let ename_c, attribs = get_cname ~def:ename ptype_attributes in
let etypedef, attribs = get_remove "typedef" attribs in
let ebitmask, attribs = get_remove "as_bitmask" attribs in
let eunexpected, attribs = get_unexpected attribs in
let eunexpected_bits, attribs = get_unexpected_bits attribs in
let enum_type =
match ebitmask with false -> Enum_normal | true -> Enum_bitmask
in
let with_bitmask, attribs = get_remove "with_bitmask" attribs in
let enum_type =
match with_bitmask with
| false -> enum_type
| true ->
if enum_type <> Enum_normal then
error ~loc:ptype_loc "either as_bitmask or with_bitmask - not both";
Enum_both
in
check_no_attribs attribs;
let el = List.map l ~f:extract_enum_entry in
let edecl =
{
whole with
ptype_kind = Ptype_variant (List.map el ~f:(fun x -> x.cdecl));
ptype_attributes = [];
}
in
Enum
{
ename;
el;
ename_c;
etypedef;
edecl;
enum_type;
eunexpected;
eunexpected_bits;
}
| {
ptype_name;
ptype_params = [];
ptype_cstrs = [];
ptype_private = Public;
ptype_manifest = None;
ptype_attributes;
ptype_kind = Ptype_record (_ :: _ as l);
ptype_loc;
} ->
let sname = ptype_name.txt in
let sname_c, attribs = get_cname ~def:sname ptype_attributes in
let stypedef, attribs = get_remove "typedef" attribs in
let union, attribs = get_remove "union" attribs in
let as_record, attribs = get_remove "as_record" attribs in
let with_record, attribs = get_remove "with_record" attribs in
check_no_attribs attribs;
let stype =
match union with
| true ->
if as_record then
error "@@@@union and @@@@as_record are mutually exclusive";
if with_record then
error "@@@@union and @@@@with_record are mutually exclusive";
Union
| false -> (
match as_record with
| true ->
if with_record then
error "@@@@as_record and @@@@with_record are mutually exclusive";
Struct_record
| false -> (
match with_record with
| true -> Struct_both
| false -> Struct_normal))
in
let lookup =
if rec' <> Recursive then None
else
match stype with
| Union | Struct_normal -> None
| Struct_record | Struct_both -> Some sname
in
let sl = List.map ~f:(extract_field lookup) l in
Struct { sname; sl; sname_c; stypedef; stype; sloc = ptype_loc }
| { ptype_loc; _ } -> error ~loc:ptype_loc "unsupported type definition"
let type_decl rec' l = List.map ~f:(type_decl rec') l
end
module C_content = struct
let write_file () =
if Options.(!mode = Regular) then
match (!Options.c_output_file, !Script_result.c_source) with
| Some fln, Some source -> (
Options.c_output_file := None;
match fln with
| "-" -> output_string stdout source
| _ ->
CCIO.with_out ~flags:[ Open_creat; Open_trunc; Open_binary ] fln
(fun ch -> output_string ch source))
| Some _, None ->
prerr_endline
"no c file necessary, remove it from the command-line invocation and update your build instructions";
exit 2
| None, None -> ()
| None, Some _ ->
prerr_endline "output file for c code missing";
exit 2
end
module Id : sig
type t = {
id : int;
script_param : expression;
expr : expression;
stri : structure_item;
}
val get : ?loc:Ast_helper.loc -> unit -> t
val get_usage_id : unit -> expression * attributes
val get_tdl_entries_id : unit -> int * structure_item
end = struct
open Ast_helper
type t = {
id : int;
script_param : expression;
expr : expression;
stri : structure_item;
}
let cnt = ref 0
let with_id f =
let id = !cnt in
incr cnt;
f id
let get ?(loc = !Ast_helper.default_loc) () =
with_id @@ fun id ->
let (t : Marshal_types.id_loc_param) = (id, loc) in
let loc_id_param = Marshal.to_string t [] in
let script_param = U.str_expr ~loc loc_id_param in
let attrs = [ Attributes.replace_expr_attrib ] in
let expr = U.int_expr ~loc ~attrs id in
let stri = Str.eval ~attrs expr in
{ id; script_param; expr; stri }
let get_usage_id attr_string () =
with_id @@ fun id ->
let script_param = U.int_expr id in
let loc = !Ast_helper.default_loc in
let st = [%stri [%e script_param]] in
let attrs =
let x = U.mk_loc attr_string in
[ Attr.mk x (PStr [ st ]) ]
in
(script_param, attrs)
let get_usage_id = get_usage_id Attributes.replace_attr_string
let get_tdl_entries_id () =
with_id @@ fun id ->
let expr = U.int_expr id in
(id, Str.eval ~attrs:[ Attributes.tdl_attrib ] expr)
end
let htl_tdl_entries = Hashtbl.create 32
module OSTypes = Ptree.OSTypes
module H : sig
val constant : (arg_label * expression) list -> expression
val bound_constant : string -> (arg_label * expression) list -> expression
val foreign_value : (arg_label * expression) list -> expression
val header : (arg_label * expression) list -> expression
val seal : (arg_label * expression) list -> expression
val external' :
is_inline:bool ->
remove_labels:bool ->
return_errno:bool ->
release_runtime_lock:bool ->
noalloc:bool ->
attrs:Ast_helper.attrs ->
value_description ->
structure_item
val foreign : ?prefix:string -> (arg_label * expression) list -> expression
val fn : string -> expression -> expression
val type_decl :
enforce_union:bool ->
c_bitmask:bool ->
rec_flag ->
type_declaration list ->
structure_item
val field : ?prefix:string -> (arg_label * expression) list -> expression
val int_alias :
mod_name:string ->
[< `Aint | `Int | `Uint ] ->
(arg_label * expression) list ->
structure_item
val opaque :
string ->
Ast_helper.attrs ->
(arg_label * expression) list ->
structure_item
val abstract :
string ->
Ast_helper.attrs ->
(arg_label * expression) list ->
structure_item
val ocaml_funptr :
acquire_runtime:bool ->
thread_registration:bool ->
string ->
expression ->
core_type ->
structure_item
val type_cb :
Ast_helper.str_opt ->
string ->
(arg_label * expression) list ->
structure_item
val typ : string -> expression -> expression
val union : string -> (arg_label * expression) list -> structure_item
val structure : string -> (arg_label * expression) list -> structure_item
val pexp_const : string -> expression -> expression
end = struct
open Ast_helper
module Topscript = Ptree.Topscript
module Impl_mod = Ptree.Impl_mod
module Type_mod = Ptree.Type_mod
let error_msg s = function
| [] -> error "arguments missing for %s" s
| _ -> error "too many or too few arguments for %s" s
let constant = function
| [ (Nolabel, str_expr); (Nolabel, type_expr) ] ->
let loc = !Ast_helper.default_loc in
let id = Id.get () in
let tx = U.marshal_to_str_expr type_expr in
let f f =
[%stri
let () =
let (ppxc__s : string) = [%e str_expr]
and (ppxc__t : _ Ctypes.typ) = [%e type_expr] in
[%e f] [%e id.Id.script_param] ppxc__s [%e tx] ppxc__t]
in
Topscript.add_extract @@ f [%expr Ppxc__script.Extract.constant];
Topscript.add_build_external @@ f [%expr Ppxc__script.Build.constant];
let prefix =
match Extract.constant_string str_expr with
| None -> None
| Some s -> Some (if String.length s < 20 then s else String.sub s 0 20)
in
let name = U.safe_mlname ?prefix () in
Impl_mod.add_named ~retype:true ~name_check:false name id.Id.expr
| l -> error_msg "constant" l
let bound_constant name = function
| [ (Nolabel, str_expr); (Nolabel, type_expr) ] ->
(match Extract.constant_string str_expr with
| Some _ -> ()
| None ->
U.error ~loc:str_expr.pexp_loc
"'let%%c ... = constant' requires a string literal");
let id = Id.get () in
let loc = !Ast_helper.default_loc in
Topscript.add_extract_phase0
[%stri
let () =
let (ppxc__s : string) = [%e str_expr] in
Ppxc__script.Extract_phase0.bound_constant [%e id.Id.script_param]
ppxc__s];
let tx = U.marshal_to_str_expr type_expr in
let f f =
[%stri
let [%p U.mk_pat name] =
let (ppxc__s : string) = [%e str_expr]
and (ppxc__t : _ Ctypes.typ) = [%e type_expr] in
[%e f] [%e id.Id.script_param] ppxc__s [%e tx] ppxc__t]
in
Topscript.add_extract @@ f [%expr Ppxc__script.Extract.bound_constant];
Topscript.add_build_external
@@ f [%expr Ppxc__script.Build.bound_constant];
Impl_mod.add_named ~retype:true ~name_check:true name id.Id.expr
| l -> error_msg "constant" l
let marshal_expr (e : Marshal_types.expr) = U.marshal_to_str_expr e
let register_fun id =
let loc = !Ast_helper.default_loc in
Topscript.add_extract
[%stri
let () = Ppxc__script.Extract.register_fun_place [%e id.Id.script_param]]
let foreign_value = function
| [ (Nolabel, str_expr); (Nolabel, typ_expr) ] ->
let prefix = Extract.constant_string str_expr in
let name = U.safe_mlname ?prefix () in
let name_expr = U.str_expr name in
let id_stri_external = Id.get () in
let id_stri_expr = Id.get () in
register_fun id_stri_external;
let texpr = marshal_expr typ_expr in
let loc = !Ast_helper.default_loc in
Topscript.add_build_external
[%stri
let () =
let (ppxc__s : string) = [%e str_expr]
and (ppxc__t : _ Ctypes.typ) = [%e typ_expr] in
Ppxc__script.Build.foreign_value
[%e id_stri_external.Id.script_param]
[%e id_stri_expr.Id.script_param] ppxc__t ppxc__s [%e name_expr]
[%e texpr]];
Impl_mod.add_external_anon id_stri_external.Id.stri id_stri_expr.Id.stri
name
| l -> error_msg "foreign_value" l
let header = function
| [ (Nolabel, x) ] ->
(match Extract.constant_string x with
| Some _ -> ()
| None -> error "'header' requires a string literal");
let loc = !Ast_helper.default_loc in
Topscript.add_extract_phase0
[%stri
let () =
let ppxc__1 : string = [%e x] in
Ppxc__script.Extract_phase0.header ppxc__1];
Topscript.add_extract
[%stri
let () =
let ppxc__1 : string = [%e x] in
Ppxc__script.Extract.header ppxc__1];
[%expr ()]
| l -> error_msg "header" l
let field ?name ?prefix ~structure ~str_expr type_expr =
let loc = !Ast_helper.default_loc in
let id = Id.get () in
let n = match name with None -> U.safe_mlname ?prefix () | Some s -> s in
let p = U.mk_pat n in
let f func =
[%stri
let [%p p] =
let (ppxc__st
: (_, [< `Struct | `Union ]) Ctypes.structured Ctypes.typ) =
[%e structure]
and (ppxc__s : string) = [%e str_expr]
and (ppxc__t : _ Ctypes.typ) = [%e type_expr] in
[%e func] [%e id.Id.script_param] ppxc__st ppxc__s ppxc__t]
in
Topscript.add_extract @@ f [%expr Ppxc__script.Extract.field];
Topscript.add_build_external @@ f [%expr Ppxc__script.Build.field];
let nexpr =
[%expr
Ppx_cstubs.Ppx_cstubs_internals.add_field [%e structure] [%e str_expr]
[%e id.Id.expr] [%e type_expr]]
in
let nc = name <> None in
let res = Impl_mod.add_named ~retype:true ~name_check:nc n nexpr in
OSTypes.types_maybe_used ();
(n, res)
let seal = function
| [ (Nolabel, seal_struct) ] ->
let id_size = Id.get () in
let id_align = Id.get () in
let loc = !Ast_helper.default_loc in
let f f =
[%stri
let () =
let (ppxc__s
: (_, [< `Struct | `Union ]) Ctypes.structured Ctypes.typ) =
[%e seal_struct]
in
[%e f] [%e id_size.Id.script_param] [%e id_align.Id.script_param]
ppxc__s]
in
Topscript.add_extract @@ f [%expr Ppxc__script.Extract.seal];
Topscript.add_build_external @@ f [%expr Ppxc__script.Build.seal];
let nexpr =
[%expr
Ppx_cstubs.Ppx_cstubs_internals.seal [%e seal_struct]
~size:[%e id_size.Id.expr] ~align:[%e id_align.Id.expr]]
in
OSTypes.types_maybe_used ();
Impl_mod.add_unit nexpr
| l -> error_msg "seal" l
let is_ocaml_operator = function
| "mod" | "or" | "land" | "lor" | "lxor" | "lsl" | "lsr" | "asr" -> true
| "" -> false
| c -> (
match c.[0] with
| '!' | '#' | '$' | '%' | '&' | '*' | '+' | '-' | '/' | '<' | '=' | '>'
| '?' | '@' | '^' | '|' | '~' ->
true
| _ -> false)
let rec build_ctypes_fn params ret =
match params with
| [] ->
let loc = ret.pexp_loc in
[%expr returning [%e ret]]
| hd :: tl ->
let loc = hd.pexp_loc in
let e = build_ctypes_fn tl ret in
[%expr [%e hd] @-> [%e e]]
let add_stri_to_all script =
Topscript.add_extract script;
Topscript.add_build_external script;
Impl_mod.add_entry script
let external' ~is_inline ~remove_labels ~return_errno ~release_runtime_lock
~noalloc ~attrs v =
let name = v.pval_name.txt in
let c_name =
match v.pval_prim with
| [ "" ] | [ "_" ] -> error ~loc:v.pval_loc "function name missing"
| [ a ] -> a
| _ -> error ~loc:v.pval_loc "too many c functions referenced"
in
if is_inline = false then (
let c = c_name.[0] in
if U.safe_ascii_only c_name <> c_name || (c >= '0' && c <= '9') then
error "invalid identifier for c function:%S" c_name;
if remove_labels then
error ~loc:v.pval_loc "remove_labels only supported for inline code");
let remove_labels =
remove_labels || (is_inline && is_ocaml_operator name)
in
let ret, el, rec' = Extract.fun_def ~lookup:name is_inline v.pval_type in
let fun_expr = build_ctypes_fn (List.map ~f:snd el) ret in
let id_stri_expr = Id.get () in
let id_stri_ext = Id.get () in
let name_impl = if rec' then U.safe_mlname ~prefix:name () else name in
let uniq_ref_id, fres =
Impl_mod.add_external ~name_check:(not rec') id_stri_ext.Id.stri
id_stri_expr.Id.stri ~name:name_impl
in
(if rec' then
let mp = Impl_mod.get_mod_path () in
let n = U.mk_ident_l [ name_impl ] in
let r = Uniq_ref.make mp ~retype:false name n in
(* slightly redundant. But it's an usual to name the function like
a Ctypes.typ value that is used to construct the function. I won't
waste time for a nicer solution... *)
let loc = !Ast_helper.default_loc in
Impl_mod.add_entry
[%stri
include struct
[@@@ocaml.warning "-32"]
[%%i r.Uniq_ref.topmod_vb]
[%%i r.Uniq_ref.topmod_ref]
end]);
let vb = Vb.mk ~attrs (U.mk_pat name) fres in
let fres = Str.value Nonrecursive [ vb ] in
let marshal_info =
let open Marshal_types in
let s =
{
el;
ret;
release_runtime_lock;
noalloc;
return_errno;
is_inline;
remove_labels;
c_name;
prim_name = name_impl;
uniq_ref_id;
}
in
U.marshal_to_str_expr s
in
if is_inline then (* order matters *)
register_fun id_stri_expr;
register_fun id_stri_ext;
let loc = !Ast_helper.default_loc in
Topscript.add_build_external
[%stri
let () =
let (ppxc__fn : _ Ctypes.fn) = [%e fun_expr] in
Ppxc__script.Build.external' [%e id_stri_ext.Id.script_param]
[%e id_stri_expr.Id.script_param] ppxc__fn
~marshal_info:[%e marshal_info]];
(* create a dummy function that can be referenced in Ctypes.view, etc.
Constraint necessary to avoid warning 21 (unsound type, never returns) *)
let script = [%expr ([%e ret] : 'b Ctypes.typ)] in
let script =
[%expr
[%e Gen_ml.stdlib_fun "ignore"] [%e script];
Ctypes.ppxc__unavailable [%e U.str_expr name]]
in
let script =
ListLabels.fold_right ~init:script el ~f:(fun (l, _) ac ->
let nac = Exp.fun_ l None (Pat.any ()) ac in
if ac == script then
Exp.constraint_ nac @@ Typ.arrow l (Typ.var "a") (Typ.var "b")
else nac)
in
let script = U.named_stri name script in
Topscript.add_extract script;
Topscript.add_build_external script;
fres
let check_reserved_type s =
if Hashtbl.mem Keywords.htl_types s then
error "type name %S is reserverd, choose another name" s
let foreign ?prefix l =
let find_first_unlabelled l =
List.find_mapi l ~f:(fun i el ->
match el with Nolabel, _ -> Some (i, el) | _ -> None)
in
let typ_expr =
match List.rev l |> find_first_unlabelled with
| None -> error "function signature in foreign not found"
| Some (_, l) -> snd l
in
let typ_expr = marshal_expr typ_expr in
let ocaml_name =
let t =
List.find_map l ~f:(function
| Nolabel, e -> Extract.constant_string e
| _ -> None)
in
match t with
| None -> U.safe_mlname ?prefix ()
| Some s -> U.safe_mlname ~prefix:s ()
in
let id_stri_external = Id.get () in
let id_stri_expr = Id.get () in
register_fun id_stri_external;
let loc = !Ast_helper.default_loc in
let f_expr =
[%expr
Ppxc__script.Build.foreign [%e id_stri_external.Id.script_param]
[%e id_stri_expr.Id.script_param]
~ocaml_name:[%e U.str_expr ocaml_name] ~typ_expr:[%e typ_expr]]
in
let call = Exp.apply f_expr l in
Topscript.add_build_external [%stri let () = [%e call]];
Impl_mod.add_external_anon id_stri_external.Id.stri id_stri_expr.Id.stri
ocaml_name
let fn binding_name expr =
let loc = !Ast_helper.default_loc in
let t = [%type: _ Ctypes.fn] in
let pat = U.mk_pat_pconstr t binding_name in
Topscript.add_extract [%stri let [%p pat] = [%e expr]];
let id_expr, attrs = Id.get_usage_id () in
Topscript.add_build_external
[%stri
let [%p pat] = Ppxc__script.Build.reg_trace_fn [%e id_expr] [%e expr]];
Impl_mod.add_named ~constr:t ~retype:true ~attrs binding_name expr
let add_ctyp ~constr ?extract_expr ?build_expr ?(name_check = true) ~retype
bname expr =
let loc = !Ast_helper.default_loc in
let pat = U.mk_pat_pconstr constr bname in
let extract_expr = match extract_expr with None -> expr | Some s -> s in
Topscript.add_extract [%stri let [%p pat] = [%e extract_expr]];
let id_expr, attrs = Id.get_usage_id () in
let script =
let e = match build_expr with None -> expr | Some e -> e in
[%stri let [%p pat] = Ppxc__script.Build.reg_trace [%e id_expr] [%e e]]
in
Topscript.add_build_external script;
Impl_mod.add_named ~constr ~retype ~name_check ~attrs bname expr
let add_type_h ?tdl typ' name =
let t = Str.type_ Recursive [ typ' ] in
add_stri_to_all t;
match tdl with
| None -> ()
| Some id -> (
let t' top =
let name = typ'.ptype_name.txt in
let constr = Impl_mod.create_type_ref name in
let typ' = { typ' with ptype_manifest = Some constr } in
let typ' =
if top then typ'
else
let p = [ Attributes.manifest_replace_attrib ] in
{ typ' with ptype_attributes = p }
in
Str.type_ Recursive [ typ' ]
in
Type_mod.add_entry (t' true);
Hashtbl.add htl_tdl_entries id (t' false);
match OSTypes.add_abstract name with
| None -> ()
| Some x -> Hashtbl.add htl_tdl_entries id x)
let union_struct ~tdl_entry_id ?alias_name ~type_name ~stype xtype orig_name =
let loc = !Ast_helper.default_loc in
let alias_name = match alias_name with None -> orig_name | Some s -> s in
let t = Type.mk ~kind:Ptype_abstract (U.mk_loc type_name) in
let tdl =
if stype = Extract.Struct_record then None else Some tdl_entry_id
in
add_type_h ?tdl t type_name;
let is_union =
match stype with
| Extract.Union -> true
| Extract.Struct_normal | Extract.Struct_record | Extract.Struct_both ->
false
in
let constr =
let x = U.mk_typc type_name in
if is_union then [%type: [%t x] Ctypes.union Ctypes.typ]
else [%type: [%t x] Ctypes.structure Ctypes.typ]
in
let expr, expr_top =
let sexpr =
match xtype with
| `Typedef _ -> U.str_expr ""
| `Named s -> U.str_expr s
| `From_expr e -> e
in
if is_union then
( [%expr Ctypes.union [%e sexpr]],
[%expr
let __s : string = [%e sexpr] in
Ctypes.ppxc__private_union __s] )
else
( [%expr Ctypes.structure [%e sexpr]],
[%expr
let __s : string = [%e sexpr] in
Ctypes.ppxc__private_structure __s] )
in
let add expr expr_top =
match stype with
| Extract.Struct_record ->
let e = U.named_stri ~constr alias_name expr_top in
Topscript.add_extract e;
Topscript.add_build_external e;
U.named_stri ~constr alias_name expr |> Impl_mod.add_entry
| Extract.Struct_normal | Extract.Struct_both | Extract.Union ->
add_ctyp ~constr ~build_expr:expr_top ~extract_expr:expr_top
~retype:false alias_name expr
|> U.named_stri ~constr orig_name
|> Hashtbl.add htl_tdl_entries tdl_entry_id
in
match xtype with
| `Named _ | `From_expr _ -> add expr expr_top
| `Typedef sname_c ->
let f e = [%expr Ctypes.typedef [%e e] [%e U.str_expr sname_c]] in
let expr = f expr in
let expr_top = f expr_top in
add expr expr_top
let type_decl ~enforce_union ~c_bitmask type_rec_flag tl =
let loc = !Ast_helper.default_loc in
if tl = [] then error "empty type definition";
let open Extract_types in
let record_name s = s ^ "_record" in
let bitmask_name s = s ^ "_bitmask" in
let tdl_entry_id, tdl_entry = Id.get_tdl_entries_id () in
let private_pref =
if type_rec_flag = Recursive then Std.identity
else
let s =
let open Location in
let open Lexing in
let loc = !Ast_helper.default_loc in
Printf.sprintf "__ppxc__private_%x_%x_" loc.loc_start.pos_lnum
loc.loc_start.pos_cnum
in
fun x -> s ^ x
in
let unhide x =
let add name =
let e = U.mk_ident @@ private_pref name in
let stri = U.no_warn_unused name e in
add_stri_to_all stri
in
match x with
| Enum { ename; enum_type; _ } ->
add ename;
if enum_type = Enum_both then add @@ bitmask_name ename
| Struct x ->
add x.sname;
if x.stype = Struct_both then add @@ record_name x.sname
in
let fields { sname; sl; stype; _ } =
let orig_name = sname in
let alias_name = private_pref orig_name in
let struct_expr = U.mk_ident alias_name in
let fnames =
List.map sl
~f:(fun { field_name; field_expr; field_cname; field_loc } ->
U.with_loc field_loc @@ fun () ->
let str_expr = U.str_expr field_cname in
let name =
match stype with
| Struct_record -> None
| Union | Struct_normal | Struct_both -> Some field_name
in
let n, e =
field ?name ~prefix:field_name ~structure:struct_expr ~str_expr
field_expr
in
(match stype with
| Struct_record -> ()
| Union | Struct_normal | Struct_both ->
let t = U.mk_typc orig_name in
let t =
if stype = Union then [%type: [%t t] Ctypes.union]
else [%type: [%t t] Ctypes.structure]
in
let t = [%type: (_, [%t t]) Ctypes.field] in
let x = U.named_stri ~constr:t field_name e in
Hashtbl.add htl_tdl_entries tdl_entry_id x);
n)
in
ignore (seal [ (Nolabel, struct_expr) ] : expression);
match stype with
| Union | Struct_normal -> ()
| Struct_record | Struct_both ->
(* Generate the view for the type *)
let alias_name, orig_name =
if stype <> Struct_both then (alias_name, orig_name)
else (record_name alias_name, record_name orig_name)
in
let s =
List.map sl ~f:(fun s -> (s.field_name, s.field_loc, s.field_expr))
in
let mod_path = Impl_mod.get_mod_path () in
let r = Gen_ml.gen_record_stris ~mod_path ~type_name:orig_name s in
List.iter ~f:add_stri_to_all r.Gen_ml.r_stri_top;
List.iter
~f:(Hashtbl.add htl_tdl_entries tdl_entry_id)
r.Gen_ml.r_stri_bottom;
List.iter ~f:Type_mod.add_entry r.Gen_ml.r_stri_type_mod;
(match OSTypes.add_struct_view orig_name with
| None -> ()
| Some b -> Hashtbl.add htl_tdl_entries tdl_entry_id b);
let view =
let init = [%expr ppxc__res] in
let param = U.mk_ident_l [ Myconst.private_prefix ^ "param" ] in
let expr =
List.fold_left2 ~init sl fnames ~f:(fun ac el fname ->
let fi = U.mk_lid el.field_name in
let v = Exp.field param fi in
let f = U.mk_ident fname in
[%expr
let () = Ctypes.setf ppxc__res [%e f] [%e v] in
[%e ac]])
in
let write =
[%expr
fun ppxc__param ->
let ppxc__res = Ctypes.make [%e struct_expr] in
[%e expr]]
in
let init =
Exp.record
(List.map sl ~f:(fun el ->
let l = U.mk_lid el.field_name in
let e = Exp.ident l in
(l, e)))
None
in
let expr =
List.fold_left2 ~init sl fnames ~f:(fun ac el fname ->
let p = U.mk_pat el.field_name in
let f = U.mk_ident fname in
[%expr
let [%p p] = Ctypes.getf ppxc__param [%e f] in
[%e ac]])
in
let read = [%expr fun ppxc__param -> [%e expr]] in
[%expr Ctypes.view ~read:[%e read] ~write:[%e write] [%e struct_expr]]
in
let t = [%type: [%t U.mk_typc orig_name] Ctypes.typ] in
add_ctyp ~constr:t ~retype:false alias_name view
|> U.named_stri ~constr:t orig_name
|> Hashtbl.add htl_tdl_entries tdl_entry_id
in
let single_typ = function
| Enum
{
ename;
el;
ename_c;
etypedef;
edecl;
enum_type;
eunexpected;
eunexpected_bits;
} ->
U.with_loc edecl.ptype_loc @@ fun () ->
let orig_name_bitmask = bitmask_name ename in
let alias_name_bitmask = private_pref orig_name_bitmask in
let orig_name = ename in
let alias_name = private_pref orig_name in
add_type_h ~tdl:tdl_entry_id edecl ename;
let exp_l, enum_l =
let init = ([%expr []], []) in
ListLabels.fold_right el ~init ~f:(fun cur (l1, l2) ->
let loc = cur.cdecl.pcd_loc in
U.with_loc loc @@ fun () ->
let c =
{
Marshal_types.ee_int_id = (Id.get ~loc ()).Id.id;
ee_type_check = (Id.get ~loc ()).Id.id;
ee_loc = loc;
ee_cname = cur.enum_cname;
ee_expr = Exp.construct (U.mk_lid cur.cdecl.pcd_name.txt) None;
}
in
([%expr [%e c.ee_expr] :: [%e l1]], c :: l2))
in
let id, id_bitmask, enum_type_id =
match enum_type with
| Enum_normal ->
let id = Id.get () in
(Some id, None, Marshal_types.E_normal id.Id.id)
| Enum_bitmask ->
let id = Id.get () in
(None, Some id, Marshal_types.E_bitmask id.Id.id)
| Enum_both ->
let id1 = Id.get () in
let id2 = Id.get () in
( Some id1,
Some id2,
Marshal_types.E_normal_bitmask (id1.Id.id, id2.Id.id) )
in
let sparam =
let wrap e =
match e with None -> [%expr None] | Some e -> [%expr Some [%e e]]
in
let enum_unexpected = wrap eunexpected in
let enum_unexpected_bits = wrap eunexpected_bits in
let open Marshal_types in
U.marshal_to_str_expr
{
enum_l;
enum_is_typedef = etypedef;
enum_type_id;
enum_unexpected;
enum_unexpected_bits;
enum_is_int_bitmask = c_bitmask;
enum_loc = edecl.ptype_name.loc;
enum_name = ename_c;
}
in
let pat =
let p1 =
match enum_type with
| Enum_normal | Enum_both -> U.mk_pat alias_name
| Enum_bitmask -> Pat.any ()
in
let p2 =
match enum_type with
| Enum_normal -> Pat.any ()
| Enum_bitmask -> U.mk_pat alias_name
| Enum_both -> U.mk_pat alias_name_bitmask
in
[%pat? [%p p1], [%p p2]]
in
Topscript.add_extract
[%stri
let ([%p pat] : 'a Ctypes.typ * 'a list Ctypes.typ) =
Ppxc__script.Extract.enum [%e exp_l] [%e sparam]];
let id_expr, attrs = Id.get_usage_id () in
Topscript.add_build_external
[%stri
let [%p pat] =
let (ppxc__1, ppxc__2) : 'a Ctypes.typ * 'a list Ctypes.typ =
Ppxc__script.Build.enum [%e exp_l] [%e sparam]
in
( Ppxc__script.Build.reg_trace [%e id_expr] ppxc__1,
Ppxc__script.Build.reg_trace [%e id_expr] ppxc__2 )];
let f ~is_list ?(bitmask_name = false) name = function
| None -> ()
| Some id ->
let constr = U.mk_typc orig_name in
let constr =
match is_list with
| false ->
constr (* FIXME: how to access list and avoid shadowing? *)
| true -> [%type: [%t constr] list]
in
let constr = [%type: [%t constr] Ctypes.typ] in
let s2 =
Impl_mod.add_named ~constr ~retype:false ~attrs name id.Id.expr
in
let name =
match bitmask_name with
| false -> orig_name
| true -> orig_name_bitmask
in
let s = U.named_stri ~constr name s2 in
Hashtbl.add htl_tdl_entries tdl_entry_id s
in
(match enum_type with
| Enum_normal -> f ~is_list:false alias_name id
| Enum_bitmask -> f ~is_list:true alias_name id_bitmask
| Enum_both ->
f ~is_list:false alias_name id;
f ~is_list:true ~bitmask_name:true alias_name_bitmask id_bitmask);
None
| Struct ({ sname; sl = _; sname_c; stypedef; stype; sloc } as swhole) ->
U.with_loc sloc @@ fun () ->
let orig_name = sname in
let alias_name = private_pref orig_name in
let type_name =
match stype with
| Union | Struct_normal | Struct_both -> orig_name
| Struct_record -> Myconst.private_prefix ^ orig_name
in
let xtype = if stypedef then `Typedef sname_c else `Named sname_c in
union_struct ~tdl_entry_id ~alias_name ~type_name ~stype xtype orig_name;
Some swhole
in
let tl = Extract.type_decl type_rec_flag tl in
if
enforce_union
&& List.for_all tl ~f:(function Enum _ -> true | Struct _ -> false)
then error "enum entry marked as union";
if
c_bitmask
&& List.for_all tl ~f:(function Enum _ -> false | Struct _ -> true)
then error "struct entry marked as bitmask";
let names =
List.fold_left ~init:[] tl ~f:(fun ac -> function
| Struct { sname = s; sl; _ } ->
check_reserved_type s;
List.fold_left ~init:(s :: ac) sl ~f:(fun ac el ->
el.field_name :: ac)
| Enum { ename = s; _ } ->
check_reserved_type s;
s :: ac)
in
let names' = CCList.uniq ~eq:CCString.equal names in
if List.length names <> List.length names' then
error "names of enumarations, structures and fields must be unique";
let tl =
List.map tl ~f:(function
| Struct s when enforce_union ->
let stype =
match s.stype with
| Struct_normal | Union -> Union
| Struct_both ->
error "@@@@with_record and type%%c_union are mutually exclusive"
| Struct_record ->
error "@@@@as_record and type%%c_union are mutually exclusive"
in
Struct { s with stype }
| Enum e ->
let res =
match e.enum_type with
| _ when c_bitmask = false -> e
| Enum_both ->
error
"@@@@with_bitmask and type%%c_bitmask f = ... are incompatible"
| Enum_normal ->
if e.etypedef then
error "@@@@typedef and type%%c_bitmask f = ... are incompatible";
{ e with enum_type = Enum_bitmask; etypedef = true }
| Enum_bitmask ->
error "@@@@as_bitmask and type%%c_bitmask f = ... are redundant"
in
(match (res.enum_type, res.eunexpected) with
| Enum_bitmask, Some _ ->
error "@@@@unexpected not supported for bitmasks"
| (Enum_both | Enum_normal | Enum_bitmask), (Some _ | None) -> ());
(match (res.enum_type, res.eunexpected_bits) with
| Enum_normal, Some _ ->
error "@@@@unexpected_bits not supported for enums"
| (Enum_both | Enum_normal | Enum_bitmask), (Some _ | None) -> ());
Enum res
| Struct _ as x -> x)
in
let cnt_structs, cnt_records =
List.fold_left tl ~init:(0, 0) ~f:(fun ((cns, cnr) as ac) -> function
| Enum _ -> ac
| Struct s ->
let cns = succ cns in
let cnr =
match s.stype with
| Struct_normal | Union -> cnr
| Struct_both | Struct_record -> succ cnr
in
(cns, cnr))
in
if cnt_structs > 1 && cnt_records >= 1 && type_rec_flag = Recursive then
error "mutually recursive records are not supported";
let refs = List.filter_map ~f:single_typ tl in
List.iter ~f:fields refs;
if type_rec_flag <> Recursive then List.iter ~f:unhide tl;
tdl_entry
let pexp_const name expr =
let script = U.named_stri name expr in
Topscript.add_extract script;
Topscript.add_build_external script;
Impl_mod.add_named ~retype:true name expr
let field ?prefix = function
| [ (Nolabel, structure); (Nolabel, str_expr); (Nolabel, type_expr) ] ->
snd (field ?prefix ~structure ~str_expr type_expr)
| l -> error_msg "field" l
let mk_str_type ?attrs ?manifest s =
let t = Type.mk ?attrs ~kind:Ptype_abstract ?manifest (U.mk_loc s) in
Str.type_ Recursive [ t ]
let int_alias ~mod_name alias_typ l =
let loc = !Ast_helper.default_loc in
let id = Id.get () in
let str_expr =
(* optional parameter ?strict *)
let er ?loc () = U.error ?loc "int aliases require a string literal" in
let x =
List.find_map l ~f:(function
| Nolabel, str_expr -> (
match Extract.constant_string str_expr with
| Some _ -> Some str_expr
| None -> er ~loc:str_expr.pexp_loc ())
| (Labelled _ | Optional _), _ -> None)
in
match x with Some s -> s | None -> er ()
in
Topscript.add_extract_phase0
[%stri
let () =
Ppxc__script.Extract_phase0.int_alias [%e id.Id.script_param]
[%e str_expr]];
let func_name, sig_name =
match alias_typ with
| `Int -> ("int_alias", "Signed")
| `Uint -> ("uint_alias", "Unsigned")
| `Aint -> ("aint_alias", "Unkown_signedness")
in
let mod_name_expr = U.str_expr mod_name in
let lmod_name = U.mk_oloc mod_name in
let f e_b =
let e = U.mk_ident_l (e_b @ [ func_name ]) in
let e =
Exp.apply e
[
(Nolabel, id.Id.script_param); (Labelled "mod_name", mod_name_expr);
]
in
let e = Mod.unpack (Exp.apply e l) in
let e = Mb.mk lmod_name e in
Str.module_ e
in
Topscript.add_extract @@ f [ "Ppxc__script"; "Extract" ];
Topscript.add_build_external @@ f [ "Ppxc__script"; "Build" ];
Impl_mod.add_entry id.Id.stri;
let lid = Impl_mod.create_ref_lid mod_name in
let t = Typ.constr (U.mk_loc (Ldot (lid.txt, "t"))) [] in
let tstri = [%stri type t = [%t t]] in
let x = Str.module_ (Mb.mk lmod_name (Mod.structure [ tstri ])) in
Type_mod.add_entry x;
let mod_ident = Mod.ident lid in
let attrs = [ Attributes.manifest_replace_attrib ] in
let t = Type.mk ~attrs ~kind:Ptype_abstract ~manifest:t (U.mk_loc "t") in
let t = [ Pwith_type (U.mk_lid "t", t) ] in
let s = Mty.ident (U.mk_lid_l [ "Ppx_cstubs"; "Types"; sig_name ]) in
let t = Mod.constraint_ mod_ident (Mty.with_ s t) in
let stri = Str.module_ (Mb.mk lmod_name t) in
let tdl_entry_id, tdl_entry = Id.get_tdl_entries_id () in
Hashtbl.add htl_tdl_entries tdl_entry_id stri;
(match OSTypes.add_abstract ~sub_module:mod_name "t" with
| None -> ()
| Some b -> Hashtbl.add htl_tdl_entries tdl_entry_id b);
tdl_entry
let opaque binding_name vb_attrs l =
let loc = !Ast_helper.default_loc in
check_reserved_type binding_name;
let id_size = Id.get () in
let id_align = Id.get () in
let id_type = Id.get () in
let usage_id_expr, attrs = Id.get_usage_id () in
let uniq_ref, main_ref =
Impl_mod.add_opaq attrs id_size.Id.stri binding_name
in
let marshal_info =
let open Marshal_types in
let s = { o_binding_name = binding_name; o_uniq_ref_id = uniq_ref } in
U.marshal_to_str_expr s
in
let mod_unique = U.safe_mlname ~capitalize:true ~prefix:binding_name () in
let f f =
let e =
[%expr
[%e f] ~size:[%e id_size.Id.script_param]
~align:[%e id_align.Id.script_param]
~typ:[%e id_type.Id.script_param] ~mi:[%e marshal_info]]
in
let e = Mod.unpack (Exp.apply e l) in
let e = Mb.mk (U.mk_oloc mod_unique) e in
Str.module_ e
in
Topscript.add_extract @@ f [%expr Ppxc__script.Extract.opaque];
Topscript.add_build_external @@ f [%expr Ppxc__script.Build.opaque];
let manifest = U.mk_typc_l [ mod_unique; "t" ] in
let stri = mk_str_type ~manifest binding_name in
Topscript.add_extract stri;
Topscript.add_build_external stri;
let expr = U.mk_ident_l [ mod_unique; "t" ] in
let constr = [%type: [%t U.mk_typc binding_name] Ctypes.typ] in
let pat = U.mk_pat_pconstr constr binding_name in
Topscript.add_extract [%stri let [%p pat] = [%e expr]];
Topscript.add_build_external
[%stri
let [%p pat] = Ppxc__script.Build.reg_trace [%e usage_id_expr] [%e expr]];
let manifest = Impl_mod.create_type_ref binding_name in
Type_mod.add_entry (mk_str_type ~manifest binding_name);
let attrs = [ Attributes.manifest_replace_attrib ] in
let stri = mk_str_type ~attrs ~manifest binding_name in
let tdl_entry_id, tdl_entry = Id.get_tdl_entries_id () in
Hashtbl.add htl_tdl_entries tdl_entry_id stri;
(match OSTypes.add_abstract binding_name with
| None -> ()
| Some b -> Hashtbl.add htl_tdl_entries tdl_entry_id b);
Str.value Nonrecursive [ Vb.mk ~attrs:vb_attrs pat main_ref ]
|> Hashtbl.add htl_tdl_entries tdl_entry_id;
tdl_entry
let abstract binding_name vb_attrs l =
let loc = !Ast_helper.default_loc in
let str_expr =
match l with [ (Nolabel, x) ] -> x | _ -> error_msg "abstract" l
in
check_reserved_type binding_name;
let id_size = Id.get () in
let id_align = Id.get () in
let tdl_entry_id, tdl_entry = Id.get_tdl_entries_id () in
let usage_id_expr, attrs = Id.get_usage_id () in
add_stri_to_all (mk_str_type binding_name);
let expr =
[%expr
let s : string = [%e str_expr] in
Ppxc__script.Extract.abstract ~size:[%e id_size.Id.script_param]
~align:[%e id_align.Id.script_param] s]
in
let t = U.mk_typc_l [ binding_name ] in
let constr = [%type: [%t t] Ctypes.abstract Ctypes.typ] in
let pat = U.mk_pat_pconstr constr binding_name in
Topscript.add_extract [%stri let [%p pat] = [%e expr]];
let expr =
[%expr
Ppxc__script.Build.abstract ~size:[%e id_size.Id.script_param]
~align:[%e id_align.Id.script_param] [%e str_expr]
|> Ppxc__script.Build.reg_trace [%e usage_id_expr]]
in
Topscript.add_build_external [%stri let [%p pat] = [%e expr]];
let expr =
[%expr
Ctypes_static.Abstract
{
Ctypes_static.aname = [%e str_expr];
Ctypes_static.asize = [%e id_size.Id.expr];
Ctypes_static.aalignment = [%e id_align.Id.expr];
}]
in
let manifest = Impl_mod.create_type_ref binding_name in
Type_mod.add_entry (mk_str_type ~manifest binding_name);
let at2 = [ Attributes.manifest_replace_attrib ] in
let stri = mk_str_type ~attrs:at2 ~manifest binding_name in
Hashtbl.add htl_tdl_entries tdl_entry_id stri;
(match OSTypes.add_abstract binding_name with
| None -> ()
| Some b -> Hashtbl.add htl_tdl_entries tdl_entry_id b);
let main_ref =
Impl_mod.add_named ~constr ~retype:false ~attrs binding_name expr
in
Str.value Nonrecursive [ Vb.mk ~attrs:vb_attrs pat main_ref ]
|> Hashtbl.add htl_tdl_entries tdl_entry_id;
tdl_entry
let ocaml_funptr ~acquire_runtime ~thread_registration cb_bname cb_user_fun
typ =
let loc = !Ast_helper.default_loc in
let id_bottom = Id.get () in
register_fun id_bottom;
let cb_top_mod = U.safe_mlname ~capitalize:true ~prefix:cb_bname () in
let rec' =
{
Marshal_types.cb_mod_path = Impl_mod.get_mod_path ();
cb_binding_name = cb_bname;
cb_bottom = id_bottom.Id.id;
cb_top_mod;
cb_user_fun;
cb_acquire_runtime = acquire_runtime;
cb_thread_registration = thread_registration;
cb_init_fun = U.safe_cname ~prefix:cb_bname;
}
in
let rec' = U.marshal_to_str_expr rec' in
let cb_typ =
match typ.ptyp_desc with
| Ptyp_constr (x, []) -> x
| _ -> U.error "invalid type specification for callback"
in
let e = Exp.ident cb_typ in
let f f =
[%stri
let () =
let (__ppxc__safe : _ Ctypes.static_funptr Ctypes.typ) = [%e e] in
[%e f] [%e rec'] __ppxc__safe]
in
Topscript.add_extract @@ f [%expr Ppxc__script.Extract.ocaml_funptr];
Topscript.add_build_external @@ f [%expr Ppxc__script.Build.ocaml_funptr];
let m =
let er () =
U.error ~loc:cb_typ.loc
"please reference the original module for the callback type"
in
match Longident.flatten_exn cb_typ.txt |> List.rev with
| [] | [ _ ] -> er ()
| x :: tl ->
if x <> "t" then er ();
List.rev tl
in
let ident = Mod.ident (U.mk_lid_l m) in
let mb = Mb.mk (U.mk_oloc cb_top_mod) ident in
Impl_mod.add_entry (Str.module_ mb);
id_bottom.Id.stri
let type_cb lmod_name_opt mod_name l =
let loc = !Ast_helper.default_loc in
let () =
let a =
Exp.apply [%expr Ppx_cstubs.Ppx_cstubs_internals.Callback.make] l
in
let m =
U.mk_lid_l [ "Ppx_cstubs"; "Ppx_cstubs_internals"; "Callback"; "Make" ]
in
let s = Mod.apply (Mod.ident m) (Mod.unpack a) in
add_stri_to_all (Str.module_ (Mb.mk lmod_name_opt s))
in
let id_expr, attrs = Id.get_usage_id () in
Topscript.add_build_external
[%stri
let (_ : _ Ctypes.static_funptr Ctypes.typ) =
Ppxc__script.Build.reg_trace ~no_dup:true [%e id_expr]
[%e U.mk_ident_l [ mod_name; "t" ]]];
let mp = Impl_mod.get_mod_path () @ [ mod_name ] in
let ident = Mod.ident (U.mk_lid_l mp) in
let ident =
if Ocaml_config.use_open_struct () = false then ident
else
let fname s = mp @ [ s ] in
let t1 = U.mk_typc_l (fname "raw_pointer") in
let t1 = [%stri type raw_pointer = [%t t1]] in
let t2 = U.mk_typc_l ~l:[ Typ.var "a" ] (fname "t") in
let t2 = [%stri type 'a t = [%t t2]] in
let tm = Mb.mk lmod_name_opt (Mod.structure [ t1; t2 ]) in
Type_mod.add_entry (Str.module_ tm);
let o = U.alias_impl_mod_os () in
let s = Str.include_ (Incl.mk ident) in
let m = Mty.typeof_ (Mod.structure [ o; s ]) in
let f s invar =
let l, params =
if invar = false then ([], None)
else
let a' = Typ.var "a" in
([ a' ], Some [ (a', (NoVariance, NoInjectivity)) ])
in
let manifest = U.mk_typc_l ~l (fname s) in
let attrs = [ Attributes.manifest_replace_attrib ] in
let tdl = Type.mk ~attrs ?params ~manifest (U.mk_loc s) in
Pwith_type (U.mk_lid s, tdl)
in
let l = [ f "t" true; f "raw_pointer" false ] in
Mod.constraint_ ident (Mty.with_ m l)
in
let mb = Mb.mk ~attrs lmod_name_opt ident in
let stri = Str.module_ mb in
let tdl_entry_id, tdl_entry = Id.get_tdl_entries_id () in
Hashtbl.add htl_tdl_entries tdl_entry_id stri;
(match OSTypes.add_types_cb mod_name with
| None -> ()
| Some x -> Hashtbl.add htl_tdl_entries tdl_entry_id x);
tdl_entry
let typ name e =
let loc = !Ast_helper.default_loc in
let n = U.safe_mlname ~prefix:name () in
let t = [%type: _ Ctypes.typ] in
let pat = U.mk_pat_pconstr t n in
Topscript.add_build_external [%stri let [%p pat] = [%e e]];
let ne = U.mk_ident_l [ n ] in
let build_expr = [%expr Ppxc__script.Build.trace_custom [%e ne]] in
add_ctyp ~constr:t ~retype:true ~build_expr name e
let union_struct s stype ocaml_name = function
| [ (Nolabel, e) ] ->
let tdl_entry_id, tdl_entry = Id.get_tdl_entries_id () in
union_struct ~tdl_entry_id ~type_name:ocaml_name ~stype (`From_expr e)
ocaml_name;
tdl_entry
| l -> error_msg s l
let union s l = union_struct "union" Extract.Union s l
let structure s l = union_struct "structure" Extract.Struct_normal s l
end
let own_extensions = [ "c"; "c_union"; "c_bitmask"; "cb" ]
module Scan () : sig
val structure : structure -> structure
end = struct
module Open_decl : sig
val new' :
open_declaration -> (unit -> open_declaration) -> open_declaration
val check : unit -> unit
val check_s : string -> unit
end = struct
let depth = ref 0
let new' s f =
let rec g s =
match s.pmod_desc with
| Pmod_ident _ | Pmod_structure _ -> true
| Pmod_functor _ | Pmod_apply _ | Pmod_unpack _ | Pmod_extension _ ->
false
| Pmod_constraint (s, _) -> g s
in
if g s.popen_expr then f ()
else (
incr depth;
Std.finally ~h:(fun () -> decr depth) f)
let check () =
if !depth <> 0 then
U.error
"Defining types inside non trivial 'open expr' blocks is not possible"
let check_s s =
if !depth <> 0 then U.error "%s is not possible in this context" s
end
module Include_str : sig
(* no type definition inside restricted include blocks.
Prevent something like this:
type t
include (struct type t end : sig (* no type t *) end)
*)
val cond_disable : bool -> (unit -> 'a) -> 'a
val check : unit -> unit
val new' : module_expr -> (unit -> 'a) -> 'a
end = struct
let inside_restricted_struct = ref false
let states = Stack.create ()
let set_tmp new_state f =
Stack.push !inside_restricted_struct states;
inside_restricted_struct := new_state;
Std.finally
~h:(fun () ->
let s = Stack.pop states in
inside_restricted_struct := s)
f
let cond_disable s f = if s = false then f () else set_tmp false f
let check () =
if !inside_restricted_struct then
error
"Defininig types inside constrained 'include struct' blocks is not supported"
let new' p f =
let is_restricted =
match p.pmod_desc with
| Pmod_ident _ | Pmod_structure _ -> false
(* just forbid types in all unusual positions for the moment *)
| Pmod_functor _ | Pmod_apply _ | Pmod_unpack _ | Pmod_extension _
| Pmod_constraint _ ->
true
in
if is_restricted = false then f () else set_tmp true f
end
module Static_level : sig
(*
ocaml_funptr must be declared "static", eg. not inside functors, etc. *)
val disable : (unit -> 'a) -> 'a
val inside_closure : unit -> bool
end = struct
let depth = ref 0
let disable f =
incr depth;
Std.finally ~h:(fun () -> decr depth) f
let inside_closure () = !depth <> 0
end
module Save_position : sig
(* forbid certain constructs inside, eg. type of `struct ... end`*)
val disable : (unit -> 'a) -> 'a
val check : string -> unit
end = struct
let depth = ref 0
let disable f =
incr depth;
Std.finally ~h:(fun () -> decr depth) f
let check s =
if !depth > 0 then U.error "%s is not possible in this context" s
end
let mark_empty a =
if a.pvb_attributes <> [] || a.pvb_pat.ppat_attributes <> [] then a
else
match a.pvb_pat.ppat_desc with
| Ppat_construct ({ txt = Lident "()"; _ }, None) -> (
match a.pvb_expr with
| {
pexp_desc = Pexp_construct ({ txt = Lident "()"; _ }, None);
pexp_attributes = [];
_;
} ->
{ a with pvb_attributes = [ Attributes.remove_attrib ] }
| _ -> a)
| _ -> a
let rec unbox_box_constr e f =
match e.pexp_desc with
| Pexp_constraint (e2, c) ->
let res = unbox_box_constr e2 f in
{ e with pexp_desc = Pexp_constraint (res, c) }
| _ -> U.with_loc e.pexp_loc @@ fun () -> f e
let check_save_type_pos () =
Include_str.check ();
Open_decl.check ()
let check_save_pos s =
Save_position.check s;
Open_decl.check_s s
let name_needed () =
error "new types need a name, parallel pattern matching is not supported"
let stri_and_open = function
| [] -> U.empty_stri ()
| [ hd ] -> hd
| l ->
let tdl_entry_id, tdl_entry = Id.get_tdl_entries_id () in
List.iter l ~f:(Hashtbl.add htl_tdl_entries tdl_entry_id);
tdl_entry
let external' ~is_inline loc strpri =
Ast_helper.default_loc := loc;
let release_runtime_lock = ref false in
let noalloc = ref false in
let return_errno = ref false in
let remove_labels = ref false in
let attrs = ref [] in
List.iter strpri.pval_attributes ~f:(fun x ->
let reuse_attrib =
match x.attr_name.txt with
(* TODO: what else? *)
| "release_runtime_lock" ->
release_runtime_lock := true;
false
| "noalloc" ->
noalloc := true;
false
| "return_errno" ->
return_errno := true;
false
| "remove_labels" when is_inline ->
remove_labels := true;
false
| "ocaml.warnerror" | "ocaml.deprecated" | "ocaml.warning"
| "warnerror" | "deprecated" | "warning" ->
attrs := x :: !attrs;
true
| y -> error ~loc:x.attr_loc "unsupported attribute %s" y
in
if reuse_attrib = false && x.attr_payload <> PStr [] then
error ~loc:x.attr_loc "unknown content in attribute %s"
x.attr_name.txt);
let attrs = List.rev !attrs in
let release_runtime_lock = !release_runtime_lock in
let noalloc = !noalloc in
let return_errno = !return_errno in
let remove_labels = !remove_labels in
H.external' ~is_inline ~remove_labels ~return_errno ~attrs
~release_runtime_lock ~noalloc strpri
let obj =
object (self)
inherit Ast_traverse.map as super
method! structure_item stri =
let pstr_loc = stri.pstr_loc in
Ast_helper.default_loc := pstr_loc;
match stri.pstr_desc with
| Pstr_extension
( ( { txt = "c"; _ },
PStr [ { pstr_desc = Pstr_primitive strpri; pstr_loc; _ } ] ),
_ )
when strpri.pval_prim <> [] ->
check_save_pos "external";
OSTypes.types_maybe_used ();
external' ~is_inline:true pstr_loc strpri
| Pstr_primitive strpri when strpri.pval_prim <> [] ->
check_save_pos "external";
OSTypes.types_maybe_used ();
external' ~is_inline:false pstr_loc strpri
| Pstr_extension
( ( { txt = ("c" | "c_union" | "c_bitmask") as txt; _ },
PStr [ { pstr_desc = Pstr_type (rf, tl); pstr_loc } ] ),
_ ) ->
check_save_type_pos ();
check_save_pos txt;
Ast_helper.default_loc := pstr_loc;
let enforce_union = txt = "c_union" in
let c_bitmask = txt = "c_bitmask" in
H.type_decl ~enforce_union ~c_bitmask rf tl
| Pstr_extension
( ( { txt = "cb"; _ },
PStr [ { pstr_desc = Pstr_value (Nonrecursive, [ p ]); _ } ] ),
_ ) ->
OSTypes.types_maybe_used ();
let pat = p.pvb_pat in
let exp = p.pvb_expr in
let thread_registration = ref false in
let acquire_runtime = ref false in
List.iter p.pvb_attributes ~f:(fun x ->
(match x.attr_name.txt with
| "acquire_runtime_lock" -> acquire_runtime := true
| "thread_registration" -> thread_registration := true
| y -> error ~loc:x.attr_loc "unsupported attribute %s" y);
if x.attr_payload <> PStr [] then
error ~loc:x.attr_loc "unknown content in attribute %s"
x.attr_name.txt);
let typ_pat =
match pat.ppat_desc with
| Ppat_constraint (_, t) -> Some t
| _ -> None
in
let exp, typ_expr =
match exp.pexp_desc with
| Pexp_constraint (e, t) -> (e, Some t)
| Pexp_fun _ -> (
let rec iter e =
match e.pexp_desc with
| Pexp_constraint (e, t) -> Some (e, t)
| Pexp_fun (a, b, c, e') -> (
match iter e' with
| Some (e'', t) ->
let pexp_desc = Pexp_fun (a, b, c, e'') in
Some ({ e with pexp_desc }, t)
| None -> None)
| _ -> None
in
match iter exp with
| None -> (exp, None)
| Some (e, t) -> (e, Some t))
| _ -> (exp, None)
in
let typ =
match (typ_pat, typ_expr) with
| None, None -> U.error "callbacks require Ctypes.typ specification"
| Some t, None | None, Some t -> t
| Some t1, Some t2 -> (
if t1 = t2 then t1
else
match t1.ptyp_desc with
| Ptyp_poly ([], t1') when t1' = t2 ->
(* simple equality works surprisingly, probably a very fragile
test *)
t2
| _ -> U.error "conflicting type definitions for callback")
in
let name =
match Extract.variable_from_pattern_constr pat with
| None, _ -> name_needed ()
| Some x, _ -> x
in
if Static_level.inside_closure () then
U.error "static ocaml callbacks must be declared at the top level";
let thread_registration = !thread_registration in
let acquire_runtime = !acquire_runtime in
H.ocaml_funptr ~acquire_runtime ~thread_registration name exp typ
| Pstr_extension
( ( { txt = "c"; _ },
PStr
[
{
pstr_desc =
Pstr_value
( Nonrecursive,
[
{
pvb_pat = pat;
pvb_expr = exp;
pvb_attributes;
_;
};
] );
_;
};
] ),
_ ) ->
(*| [%stri let%c [%p? pat] = [%e? exp]]*)
Std.with_return @@ fun ret ->
let t =
let orig_exp = exp in
unbox_box_constr exp @@ fun exp ->
let s, l, is_constant =
match exp.pexp_desc with
| Pexp_apply
( {
pexp_desc = Pexp_ident { txt = Lident s; loc = _ };
pexp_attributes = [];
_;
},
l ) ->
(s, l, false)
| Pexp_constant _ -> ("", [], true)
| _ -> ("", [], false)
in
(* TODO: really allow everything as long as a Ctypes.typ is returned? *)
let name, constr =
match Extract.variable_from_pattern_constr pat with
| None, x when s = "header" -> ("", x)
| None, _ -> name_needed ()
| Some x, y -> (x, y)
in
let nc () =
U.error ~loc:orig_exp.pexp_loc "constraint not supported here"
in
check_save_pos s;
if s <> "header" then OSTypes.types_maybe_used ();
match s with
| "header" ->
if orig_exp <> exp then nc ();
H.header l
| "opaque" | "abstract" ->
check_save_type_pos ();
if orig_exp <> exp || constr then nc ();
let at = pvb_attributes in
if s = "opaque" then ret.return (H.opaque name at l)
else ret.return (H.abstract name at l)
| "union" ->
check_save_type_pos ();
ret.return (H.union name l)
| "structure" ->
check_save_type_pos ();
ret.return (H.structure name l)
| "@->" -> H.fn name exp
| "constant" -> H.bound_constant name l
| _ when is_constant -> H.pexp_const name exp
| _ -> H.typ name exp
in
let vb = Ast_helper.Vb.mk ~attrs:pvb_attributes pat t |> mark_empty in
Ast_helper.Str.value Nonrecursive [ vb ]
| Pstr_module
{
pmb_name = lname;
pmb_expr =
{
pmod_desc =
Pmod_extension
( { txt = ("cb" | "c") as txt; _ },
PStr [ { pstr_desc = Pstr_eval (exp, _); _ } ] );
_;
};
_;
} -> (
check_save_type_pos ();
let mod_name =
match lname.txt with
| None -> ""
| Some txt ->
if Hashtbl.mem Keywords.htl_modules txt then
U.error "module name %S is reserved" txt;
txt
in
if txt = "cb" then (
if Static_level.inside_closure () then
U.error "static ocaml callbacks must be declared at the top level";
check_save_pos "ocaml callback";
if mod_name = "" then
U.error "module for ocaml callback must have a name";
H.type_cb lname mod_name [ (Nolabel, exp) ])
else
let s, l, loc =
match exp.pexp_desc with
| Pexp_apply
( {
pexp_desc = Pexp_ident { txt = Lident s; loc = lo };
pexp_attributes = [];
_;
},
l ) ->
(s, l, lo)
| _ ->
U.error ~loc:exp.pexp_loc
"don't know what do do with this expression."
in
check_save_pos s;
let f x =
if mod_name = "" then
U.error "module for int_alias must have a name";
H.int_alias ~mod_name x l
in
match s with
| "int" -> f `Int
| "uint" -> f `Uint
| "aint" -> f `Aint
| _ -> U.error ~loc "unsupported function %S" s)
| Pstr_extension (({ txt; loc }, _), _)
when List.mem ~eq:CCString.equal txt own_extensions ->
error ~loc "extension '%s' is not supported here" txt
| Pstr_value
( Nonrecursive,
[
({
pvb_expr =
{
pexp_desc =
Pexp_extension
( { txt = "c"; _ },
PStr [ { pstr_desc = Pstr_eval (e, []); _ } ] );
_;
};
_;
} as a);
] ) ->
let t =
unbox_box_constr e @@ fun e ->
let prefix = Extract.variable_from_pattern a.pvb_pat in
let s, l =
match e.pexp_desc with
| Pexp_apply
( {
pexp_desc = Pexp_ident { txt = Lident s; loc = _ };
pexp_attributes = [];
_;
},
l ) ->
(s, l)
| Pexp_apply _ -> ("", [])
| _ ->
error "only function application is allowed in this context"
in
let res =
match s with
| "header" -> H.header l
| "field" -> H.field ?prefix l
| "constant" -> H.constant l
| "seal" -> H.seal l
| "foreign_value" -> H.foreign_value l
| "foreign" -> H.foreign ?prefix l
| _ -> error "invalid function call in [%%c ... ]"
in
if s <> "header" then OSTypes.types_maybe_used ();
check_save_pos s;
res
in
let na = mark_empty { a with pvb_expr = t } in
{ stri with pstr_desc = Pstr_value (Nonrecursive, [ na ]) }
| Pstr_module x ->
Include_str.cond_disable (x.pmb_name.txt = None) @@ fun () ->
let f () = super#structure_item stri in
Ptree.Modules.pstr_module x f |> stri_and_open
| Pstr_recmodule l ->
let f x =
Include_str.cond_disable (x.pmb_name.txt = None) @@ fun () ->
self#module_binding x
in
let l' = Ptree.Modules.pstr_recmodule l f in
{ pstr_desc = Pstr_recmodule l'; pstr_loc }
| Pstr_include i ->
Include_str.new' i.pincl_mod @@ fun () ->
let f () = super#structure_item stri in
Ptree.Modules.pstr_include i f |> stri_and_open
| Pstr_open odl ->
Ptree.Modules.pstr_open odl (fun () -> super#structure_item stri)
|> stri_and_open
| _ -> super#structure_item stri
method! expression pexp =
Ast_helper.default_loc := pexp.pexp_loc;
match pexp.pexp_desc with
| Pexp_extension
({ txt = "c"; _ }, PStr [ { pstr_desc = Pstr_eval (e, []); _ } ]) ->
OSTypes.types_maybe_used ();
unbox_box_constr e @@ fun e ->
let s, l =
match e.pexp_desc with
| Pexp_apply
( {
pexp_desc = Pexp_ident { txt = Lident s; loc = _ };
pexp_attributes = [];
_;
},
l ) ->
(s, l)
| Pexp_apply _ -> ("", [])
| _ -> error "only function application is allowed in this context"
in
let r =
match s with
| "constant" -> H.constant l
| "foreign_value" -> H.foreign_value l
| "foreign" -> H.foreign l
| _ -> error "invalid function call in [%%c ... ]"
in
check_save_pos s;
r
| Pexp_extension ({ txt; loc }, _)
when List.mem ~eq:CCString.equal txt own_extensions ->
error ~loc "extension '%s' is not allowed here" txt
| Pexp_letmodule (name, mexpr, e) ->
Include_str.cond_disable true @@ fun () ->
Static_level.disable @@ fun () ->
let fmexpr () = self#module_expr mexpr
and fexpr () = self#expression e in
let m, e = Ptree.Modules.pexp_letmodule name ~mexpr ~fmexpr ~fexpr in
{ pexp with pexp_desc = Pexp_letmodule (name, m, e) }
| Pexp_pack m ->
Include_str.cond_disable true @@ fun () ->
Static_level.disable @@ fun () ->
Ptree.Modules.pexp_pack m @@ fun () -> super#expression pexp
| Pexp_open (odl, e) ->
let fodl () = self#open_declaration odl in
let fexpr () = self#expression e in
let odl, e = Ptree.Modules.pexp_open odl ~fodl ~fexpr in
{ pexp with pexp_desc = Pexp_open (odl, e) }
| _ -> super#expression pexp
method! module_expr m =
Ast_helper.default_loc := m.pmod_loc;
match m.pmod_desc with
| Pmod_ident _ | Pmod_structure _ | Pmod_constraint _ ->
super#module_expr m
| Pmod_apply _ | Pmod_unpack _ | Pmod_functor _ ->
Static_level.disable @@ fun () -> super#module_expr m
| Pmod_extension ({ txt; loc }, _)
when List.mem ~eq:CCString.equal txt own_extensions ->
error ~loc "extension '%s' is not allowed here" txt
| Pmod_extension _ ->
Static_level.disable @@ fun () ->
Save_position.disable @@ fun () -> super#module_expr m
method! module_type m =
Ast_helper.default_loc := m.pmty_loc;
match m.pmty_desc with
| Pmty_typeof _ ->
Static_level.disable @@ fun () ->
Save_position.disable @@ fun () -> super#module_type m
| Pmty_ident _ | Pmty_signature _ | Pmty_functor _ | Pmty_with _
| Pmty_extension _ | Pmty_alias _ ->
super#module_type m
method! payload p =
Static_level.disable @@ fun () ->
Save_position.disable @@ fun () -> super#payload p
method! open_declaration p =
Ast_helper.default_loc := p.popen_loc;
Open_decl.new' p @@ fun () -> super#open_declaration p
end
let structure str = obj#structure str
end
module Replace () : sig
val structure : structure -> structure
end = struct
let remove_attrib attr l = List.filter l ~f:(fun x -> x.attr_name.txt <> attr)
let get_usage_id_from_attribs_exn attr =
let pl =
let s =
List.find attr ~f:(fun x ->
x.attr_name.txt = Attributes.replace_attr_string)
in
s.attr_payload
in
let attr =
List.filter attr ~f:(fun x ->
x.attr_name.txt <> Attributes.replace_attr_string)
in
let id =
match pl with
| PStr
[
{
pstr_desc =
Pstr_eval
( { pexp_desc = Pexp_constant (Pconst_integer (x, None)); _ },
[] );
_;
};
] ->
int_of_string x
| _ -> error "attribute %S is reserved" Attributes.replace_attr_string
in
(attr, id)
let mark_if_used ?pexp_outer map stri pvb pexp =
let pexp_attributes, id =
get_usage_id_from_attribs_exn pexp.pexp_attributes
in
let pexp' = { pexp with pexp_attributes } in
let pexp' =
match pexp_outer with
| None -> pexp'
| Some (pexp_outer, ct) ->
{ pexp_outer with pexp_desc = Pexp_constraint (pexp', ct) }
in
let used = Hashtbl.mem Script_result.htl_used id in
let nattrib =
if (not used) || Ocaml_config.version () < (4, 6, 0) then
pvb.pvb_attributes
else U.ocaml_warning "-32" :: pvb.pvb_attributes
in
let pvb' = { pvb with pvb_expr = pexp'; pvb_attributes = nattrib } in
let stri' = { stri with pstr_desc = Pstr_value (Nonrecursive, [ pvb' ]) } in
map (if used then U.no_warn_unused_pre406 stri' else stri')
let add_tdl_entries str =
List.fold_left ~init:[] str ~f:(fun ac -> function
| {
pstr_desc =
Pstr_eval
( { pexp_desc = Pexp_constant (Pconst_integer (s, None)); _ },
(_ :: _ as l) );
pstr_loc;
_;
}
when List.exists l ~f:(fun x -> x.attr_name.txt = Attributes.tdl_string)
-> (
match Hashtbl.find_all htl_tdl_entries @@ int_of_string s with
| exception Failure _ ->
error ~loc:pstr_loc "fatal: type info not found"
| x -> x @ ac)
| x -> x :: ac)
|> List.rev
let obj =
object (self)
inherit Ast_traverse.map as super
method! structure str =
let remove_empty accu el =
match el.pstr_desc with
| Pstr_value (Nonrecursive, [ { pvb_attributes = [ x ]; _ } ])
when x.attr_name.txt = Attributes.remove_string ->
accu
| _ -> el :: accu
in
let rec remove_end_open = function
| [] -> []
| hd :: tl as l -> (
match hd.pstr_desc with
| Pstr_open { popen_attributes = _ :: _ as l; _ }
when List.exists l ~f:(fun x ->
let t = x.attr_name.txt in
t = Attributes.open_struct_body_string
|| t = Attributes.open_struct_type_mod_string
|| t = Attributes.open_struct_openmod_string) ->
remove_end_open tl
| _ -> l)
in
add_tdl_entries str
|> super#structure
|> List.fold_left ~f:remove_empty ~init:[]
|> remove_end_open
|> List.rev_map ~f:(function
| {
pstr_desc =
Pstr_open ({ popen_attributes = _ :: _ as l; _ } as d);
_;
} as w ->
let l =
remove_attrib Attributes.open_struct_body_string l
|> remove_attrib Attributes.open_struct_type_mod_string
|> remove_attrib Attributes.open_struct_openmod_string
in
{ w with pstr_desc = Pstr_open { d with popen_attributes = l } }
| s -> s)
method! structure_item stri =
let pstr_loc = stri.pstr_loc in
Ast_helper.default_loc := pstr_loc;
let stri = Uniq_ref.replace_stri stri in
match stri.pstr_desc with
| Pstr_eval
( { pexp_desc = Pexp_constant (Pconst_integer (s, None)); _ },
(_ :: _ as l) )
when List.exists l ~f:(fun x ->
x.attr_name.txt = Attributes.replace_expr_string) -> (
try Hashtbl.find Script_result.htl_stri (int_of_string s)
with Not_found -> error "fatal error: external not found")
| Pstr_value
( Nonrecursive,
[
({ pvb_expr = { pexp_attributes = _ :: _ as l; _ } as pexp; _ }
as pvb);
] )
when List.exists l ~f:(fun x ->
x.attr_name.txt = Attributes.replace_attr_string) ->
mark_if_used super#structure_item stri pvb pexp
| Pstr_value
( Nonrecursive,
[
({
pvb_expr =
{
pexp_desc =
Pexp_constraint
(({ pexp_attributes = _ :: _ as l; _ } as pexp), ct);
_;
} as pexp_outer;
_;
} as pvb);
] )
when List.exists l ~f:(fun x ->
x.attr_name.txt = Attributes.replace_attr_string) ->
mark_if_used ~pexp_outer:(pexp_outer, ct) super#structure_item stri
pvb pexp
| Pstr_module ({ pmb_attributes = _ :: _ as l; _ } as w2)
when List.exists l ~f:(fun x ->
x.attr_name.txt = Attributes.replace_attr_string) ->
let pmb_attributes, id = get_usage_id_from_attribs_exn l in
let pstr_desc = Pstr_module { w2 with pmb_attributes } in
let w1 = { stri with pstr_desc } in
let w = self#structure_item w1 in
(* TODO: modules are now always used because of the __alias redirection.
Is this avoidable somehow? *)
if
false = Hashtbl.mem Script_result.htl_used id
|| Ocaml_config.use_open_struct ()
then w
else U.no_warn_unused_module ~loc:pstr_loc w
| Pstr_open { popen_attributes = _ :: _ as l; _ }
when List.exists l ~f:(fun x ->
x.attr_name.txt = Attributes.open_struct_type_mod_string)
&& OSTypes.delete_os_inside_type_mod () ->
U.empty_stri ()
| _ -> super#structure_item stri
method! expression pexp =
Ast_helper.default_loc := pexp.pexp_loc;
let pexp = Uniq_ref.replace_expr pexp in
let la = pexp.pexp_attributes in
if la = [] then super#expression pexp
else
match pexp.pexp_desc with
| Pexp_constant (Pconst_integer (s, None))
when List.exists la ~f:(fun x ->
x.attr_name.txt = Attributes.replace_expr_string) -> (
try Hashtbl.find Script_result.htl_expr (int_of_string s)
with Not_found -> error "fatal: constant not found")
| Pexp_ifthenelse (_, _, Some e3)
when List.exists la ~f:(fun x ->
x.attr_name.txt = Attributes.open_struct_ifthenelse_string)
->
let a = remove_attrib Attributes.open_struct_ifthenelse_string la in
let e =
if OSTypes.remove_alias_types () then
{ e3 with pexp_attributes = e3.pexp_attributes @ a }
else { pexp with pexp_attributes = a }
in
self#expression e
| _ -> super#expression pexp
method! type_declaration t =
Ast_helper.default_loc := t.ptype_loc;
match t with
| {
ptype_manifest =
Some ({ ptyp_desc = Ptyp_constr ({ txt; loc }, cl); _ } as w2);
ptype_attributes = _ :: _ as l;
_;
} as w
when List.exists l ~f:(fun x ->
x.attr_name.txt = Attributes.manifest_replace_string) ->
let a = remove_attrib Attributes.manifest_replace_string l in
let txt =
if Ptree.type_mod_is_used () = false then txt
else
match Longident.flatten_exn txt with
| [] -> assert false
| _ :: tl -> (
match U.lid_unflatten (!Lconst.type_mod_name :: tl) with
| None -> assert false
| Some l -> l)
in
let w2 = { w2 with ptyp_desc = Ptyp_constr ({ txt; loc }, cl) } in
{ w with ptype_manifest = Some w2; ptype_attributes = a }
| t -> super#type_declaration t
end
let structure str = obj#structure str
end
module Merlin () : sig
val structure : structure -> structure
end = struct
let error loc =
error ~loc
"please run ppx_cstubs preprocessor manually first, ppx_cstubs.merlin is only intended for editor integration"
let obj =
object
inherit Ast_traverse.map as super
method! structure_item s =
match s.pstr_desc with
| Pstr_extension (({ txt; loc }, _), _)
when List.mem ~eq:CCString.equal txt own_extensions ->
error loc
| _ -> super#structure_item s
method! expression p =
match p.pexp_desc with
| Pexp_extension ({ txt; loc }, _)
when List.mem ~eq:CCString.equal txt own_extensions ->
error loc
| _ -> super#expression p
method! module_expr m =
match m.pmod_desc with
| Pmod_extension ({ txt; loc }, _)
when List.mem ~eq:CCString.equal txt own_extensions ->
error loc
| _ -> super#module_expr m
end
let structure str = obj#structure str
end
let mapper top = function
| [] -> []
| fst :: _ as str ->
let clear () =
Uniq_ref.clear ();
Script_result.clear ();
Hashtbl.clear htl_tdl_entries;
Ptree.clear ()
in
let orig_log = fst.pstr_loc in
clear ();
Ast_helper.default_loc := orig_log;
Lconst.init (U.unsuffixed_file_name ());
U.convert_ctypes_exeptions @@ fun () ->
let module S = Scan () in
let st = S.structure str in
Ast_helper.default_loc := orig_log;
Ptree.Topscript.run top;
let ppx_main = Ptree.all_top_modules () in
let st = ppx_main @ st in
let module R = Replace () in
let st = R.structure st in
C_content.write_file ();
clear ();
st
let init top =
let () = Ppxc__script_real._init None in
(match !Options.mode with
| Options.Regular -> ()
| Options.Emulate ->
Ppxlib.Driver.add_arg "-pkg"
(Arg.String
(fun s ->
Options.findlib_pkgs :=
Std.Various.split_findlib_pkgs s @ !Options.findlib_pkgs))
~doc:"<opt> import types from findlib package <opt>");
let f =
lazy
(if
(match !Options.mode with
| Options.Regular -> false
| Options.Emulate -> true)
&& CCString.find ~sub:"merlin" (Ocaml_common.Ast_mapper.tool_name ()) < 0
then
let module M = Merlin () in
M.structure
else mapper top)
in
let impl str = (Lazy.force f) str in
Ppxlib.Driver.register_transformation ~impl "ppx_cstubs"
| (* This file is part of ppx_cstubs (https://github.com/fdopen/ppx_cstubs)
* Copyright (c) 2018-2019 fdopen
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*) |
ed25519.ml | open Error_monad
module Public_key_hash = struct
include
Blake2B.Make
(Base58)
(struct
let name = "Ed25519.Public_key_hash"
let title = "An Ed25519 public key hash"
let b58check_prefix = Base58.Prefix.ed25519_public_key_hash
let size = Some 20
end)
module Logging = struct
let tag = Tag.def ~doc:title name pp
end
end
let () = Base58.check_encoded_prefix Public_key_hash.b58check_encoding "tz1" 36
open Hacl.Ed25519
module Public_key = struct
type t = Hacl.public Hacl.Ed25519.key
let name = "Ed25519.Public_key"
let title = "Ed25519 public key"
let to_bytes = to_bytes
let to_string s = Bytes.to_string (to_bytes s)
let of_bytes_opt = pk_of_bytes
let of_string_opt s = of_bytes_opt (Bytes.of_string s)
let of_bytes_without_validation = of_bytes_opt
let size _ = pk_size
type Base58.data += Data of t
let b58check_encoding =
Base58.register_encoding
~prefix:Base58.Prefix.ed25519_public_key
~length:(size ())
~to_raw:to_string
~of_raw:of_string_opt
~wrap:(fun x -> Data x)
let () = Base58.check_encoded_prefix b58check_encoding "edpk" 54
let hash v = Public_key_hash.hash_bytes [to_bytes v]
include Compare.Make (struct
type nonrec t = t
let compare = Hacl.Ed25519.compare
end)
include Helpers.MakeRaw (struct
type nonrec t = t
let name = name
let of_bytes_opt = of_bytes_opt
let of_string_opt = of_string_opt
let to_string = to_string
end)
include Helpers.MakeB58 (struct
type nonrec t = t
let name = name
let b58check_encoding = b58check_encoding
end)
include Helpers.MakeEncoder (struct
type nonrec t = t
let name = name
let title = title
let raw_encoding =
let open Data_encoding in
conv to_bytes of_bytes_exn (Fixed.bytes (size ()))
let of_b58check = of_b58check
let of_b58check_opt = of_b58check_opt
let of_b58check_exn = of_b58check_exn
let to_b58check = to_b58check
let to_short_b58check = to_short_b58check
end)
let pp ppf t = Format.fprintf ppf "%s" (to_b58check t)
end
module Secret_key = struct
type t = Hacl.secret key
let name = "Ed25519.Secret_key"
let title = "An Ed25519 secret key"
let size = sk_size
let to_bytes = to_bytes
let to_string s = Bytes.to_string (to_bytes s)
let of_bytes_opt = sk_of_bytes
let of_string_opt s = of_bytes_opt (Bytes.of_string s)
let to_public_key = neuterize
type Base58.data += Data of t
let b58check_encoding =
Base58.register_encoding
~prefix:Base58.Prefix.ed25519_seed
~length:size
~to_raw:to_string
~of_raw:of_string_opt
~wrap:(fun sk -> Data sk)
(* Legacy NaCl secret key encoding. Used to store both sk and pk. *)
let secret_key_encoding =
Base58.register_encoding
~prefix:Base58.Prefix.ed25519_secret_key
~length:(sk_size + pk_size)
~to_raw:(fun sk ->
let pk = neuterize sk in
let buf = Bytes.create (sk_size + pk_size) in
blit_to_bytes sk buf ;
blit_to_bytes pk ~pos:sk_size buf ;
Bytes.unsafe_to_string buf)
~of_raw:(fun buf ->
let sk = Bytes.create sk_size in
Bytes.blit_string buf 0 sk 0 sk_size ;
sk_of_bytes sk)
~wrap:(fun x -> Data x)
let of_b58check_opt s =
match Base58.simple_decode b58check_encoding s with
| Some x -> Some x
| None -> Base58.simple_decode secret_key_encoding s
let of_b58check_exn s =
match of_b58check_opt s with
| Some x -> x
| None -> Format.kasprintf Stdlib.failwith "Unexpected data (%s)" name
let of_b58check s =
match of_b58check_opt s with
| Some x -> Ok x
| None ->
error_with "Failed to read a b58check_encoding data (%s): %S" name s
let to_b58check s = Base58.simple_encode b58check_encoding s
let to_short_b58check s =
String.sub
(to_b58check s)
0
(10 + String.length (Base58.prefix b58check_encoding))
let () =
Base58.check_encoded_prefix b58check_encoding "edsk" 54 ;
Base58.check_encoded_prefix secret_key_encoding "edsk" 98
include Compare.Make (struct
type nonrec t = t
let compare = compare
end)
include Helpers.MakeRaw (struct
type nonrec t = t
let name = name
let of_bytes_opt = of_bytes_opt
let of_string_opt = of_string_opt
let to_string = to_string
end)
include Helpers.MakeEncoder (struct
type nonrec t = t
let name = name
let title = title
let raw_encoding =
let open Data_encoding in
conv to_bytes of_bytes_exn (Fixed.bytes size)
let of_b58check = of_b58check
let of_b58check_opt = of_b58check_opt
let of_b58check_exn = of_b58check_exn
let to_b58check = to_b58check
let to_short_b58check = to_short_b58check
end)
let pp ppf t = Format.fprintf ppf "%s" (to_b58check t)
end
type t = Bytes.t
type watermark = Bytes.t
let name = "Ed25519"
let title = "An Ed25519 signature"
let size = size
let to_bytes s = Bytes.copy s
let to_string s = Bytes.to_string (to_bytes s)
let of_bytes_opt s = if Bytes.length s = size then Some s else None
let of_string_opt s = of_bytes_opt (Bytes.of_string s)
type Base58.data += Data of t
let b58check_encoding =
Base58.register_encoding
~prefix:Base58.Prefix.ed25519_signature
~length:size
~to_raw:to_string
~of_raw:of_string_opt
~wrap:(fun x -> Data x)
let () = Base58.check_encoded_prefix b58check_encoding "edsig" 99
include Helpers.MakeRaw (struct
type nonrec t = t
let name = name
let of_bytes_opt = of_bytes_opt
let of_string_opt = of_string_opt
let to_string = to_string
end)
include Helpers.MakeB58 (struct
type nonrec t = t
let name = name
let b58check_encoding = b58check_encoding
end)
include Helpers.MakeEncoder (struct
type nonrec t = t
let name = name
let title = title
let raw_encoding =
let open Data_encoding in
conv to_bytes of_bytes_exn (Fixed.bytes size)
let of_b58check = of_b58check
let of_b58check_opt = of_b58check_opt
let of_b58check_exn = of_b58check_exn
let to_b58check = to_b58check
let to_short_b58check = to_short_b58check
end)
let pp ppf t = Format.fprintf ppf "%s" (to_b58check t)
let zero = Bytes.make size '\000'
let sign ?watermark sk msg =
let msg =
Blake2B.to_bytes @@ Blake2B.hash_bytes
@@ match watermark with None -> [msg] | Some prefix -> [prefix; msg]
in
sign ~sk ~msg
let check ?watermark pk signature msg =
let msg =
Blake2B.to_bytes @@ Blake2B.hash_bytes
@@ match watermark with None -> [msg] | Some prefix -> [prefix; msg]
in
verify ~pk ~msg ~signature
let generate_key ?seed () =
match seed with
| None ->
let (pk, sk) = keypair () in
(Public_key.hash pk, pk, sk)
| Some seed -> (
let seedlen = Bytes.length seed in
if seedlen < Secret_key.size then
invalid_arg
(Printf.sprintf
"Ed25519.generate_key: seed must be at least %d bytes long (got \
%d)"
Secret_key.size
seedlen)
else
match sk_of_bytes (Bytes.sub seed 0 Secret_key.size) with
| None -> invalid_arg "Ed25519.generate_key: invalid seed"
| Some sk ->
let pk = neuterize sk in
(Public_key.hash pk, pk, sk))
let deterministic_nonce sk msg =
let key = Secret_key.to_bytes sk in
Hacl.Hash.SHA256.HMAC.digest ~key ~msg
let deterministic_nonce_hash sk msg =
Blake2B.to_bytes (Blake2B.hash_bytes [deterministic_nonce sk msg])
include (Compare.Bytes : Compare.S with type t := t)
| (*****************************************************************************)
(* *)
(* 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. *)
(* *)
(*****************************************************************************)
|
commitment_repr.mli | type t = {
blinded_public_key_hash : Blinded_public_key_hash.t;
amount : Tez_repr.t;
}
val encoding : t 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. *)
(* *)
(*****************************************************************************)
|
latexmacros.mli | (*s This module provides a table to store the translations of LaTeX
macros. A translation is a list of actions of the following type
[action]. *)
(* This code is an adaptation of a code written by Xavier Leroy in
1995-1997, in his own home-made latex2html translator. See
@inproceedings{Leroy-latex2html,
author = "Xavier Leroy",
title = "Lessons learned from the translation of
documentation from \LaTeX\ to {HTML}",
booktitle = "ERCIM/W4G Int. Workshop on WWW
Authoring and Integration Tools",
year = 1995,
month = feb}
*)
type action =
| Print of string
| Print_arg
| Skip_arg
| Raw_arg of (string -> unit)
| Parameterized of (string -> action list)
| Recursive of string
val def : string -> action list -> unit
val find_macro: string -> action list
val init_style_macros : string -> unit
(*s HTML entities *)
val html_entities : unit -> unit
val unicode_entities : unit -> unit
(*s Utility functions used in the definition of translations. *)
val out_channel : out_channel ref
val print_s : string -> unit
val print_c : char -> unit
| (**************************************************************************)
(* bibtex2html - A BibTeX to HTML translator *)
(* Copyright (C) 1997-2014 Jean-Christophe Filliâtre and Claude Marché *)
(* *)
(* This software is free software; you can redistribute it and/or *)
(* modify it under the terms of the GNU General Public *)
(* License version 2, as published by the Free Software Foundation. *)
(* *)
(* This software is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *)
(* *)
(* See the GNU General Public License version 2 for more details *)
(* (enclosed in the file GPL). *)
(**************************************************************************)
|
main.mli | (** Tezos Protocol Implementation - Protocol Signature Instance *)
type validation_mode =
| Application of {
block_header : Alpha_context.Block_header.t ;
baker : Alpha_context.public_key_hash ;
}
| Partial_application of {
block_header : Alpha_context.Block_header.t ;
baker : Alpha_context.public_key_hash ;
}
| Partial_construction of {
predecessor : Block_hash.t ;
}
| Full_construction of {
predecessor : Block_hash.t ;
protocol_data : Alpha_context.Block_header.contents ;
baker : Alpha_context.public_key_hash ;
}
type validation_state =
{ mode : validation_mode ;
chain_id : Chain_id.t ;
ctxt : Alpha_context.t ;
op_count : int ;
}
type operation_data = Alpha_context.packed_protocol_data
type operation = Alpha_context.packed_operation = {
shell: Operation.shell_header ;
protocol_data: operation_data ;
}
include Updater.PROTOCOL
with type block_header_data = Alpha_context.Block_header.protocol_data
and type block_header_metadata = Apply_results.block_metadata
and type block_header = Alpha_context.Block_header.t
and type operation_data := operation_data
and type operation_receipt = Apply_results.packed_operation_metadata
and type operation := operation
and type validation_state := validation_state
| (*****************************************************************************)
(* *)
(* 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. *)
(* *)
(*****************************************************************************)
|
chown.c | #include <caml/mlvalues.h>
#include <caml/memory.h>
#include <caml/signals.h>
#include "unixsupport.h"
CAMLprim value unix_chown(value path, value uid, value gid)
{
CAMLparam1(path);
char * p;
int ret;
caml_unix_check_path(path, "chown");
p = caml_stat_strdup(String_val(path));
caml_enter_blocking_section();
ret = chown(p, Int_val(uid), Int_val(gid));
caml_leave_blocking_section();
caml_stat_free(p);
if (ret == -1) uerror("chown", path);
CAMLreturn(Val_unit);
}
| /**************************************************************************/
/* */
/* 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. */
/* */
/**************************************************************************/
|
app.mli |
open! Core
open! Bonsai_web
open Bonsai_chat_common
val component
: room_list:Room.t list Value.t
-> current_room:Room.t option Value.t
-> messages:Message.t list Value.t
-> refresh_rooms:unit Effect.t
-> change_room:(Room.t -> unit Effect.t)
-> send_message:(room:Room.t -> contents:string -> unit Effect.t)
-> Vdom.Node.t Computation.t
| |
linear_format.ml | (* Marshal and unmarshal a compilation unit in linear format *)
type linear_item_info =
| Func of Linear.fundecl
| Data of Cmm.data_item list
type linear_unit_info =
{
mutable unit_name : string;
mutable items : linear_item_info list;
mutable for_pack : string option
}
type error =
| Wrong_format of string
| Wrong_version of string
| Corrupted of string
| Marshal_failed of string
exception Error of error
let save filename linear_unit_info =
let ch = open_out_bin filename in
Misc.try_finally (fun () ->
output_string ch Config.linear_magic_number;
output_value ch linear_unit_info;
(* Saved because Linearize and Emit depend on Cmm.label. *)
output_value ch (Cmm.cur_label ());
(* Compute digest of the contents and append it to the file. *)
flush ch;
let crc = Digest.file filename in
output_value ch crc
)
~always:(fun () -> close_out ch)
~exceptionally:(fun () -> raise (Error (Marshal_failed filename)))
let restore filename =
let ic = open_in_bin filename in
Misc.try_finally
(fun () ->
let magic = Config.linear_magic_number in
let buffer = really_input_string ic (String.length magic) in
if String.equal buffer magic then begin
try
let linear_unit_info = (input_value ic : linear_unit_info) in
let last_label = (input_value ic : Cmm.label) in
Cmm.reset ();
Cmm.set_label last_label;
let crc = (input_value ic : Digest.t) in
linear_unit_info, crc
with End_of_file | Failure _ -> raise (Error (Corrupted filename))
| Error e -> raise (Error e)
end
else if String.sub buffer 0 9 = String.sub magic 0 9 then
raise (Error (Wrong_version filename))
else
raise (Error (Wrong_format filename))
)
~always:(fun () -> close_in ic)
(* Error report *)
open Format
let report_error ppf = function
| Wrong_format filename ->
fprintf ppf "Expected Linear format. Incompatible file %a"
Location.print_filename filename
| Wrong_version filename ->
fprintf ppf
"%a@ is not compatible with this version of OCaml"
Location.print_filename filename
| Corrupted filename ->
fprintf ppf "Corrupted format@ %a"
Location.print_filename filename
| Marshal_failed filename ->
fprintf ppf "Failed to marshal Linear to file@ %a"
Location.print_filename filename
let () =
Location.register_error_of_exn
(function
| Error err -> Some (Location.error_of_printer_file report_error err)
| _ -> None
)
| (**************************************************************************)
(* *)
(* OCaml *)
(* *)
(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
(* Greta Yorsh, Jane Street Europe *)
(* *)
(* Copyright 1996 Institut National de Recherche en Informatique et *)
(* en Automatique. *)
(* Copyright 2019 Jane Street Group LLC *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
(* the GNU Lesser General Public License version 2.1, with the *)
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
|
ploc.mli | (** Locations and some pervasive type and value. *)
type t;;
(* located exceptions *)
exception Exc of t * exn;;
(** [Ploc.Exc loc e] is an encapsulation of the exception [e] with
the input location [loc]. To be used to specify a location
for an error. This exception must not be raised by [raise] but
rather by [Ploc.raise] (see below), to prevent the risk of several
encapsulations of [Ploc.Exc]. *)
val raise : t -> exn -> 'a;;
(** [Ploc.raise loc e], if [e] is already the exception [Ploc.Exc],
re-raise it (ignoring the new location [loc]), else raise the
exception [Ploc.Exc loc e]. *)
(* making locations *)
val make_loc : string -> int -> int -> int * int -> string -> t;;
(** [Ploc.make_loc fname line_nb bol_pos (bp, ep) comm] creates a location
starting at line number [line_nb], where the position of the beginning
of the line is [bol_pos] and between the positions [bp] (included) and
[ep] excluded. And [comm] is the comment before the location. The
positions are in number of characters since the begin of the stream. *)
val make_unlined : int * int -> t;;
(** [Ploc.make_unlined] is like [Ploc.make] except that the line number
is not provided (to be used e.g. when the line number is unknown. *)
val dummy : t;;
(** [Ploc.dummy] is a dummy location, used in situations when location
has no meaning. *)
(* getting location info *)
val file_name : t -> string;;
(** [Ploc.file_name loc] returns the file name of the location. *)
val first_pos : t -> int;;
(** [Ploc.first_pos loc] returns the position of the begin of the location
in number of characters since the beginning of the stream. *)
val last_pos : t -> int;;
(** [Ploc.last_pos loc] returns the position of the first character not
in the location in number of characters since the beginning of the
stream. *)
val line_nb : t -> int;;
(** [Ploc.line_nb loc] returns the line number of the location or [-1] if
the location does not contain a line number (i.e. built with
[Ploc.make_unlined]. *)
val bol_pos : t -> int;;
(** [Ploc.bol_pos loc] returns the position of the beginning of the line
of the location in number of characters since the beginning of
the stream, or [0] if the location does not contain a line number
(i.e. built with [Ploc.make_unlined]. *)
val line_nb_last : t -> int;;
val bol_pos_last : t -> int;;
(** Return the line number and the position of the beginning of the line
of the last position. *)
val comment : t -> string;;
(** [Ploc.comment loc] returns the comment before the location. *)
val comment_last : t -> string;;
(** [Ploc.comment loc] returns the last comment of the location. *)
(* combining locations *)
val encl : t -> t -> t;;
(** [Ploc.encl loc1 loc2] returns the location starting at the
smallest start of [loc1] and [loc2] and ending at the greatest end
of them. In other words, it is the location enclosing [loc1] and
[loc2]. *)
val shift : int -> t -> t;;
(** [Ploc.shift sh loc] returns the location [loc] shifted with [sh]
characters. The line number is not recomputed. *)
val sub : t -> int -> int -> t;;
(** [Ploc.sub loc sh len] is the location [loc] shifted with [sh]
characters and with length [len]. The previous ending position
of the location is lost. *)
val after : t -> int -> int -> t;;
(** [Ploc.after loc sh len] is the location just after loc (starting at
the end position of [loc]) shifted with [sh] characters and of length
[len]. *)
val with_comment : t -> string -> t;;
(** Change the comment part of the given location *)
val with_comment_last : t -> string -> t;;
val with_line_nb_last : t -> int -> t;;
val with_bol_pos_last : t -> int -> t;;
(* miscellaneous *)
val name : string ref;;
(** [Ploc.name.val] is the name of the location variable used in grammars
and in the predefined quotations for OCaml syntax trees. Default:
["loc"] *)
val get : t -> int * int * int * int * int;;
(** [Ploc.get loc] returns in order: 1/ the line number of the begin
of the location, 2/ its column, 3/ the line number of the first
character not in the location, 4/ its column and 5/ the length
of the location. The file where the location occurs (if any) may
be read during this operation. *)
val from_file : string -> t -> string * int * int * int;;
(** [Ploc.from_file fname loc] reads the file [fname] up to the
location [loc] and returns the real input file, the line number
and the characters location in the line; the real input file
can be different from [fname] because of possibility of line
directives typically generated by /lib/cpp. *)
(* pervasives *)
type 'a vala =
VaAnt of string
| VaVal of 'a
;;
(** Encloser of many abstract syntax tree nodes types, in "strict" mode.
This allow the system of antiquotations of abstract syntax tree
quotations to work when using the quotation kit [q_ast.cmo]. *)
val call_with : 'a ref -> 'a -> ('b -> 'c) -> 'b -> 'c;;
(** [Ploc.call_with r v f a] sets the reference [r] to the value [v],
then call [f a], and resets [r] to its initial value. If [f a] raises
an exception, its initial value is also reset and the exception is
re-raised. The result is the result of [f a]. *)
val string_of_location : t -> string;;
(** formats a location suitable for printing *)
(**/**)
val make : int -> int -> int * int -> t;;
(** deprecated function since version 6.00; use [make_loc] instead
with the empty string *)
| (* camlp5r *)
(* ploc.mli,v *)
(* Copyright (c) INRIA 2007-2017 *)
|
pow.c |
#include "fmpz_mat.h"
void
fmpz_mat_pow(fmpz_mat_t B, const fmpz_mat_t A, ulong exp)
{
slong d = fmpz_mat_nrows(A);
if (exp <= 2 || d <= 1)
{
if (exp == 0 || d == 0)
{
fmpz_mat_one(B);
}
else if (d == 1)
{
fmpz_pow_ui(fmpz_mat_entry(B, 0, 0),
fmpz_mat_entry(A, 0, 0), exp);
}
else if (exp == 1)
{
fmpz_mat_set(B, A);
}
else if (exp == 2)
{
fmpz_mat_sqr(B, A);
}
}
else
{
fmpz_mat_t T, U;
slong i;
fmpz_mat_init_set(T, A);
fmpz_mat_init(U, d, d);
for (i = ((slong) FLINT_BIT_COUNT(exp)) - 2; i >= 0; i--)
{
fmpz_mat_sqr(U, T);
if (exp & (WORD(1) << i))
fmpz_mat_mul(T, U, A);
else
fmpz_mat_swap(T, U);
}
fmpz_mat_swap(B, T);
fmpz_mat_clear(T);
fmpz_mat_clear(U);
}
}
| /*
Copyright (C) 2012 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/>.
*/ |
diagnostic.mli | module Extra : sig
type t =
| FailedRequire of
{ prefix : Libnames.qualid option
; refs : Libnames.qualid list
}
end
type t =
{ range : Range.t
; severity : int
; message : Pp.t
; extra : Extra.t list option
}
val is_error : t -> bool
| (************************************************************************)
(* Flèche => document manager: Language Support *)
(* Copyright 2019-2023 Inria -- Dual License LGPL 2.1 / GPL3+ *)
(* Written by: Emilio J. Gallego Arias *)
(************************************************************************)
|
sc_rollup_arith.ml | open Sc_rollup_repr
module PS = Sc_rollup_PVM_sem
module type P = sig
module Tree : Context.TREE with type key = string list and type value = bytes
type tree = Tree.tree
type proof
val proof_encoding : proof Data_encoding.t
val proof_before : proof -> State_hash.t
val proof_after : proof -> State_hash.t
val verify_proof :
proof -> (tree -> (tree * 'a) Lwt.t) -> (tree * 'a) option Lwt.t
val produce_proof :
Tree.t -> tree -> (tree -> (tree * 'a) Lwt.t) -> (proof * 'a) option Lwt.t
end
module type S = sig
include PS.S
val name : string
val parse_boot_sector : string -> string option
val pp_boot_sector : Format.formatter -> string -> unit
val pp : state -> (Format.formatter -> unit -> unit) Lwt.t
val get_tick : state -> Sc_rollup_tick_repr.t Lwt.t
type status = Halted | WaitingForInputMessage | Parsing | Evaluating
val get_status : state -> status Lwt.t
type instruction =
| IPush : int -> instruction
| IAdd : instruction
| IStore : string -> instruction
val equal_instruction : instruction -> instruction -> bool
val pp_instruction : Format.formatter -> instruction -> unit
val get_parsing_result : state -> bool option Lwt.t
val get_code : state -> instruction list Lwt.t
val get_stack : state -> int list Lwt.t
val get_var : state -> string -> int option Lwt.t
val get_evaluation_result : state -> bool option Lwt.t
val get_is_stuck : state -> string option Lwt.t
end
module Make (Context : P) :
S with type context = Context.Tree.t and type state = Context.tree = struct
module Tree = Context.Tree
type context = Context.Tree.t
type hash = State_hash.t
type proof = {
tree_proof : Context.proof;
given : PS.input option;
requested : PS.input_request;
}
let proof_encoding =
let open Data_encoding in
conv
(fun {tree_proof; given; requested} -> (tree_proof, given, requested))
(fun (tree_proof, given, requested) -> {tree_proof; given; requested})
(obj3
(req "tree_proof" Context.proof_encoding)
(req "given" (option PS.input_encoding))
(req "requested" PS.input_request_encoding))
let proof_start_state p = Context.proof_before p.tree_proof
let proof_stop_state p =
match (p.given, p.requested) with
| None, PS.No_input_required -> Some (Context.proof_after p.tree_proof)
| None, _ -> None
| _ -> Some (Context.proof_after p.tree_proof)
let proof_input_given p = p.given
let proof_input_requested p = p.requested
let name = "arith"
let parse_boot_sector s = Some s
let pp_boot_sector fmt s = Format.fprintf fmt "%s" s
type tree = Tree.tree
type status = Halted | WaitingForInputMessage | Parsing | Evaluating
type instruction =
| IPush : int -> instruction
| IAdd : instruction
| IStore : string -> instruction
let equal_instruction i1 i2 =
match (i1, i2) with
| IPush x, IPush y -> Compare.Int.(x = y)
| IAdd, IAdd -> true
| IStore x, IStore y -> Compare.String.(x = y)
| _, _ -> false
let pp_instruction fmt = function
| IPush x -> Format.fprintf fmt "push(%d)" x
| IAdd -> Format.fprintf fmt "add"
| IStore x -> Format.fprintf fmt "store(%s)" x
(*
The machine state is represented using a Merkle tree.
Here is the data model of this state represented in the tree:
- tick : Sc_rollup_tick_repr.t
The current tick counter of the machine.
- status : status
The current status of the machine.
- stack : int deque
The stack of integers.
- next_message : string option
The current input message to be processed.
- code : instruction deque
The instructions parsed from the input message.
- lexer_state : int * int
The internal state of the lexer.
- parsing_state : parsing_state
The internal state of the parser.
- parsing_result : bool option
The outcome of parsing.
- evaluation_result : bool option
The outcome of evaluation.
*)
module State = struct
type state = tree
module Monad : sig
type 'a t
val run : 'a t -> state -> (state * 'a option) Lwt.t
val is_stuck : string option t
val internal_error : string -> 'a t
val return : 'a -> 'a t
module Syntax : sig
val ( let* ) : 'a t -> ('a -> 'b t) -> 'b t
end
val remove : Tree.key -> unit t
val find_value : Tree.key -> 'a Data_encoding.t -> 'a option t
val children : Tree.key -> 'a Data_encoding.t -> (string * 'a) list t
val get_value : default:'a -> Tree.key -> 'a Data_encoding.t -> 'a t
val set_value : Tree.key -> 'a Data_encoding.t -> 'a -> unit t
end = struct
type 'a t = state -> (state * 'a option) Lwt.t
let return x state = Lwt.return (state, Some x)
let bind m f state =
let open Lwt_syntax in
let* state, res = m state in
match res with None -> return (state, None) | Some res -> f res state
module Syntax = struct
let ( let* ) = bind
end
let run m state = m state
let internal_error_key = ["internal_error"]
let internal_error msg tree =
let open Lwt_syntax in
let* tree = Tree.add tree internal_error_key (Bytes.of_string msg) in
return (tree, None)
let is_stuck tree =
let open Lwt_syntax in
let* v = Tree.find tree internal_error_key in
return (tree, Some (Option.map Bytes.to_string v))
let remove key tree =
let open Lwt_syntax in
let* tree = Tree.remove tree key in
return (tree, Some ())
let decode encoding bytes state =
let open Lwt_syntax in
match Data_encoding.Binary.of_bytes_opt encoding bytes with
| None -> internal_error "Error during decoding" state
| Some v -> return (state, Some v)
let find_value key encoding state =
let open Lwt_syntax in
let* obytes = Tree.find state key in
match obytes with
| None -> return (state, Some None)
| Some bytes ->
let* state, value = decode encoding bytes state in
return (state, Some value)
let children key encoding state =
let open Lwt_syntax in
let* children = Tree.list state key in
let rec aux = function
| [] -> return (state, Some [])
| (key, tree) :: children -> (
let* obytes = Tree.to_value tree in
match obytes with
| None -> internal_error "Invalid children" state
| Some bytes -> (
let* state, v = decode encoding bytes state in
match v with
| None -> return (state, None)
| Some v -> (
let* state, l = aux children in
match l with
| None -> return (state, None)
| Some l -> return (state, Some ((key, v) :: l)))))
in
aux children
let get_value ~default key encoding =
let open Syntax in
let* ov = find_value key encoding in
match ov with None -> return default | Some x -> return x
let set_value key encoding value tree =
let open Lwt_syntax in
Data_encoding.Binary.to_bytes_opt encoding value |> function
| None -> internal_error "Internal_Error during encoding" tree
| Some bytes ->
let* tree = Tree.add tree key bytes in
return (tree, Some ())
end
open Monad
module MakeVar (P : sig
type t
val name : string
val initial : t
val pp : Format.formatter -> t -> unit
val encoding : t Data_encoding.t
end) =
struct
let key = [P.name]
let create = set_value key P.encoding P.initial
let get =
let open Monad.Syntax in
let* v = find_value key P.encoding in
match v with
| None ->
(* This case should not happen if [create] is properly called. *)
return P.initial
| Some v -> return v
let set = set_value key P.encoding
let pp =
let open Monad.Syntax in
let* v = get in
return @@ fun fmt () -> Format.fprintf fmt "@[%s : %a@]" P.name P.pp v
end
module MakeDict (P : sig
type t
val name : string
val pp : Format.formatter -> t -> unit
val encoding : t Data_encoding.t
end) =
struct
let key k = [P.name; k]
let get k = find_value (key k) P.encoding
let set k v = set_value (key k) P.encoding v
let mapped_to k v state =
let open Lwt_syntax in
let* state', _ = Monad.(run (set k v) state) in
let* t = Tree.find_tree state (key k)
and* t' = Tree.find_tree state' (key k) in
Lwt.return (Option.equal Tree.equal t t')
let pp =
let open Monad.Syntax in
let* l = children [P.name] P.encoding in
let pp_elem fmt (key, value) =
Format.fprintf fmt "@[%s : %a@]" key P.pp value
in
return @@ fun fmt () -> Format.pp_print_list pp_elem fmt l
end
module MakeDeque (P : sig
type t
val name : string
val encoding : t Data_encoding.t
end) =
struct
(*
A stateful deque.
[[head; end[] is the index range for the elements of the deque.
The length of the deque is therefore [end - head].
*)
let head_key = [P.name; "head"]
let end_key = [P.name; "end"]
let get_head = get_value ~default:Z.zero head_key Data_encoding.z
let set_head = set_value head_key Data_encoding.z
let get_end = get_value ~default:(Z.of_int 0) end_key Data_encoding.z
let set_end = set_value end_key Data_encoding.z
let idx_key idx = [P.name; Z.to_string idx]
let top =
let open Monad.Syntax in
let* head_idx = get_head in
let* end_idx = get_end in
let* v = find_value (idx_key head_idx) P.encoding in
if Z.(leq end_idx head_idx) then return None
else
match v with
| None -> (* By invariants of the Deque. *) assert false
| Some x -> return (Some x)
let push x =
let open Monad.Syntax in
let* head_idx = get_head in
let head_idx' = Z.pred head_idx in
let* () = set_head head_idx' in
set_value (idx_key head_idx') P.encoding x
let pop =
let open Monad.Syntax in
let* head_idx = get_head in
let* end_idx = get_end in
if Z.(leq end_idx head_idx) then return None
else
let* v = find_value (idx_key head_idx) P.encoding in
match v with
| None -> (* By invariants of the Deque. *) assert false
| Some x ->
let* () = remove (idx_key head_idx) in
let head_idx = Z.succ head_idx in
let* () = set_head head_idx in
return (Some x)
let inject x =
let open Monad.Syntax in
let* end_idx = get_end in
let end_idx' = Z.succ end_idx in
let* () = set_end end_idx' in
set_value (idx_key end_idx) P.encoding x
let to_list =
let open Monad.Syntax in
let* head_idx = get_head in
let* end_idx = get_end in
let rec aux l idx =
if Z.(lt idx head_idx) then return l
else
let* v = find_value (idx_key idx) P.encoding in
match v with
| None -> (* By invariants of deque *) assert false
| Some v -> aux (v :: l) (Z.pred idx)
in
aux [] (Z.pred end_idx)
let clear = remove [P.name]
end
module CurrentTick = MakeVar (struct
include Sc_rollup_tick_repr
let name = "tick"
end)
module Vars = MakeDict (struct
type t = int
let name = "vars"
let encoding = Data_encoding.int31
let pp fmt x = Format.fprintf fmt "%d" x
end)
module Stack = MakeDeque (struct
type t = int
let name = "stack"
let encoding = Data_encoding.int31
end)
module Code = MakeDeque (struct
type t = instruction
let name = "code"
let encoding =
Data_encoding.(
union
[
case
~title:"push"
(Tag 0)
Data_encoding.int31
(function IPush x -> Some x | _ -> None)
(fun x -> IPush x);
case
~title:"add"
(Tag 1)
Data_encoding.unit
(function IAdd -> Some () | _ -> None)
(fun () -> IAdd);
case
~title:"store"
(Tag 2)
Data_encoding.string
(function IStore x -> Some x | _ -> None)
(fun x -> IStore x);
])
end)
module Boot_sector = MakeVar (struct
type t = string
let name = "boot_sector"
let initial = ""
let encoding = Data_encoding.string
let pp fmt s = Format.fprintf fmt "%s" s
end)
module Status = MakeVar (struct
type t = status
let initial = Halted
let encoding =
Data_encoding.string_enum
[
("Halted", Halted);
("WaitingForInput", WaitingForInputMessage);
("Parsing", Parsing);
("Evaluating", Evaluating);
]
let name = "status"
let string_of_status = function
| Halted -> "Halted"
| WaitingForInputMessage -> "WaitingForInputMessage"
| Parsing -> "Parsing"
| Evaluating -> "Evaluating"
let pp fmt status = Format.fprintf fmt "%s" (string_of_status status)
end)
module CurrentLevel = MakeVar (struct
type t = Raw_level_repr.t
let initial = Raw_level_repr.root
let encoding = Raw_level_repr.encoding
let name = "current_level"
let pp = Raw_level_repr.pp
end)
module MessageCounter = MakeVar (struct
type t = Z.t option
let initial = None
let encoding = Data_encoding.option Data_encoding.n
let name = "message_counter"
let pp fmt = function
| None -> Format.fprintf fmt "None"
| Some c -> Format.fprintf fmt "Some %a" Z.pp_print c
end)
module NextMessage = MakeVar (struct
type t = string option
let initial = None
let encoding = Data_encoding.(option string)
let name = "next_message"
let pp fmt = function
| None -> Format.fprintf fmt "None"
| Some s -> Format.fprintf fmt "Some %s" s
end)
type parser_state = ParseInt | ParseVar | SkipLayout
module LexerState = MakeVar (struct
type t = int * int
let name = "lexer_buffer"
let initial = (-1, -1)
let encoding = Data_encoding.(tup2 int31 int31)
let pp fmt (start, len) =
Format.fprintf fmt "lexer.(start = %d, len = %d)" start len
end)
module ParserState = MakeVar (struct
type t = parser_state
let name = "parser_state"
let initial = SkipLayout
let encoding =
Data_encoding.string_enum
[
("ParseInt", ParseInt);
("ParseVar", ParseVar);
("SkipLayout", SkipLayout);
]
let pp fmt = function
| ParseInt -> Format.fprintf fmt "Parsing int"
| ParseVar -> Format.fprintf fmt "Parsing var"
| SkipLayout -> Format.fprintf fmt "Skipping layout"
end)
module ParsingResult = MakeVar (struct
type t = bool option
let name = "parsing_result"
let initial = None
let encoding = Data_encoding.(option bool)
let pp fmt = function
| None -> Format.fprintf fmt "n/a"
| Some true -> Format.fprintf fmt "parsing succeeds"
| Some false -> Format.fprintf fmt "parsing fails"
end)
module EvaluationResult = MakeVar (struct
type t = bool option
let name = "evaluation_result"
let initial = None
let encoding = Data_encoding.(option bool)
let pp fmt = function
| None -> Format.fprintf fmt "n/a"
| Some true -> Format.fprintf fmt "evaluation succeeds"
| Some false -> Format.fprintf fmt "evaluation fails"
end)
module OutputCounter = MakeVar (struct
type t = Z.t
let initial = Z.zero
let name = "output_counter"
let encoding = Data_encoding.z
let pp = Z.pp_print
end)
module Output = MakeDict (struct
type t = Sc_rollup_PVM_sem.output
let name = "output"
let encoding = Sc_rollup_PVM_sem.output_encoding
let pp = Sc_rollup_PVM_sem.pp_output
end)
let pp =
let open Monad.Syntax in
let* status_pp = Status.pp in
let* message_counter_pp = MessageCounter.pp in
let* next_message_pp = NextMessage.pp in
let* parsing_result_pp = ParsingResult.pp in
let* parser_state_pp = ParserState.pp in
let* lexer_state_pp = LexerState.pp in
let* evaluation_result_pp = EvaluationResult.pp in
let* vars_pp = Vars.pp in
let* output_pp = Output.pp in
let* stack = Stack.to_list in
return @@ fun fmt () ->
Format.fprintf
fmt
"@[<v 0 >@;\
%a@;\
%a@;\
%a@;\
%a@;\
%a@;\
%a@;\
%a@;\
vars : %a@;\
output :%a@;\
stack : %a@;\
@]"
status_pp
()
message_counter_pp
()
next_message_pp
()
parsing_result_pp
()
parser_state_pp
()
lexer_state_pp
()
evaluation_result_pp
()
vars_pp
()
output_pp
()
Format.(pp_print_list pp_print_int)
stack
end
open State
type state = State.state
let pp state =
let open Lwt_syntax in
let* _, pp = Monad.run pp state in
match pp with
| None -> return @@ fun fmt _ -> Format.fprintf fmt "<opaque>"
| Some pp -> return pp
open Monad
let initial_state ctxt boot_sector =
let state = Tree.empty ctxt in
let m =
let open Monad.Syntax in
let* () = Boot_sector.set boot_sector in
let* () = Status.set Halted in
return ()
in
let open Lwt_syntax in
let* state, _ = run m state in
return state
let state_hash state =
let m =
let open Monad.Syntax in
let* status = Status.get in
match status with
| Halted -> return State_hash.zero
| _ ->
Context_hash.to_bytes @@ Tree.hash state |> fun h ->
return @@ State_hash.hash_bytes [h]
in
let open Lwt_syntax in
let* state = Monad.run m state in
match state with
| _, Some hash -> return hash
| _ -> (* Hash computation always succeeds. *) assert false
let boot =
let open Monad.Syntax in
let* () = Status.create in
let* () = NextMessage.create in
let* () = Status.set WaitingForInputMessage in
return ()
let result_of ~default m state =
let open Lwt_syntax in
let* _, v = run m state in
match v with None -> return default | Some v -> return v
let state_of m state =
let open Lwt_syntax in
let* s, _ = run m state in
return s
let get_tick = result_of ~default:Sc_rollup_tick_repr.initial CurrentTick.get
let is_input_state_monadic =
let open Monad.Syntax in
let* status = Status.get in
match status with
| WaitingForInputMessage -> (
let* level = CurrentLevel.get in
let* counter = MessageCounter.get in
match counter with
| Some n -> return (PS.First_after (level, n))
| None -> return PS.Initial)
| _ -> return PS.No_input_required
let is_input_state =
result_of ~default:PS.No_input_required @@ is_input_state_monadic
let get_status = result_of ~default:WaitingForInputMessage @@ Status.get
let get_code = result_of ~default:[] @@ Code.to_list
let get_parsing_result = result_of ~default:None @@ ParsingResult.get
let get_stack = result_of ~default:[] @@ Stack.to_list
let get_var state k = (result_of ~default:None @@ Vars.get k) state
let get_evaluation_result = result_of ~default:None @@ EvaluationResult.get
let get_is_stuck = result_of ~default:None @@ is_stuck
let set_input_monadic input =
let open PS in
let {inbox_level; message_counter; payload} = input in
let open Monad.Syntax in
let* boot_sector = Boot_sector.get in
let msg = boot_sector ^ payload in
let* () = CurrentLevel.set inbox_level in
let* () = MessageCounter.set (Some message_counter) in
let* () = NextMessage.set (Some msg) in
return ()
let set_input input = state_of @@ set_input_monadic input
let next_char =
let open Monad.Syntax in
LexerState.(
let* start, len = get in
set (start, len + 1))
let no_message_to_lex () =
internal_error "lexer: There is no input message to lex"
let current_char =
let open Monad.Syntax in
let* start, len = LexerState.get in
let* msg = NextMessage.get in
match msg with
| None -> no_message_to_lex ()
| Some s ->
if Compare.Int.(start + len < String.length s) then
return (Some s.[start + len])
else return None
let lexeme =
let open Monad.Syntax in
let* start, len = LexerState.get in
let* msg = NextMessage.get in
match msg with
| None -> no_message_to_lex ()
| Some s ->
let* () = LexerState.set (start + len, 0) in
return (String.sub s start len)
let push_int_literal =
let open Monad.Syntax in
let* s = lexeme in
match int_of_string_opt s with
| Some x -> Code.inject (IPush x)
| None -> (* By validity of int parsing. *) assert false
let push_var =
let open Monad.Syntax in
let* s = lexeme in
Code.inject (IStore s)
let start_parsing : unit t =
let open Monad.Syntax in
let* () = Status.set Parsing in
let* () = ParsingResult.set None in
let* () = ParserState.set SkipLayout in
let* () = LexerState.set (0, 0) in
let* () = Status.set Parsing in
let* () = Code.clear in
return ()
let start_evaluating : unit t =
let open Monad.Syntax in
let* () = EvaluationResult.set None in
let* () = Stack.clear in
let* () = Status.set Evaluating in
return ()
let stop_parsing outcome =
let open Monad.Syntax in
let* () = ParsingResult.set (Some outcome) in
start_evaluating
let stop_evaluating outcome =
let open Monad.Syntax in
let* () = EvaluationResult.set (Some outcome) in
Status.set WaitingForInputMessage
let parse : unit t =
let open Monad.Syntax in
let produce_add =
let* _ = lexeme in
let* () = next_char in
let* () = Code.inject IAdd in
return ()
in
let produce_int =
let* () = push_int_literal in
let* () = ParserState.set SkipLayout in
return ()
in
let produce_var =
let* () = push_var in
let* () = ParserState.set SkipLayout in
return ()
in
let is_digit d = Compare.Char.(d >= '0' && d <= '9') in
let is_letter d = Compare.Char.(d >= 'a' && d <= 'z') in
let* parser_state = ParserState.get in
match parser_state with
| ParseInt -> (
let* char = current_char in
match char with
| Some d when is_digit d -> next_char
| Some '+' ->
let* () = produce_int in
let* () = produce_add in
return ()
| Some ' ' ->
let* () = produce_int in
let* () = next_char in
return ()
| None ->
let* () = push_int_literal in
stop_parsing true
| _ -> stop_parsing false)
| ParseVar -> (
let* char = current_char in
match char with
| Some d when is_letter d -> next_char
| Some '+' ->
let* () = produce_var in
let* () = produce_add in
return ()
| Some ' ' ->
let* () = produce_var in
let* () = next_char in
return ()
| None ->
let* () = push_var in
stop_parsing true
| _ -> stop_parsing false)
| SkipLayout -> (
let* char = current_char in
match char with
| Some ' ' -> next_char
| Some '+' -> produce_add
| Some d when is_digit d ->
let* _ = lexeme in
let* () = next_char in
let* () = ParserState.set ParseInt in
return ()
| Some d when is_letter d ->
let* _ = lexeme in
let* () = next_char in
let* () = ParserState.set ParseVar in
return ()
| None -> stop_parsing true
| _ -> stop_parsing false)
let output v =
let open Monad.Syntax in
let open Sc_rollup_outbox_message_repr in
let* counter = OutputCounter.get in
let* () = OutputCounter.set (Z.succ counter) in
let unparsed_parameters =
Micheline.(Int ((), Z.of_int v) |> strip_locations)
in
let destination = Contract_hash.zero in
let entrypoint = Entrypoint_repr.default in
let transaction = {unparsed_parameters; destination; entrypoint} in
let message = Atomic_transaction_batch {transactions = [transaction]} in
let* outbox_level = CurrentLevel.get in
let output =
Sc_rollup_PVM_sem.{outbox_level; message_index = counter; message}
in
Output.set (Z.to_string counter) output
let evaluate =
let open Monad.Syntax in
let* i = Code.pop in
match i with
| None -> stop_evaluating true
| Some (IPush x) -> Stack.push x
| Some (IStore x) -> (
let* v = Stack.top in
match v with
| None -> stop_evaluating false
| Some v ->
if Compare.String.(x = "out") then output v else Vars.set x v)
| Some IAdd -> (
let* v = Stack.pop in
match v with
| None -> stop_evaluating false
| Some x -> (
let* v = Stack.pop in
match v with
| None -> stop_evaluating false
| Some y -> Stack.push (x + y)))
let reboot =
let open Monad.Syntax in
let* () = Status.set WaitingForInputMessage in
let* () = Stack.clear in
let* () = Code.clear in
return ()
let eval_step =
let open Monad.Syntax in
let* x = is_stuck in
match x with
| Some _ -> reboot
| None -> (
let* status = Status.get in
match status with
| Halted -> boot
| WaitingForInputMessage -> (
let* msg = NextMessage.get in
match msg with
| None ->
internal_error
"An input state was not provided an input message."
| Some _ -> start_parsing)
| Parsing -> parse
| Evaluating -> evaluate)
let ticked m =
let open Monad.Syntax in
let* tick = CurrentTick.get in
let* () = CurrentTick.set (Sc_rollup_tick_repr.next tick) in
m
let eval state = state_of (ticked eval_step) state
let step_transition input_given state =
let open Lwt_syntax in
let* request = is_input_state state in
let* state =
match request with
| PS.No_input_required -> eval state
| _ -> (
match input_given with
| Some input -> set_input input state
| None -> return state)
in
return (state, request)
let verify_proof proof =
let open Lwt_syntax in
let* result =
Context.verify_proof proof.tree_proof (step_transition proof.given)
in
match result with
| None -> return false
| Some (_, request) ->
return (PS.input_request_equal request proof.requested)
type error += Arith_proof_production_failed
let produce_proof context input_given state =
let open Lwt_result_syntax in
let*! result =
Context.produce_proof context state (step_transition input_given)
in
match result with
| Some (tree_proof, requested) ->
return {tree_proof; given = input_given; requested}
| None -> fail Arith_proof_production_failed
(* TEMPORARY: The following definitions will be extended in a future commit. *)
type output_proof = {
output_proof : Context.proof;
output_proof_state : hash;
output_proof_output : PS.output;
}
let output_proof_encoding =
let open Data_encoding in
conv
(fun {output_proof; output_proof_state; output_proof_output} ->
(output_proof, output_proof_state, output_proof_output))
(fun (output_proof, output_proof_state, output_proof_output) ->
{output_proof; output_proof_state; output_proof_output})
(obj3
(req "output_proof" Context.proof_encoding)
(req "output_proof_state" State_hash.encoding)
(req "output_proof_output" PS.output_encoding))
let output_of_output_proof s = s.output_proof_output
let state_of_output_proof s = s.output_proof_state
let output_key (output : PS.output) = Z.to_string output.message_index
let has_output output tree =
let open Lwt_syntax in
let* equal = Output.mapped_to (output_key output) output tree in
return (tree, equal)
let verify_output_proof p =
let open Lwt_syntax in
let transition = has_output p.output_proof_output in
let* result = Context.verify_proof p.output_proof transition in
match result with None -> return false | Some _ -> return true
type error += Arith_output_proof_production_failed
type error += Arith_invalid_claim_about_outbox
let produce_output_proof context state output_proof_output =
let open Lwt_result_syntax in
let*! output_proof_state = state_hash state in
let*! result =
Context.produce_proof context state @@ has_output output_proof_output
in
match result with
| Some (output_proof, true) ->
return {output_proof; output_proof_state; output_proof_output}
| Some (_, false) -> fail Arith_invalid_claim_about_outbox
| None -> fail Arith_output_proof_production_failed
end
module ProtocolImplementation = Make (struct
module Tree = struct
include Context.Tree
type tree = Context.tree
type t = Context.t
type key = string list
type value = bytes
end
type tree = Context.tree
type proof = Context.Proof.tree Context.Proof.t
let verify_proof p f =
Lwt.map Result.to_option (Context.verify_tree_proof p f)
let produce_proof _context _state _f =
(* Can't produce proof without full context*)
Lwt.return None
let kinded_hash_to_state_hash = function
| `Value hash | `Node hash ->
State_hash.hash_bytes [Context_hash.to_bytes hash]
let proof_before proof = kinded_hash_to_state_hash proof.Context.Proof.before
let proof_after proof = kinded_hash_to_state_hash proof.Context.Proof.after
let proof_encoding = Context.Proof_encoding.V1.Tree32.tree_proof_encoding
end)
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2021 Nomadic Labs <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
higher_kinded_cinaps.mli |
open! Base
val print_module_type_monad : unit -> unit
val print_module_type_s : unit -> unit
val print_functor_implementations : unit -> unit
val print_functor_types : unit -> unit
val print_type_aliases : include_comments:bool -> unit
| |
voting_period_repr.mli | (** The voting period kinds are ordered as follows:
Proposal -> Exploration -> Cooldown -> Promotion -> Adoption.
This order is the one used be the function [succ] below.
*)
type kind =
| Proposal (** protocols can be proposed *)
| Exploration (** a proposal can be voted *)
| Cooldown (** a delay before the second vote of the Promotion period. *)
| Promotion (** activation can be voted *)
| Adoption (** a delay before activation *)
val kind_encoding : kind Data_encoding.t
(** A voting period can be of several kinds and is uniquely identified by
the counter 'index'. The 'start_position' represents the relative
position of the first level of the period with respect to the
first level of the Alpha family of protocols. *)
type voting_period = {index : Int32.t; kind : kind; start_position : Int32.t}
type t = voting_period
(** Information about a block with respect to the voting period it
belongs to: the voting period, the position within the voting
period and the number of remaining blocks till the end of the
period. The following invariant is satisfied:
`position + remaining + 1 = blocks_per_voting_period` *)
type info = {voting_period : t; position : Int32.t; remaining : Int32.t}
val root : start_position:Int32.t -> t
include Compare.S with type t := voting_period
val encoding : t Data_encoding.t
val info_encoding : info Data_encoding.t
val pp : Format.formatter -> t -> unit
val pp_info : Format.formatter -> info -> unit
val pp_kind : Format.formatter -> kind -> unit
(** [raw_reset period ~start_position] increment the index by one and set the
kind to Proposal which is the period kind that start the voting
process. [start_position] is the level at wich this voting_period started.
*)
val raw_reset : t -> start_position:Int32.t -> t
(** [raw_succ period ~start_position] increment the index by one and set the
kind to its successor. [start_position] is the level at which this
voting_period started. *)
val raw_succ : t -> start_position:Int32.t -> t
val position_since : Level_repr.t -> t -> Int32.t
val remaining_blocks :
Level_repr.t -> t -> blocks_per_voting_period:Int32.t -> Int32.t
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
owl_fft_generic.mli |
(** Fast Fourier Transform *)
open Owl_dense_ndarray_generic
(** {5 Basic functions} *)
val fft : ?axis:int -> (Complex.t, 'a) t -> (Complex.t, 'a) t
(**
``fft ~axis x`` performs 1-dimensional FFT on a complex input. ``axis`` is the
highest dimension if not specified. The return is not scaled.
*)
val ifft : ?axis:int -> (Complex.t, 'a) t -> (Complex.t, 'a) t
(**
``ifft ~axis x`` performs inverse 1-dimensional FFT on a complex input. ``axis``
is the highest dimension by default.
*)
val rfft : ?axis:int -> otyp:(Complex.t, 'a) kind -> (float, 'b) t -> (Complex.t, 'a) t
(**
``rfft ~axis ~otyp x`` performs 1-dimensional FFT on real input along the
``axis``. ``otyp`` is used to specify the output type, it must be the consistent
precision with input ``x``. You can skip this parameter by using a submodule
with specific precision such as ``Owl.Fft.S`` or ``Owl.Fft.D``.
*)
val irfft
: ?axis:int
-> ?n:int
-> otyp:(float, 'a) kind
-> (Complex.t, 'b) t
-> (float, 'a) t
(**
``irfft ~axis ~n x`` is the inverse function of ``rfft``. Note the ``n`` parameter
is used to specified the size of output.
*)
| (*
* OWL - OCaml Scientific and Engineering Computing
* Copyright (c) 2016-2020 Liang Wang <liang.wang@cl.cam.ac.uk>
*) |
dune |
; This file was automatically generated, do not edit.
; Edit file manifest/main.ml instead.
(executables
(names
test_sampling_data
test_sampling_code
test_autocompletion
test_distribution)
(libraries
tezos-base
tezos-micheline
tezos-micheline-rewriting
tezos-protocol-013-PtJakart
tezos-benchmark
tezos-benchmark-type-inference-013-PtJakart
tezos-benchmark-013-PtJakart
tezos-013-PtJakart-test-helpers
tezos-error-monad
alcotest-lwt
prbnmcn-stats)
(flags
(:standard
-open Tezos_base.TzPervasives.Error_monad.Legacy_monad_globals
-open Tezos_micheline
-open Tezos_protocol_013_PtJakart
-open Tezos_benchmark
-open Tezos_benchmark_type_inference_013_PtJakart
-open Tezos_benchmark_013_PtJakart
-open Tezos_013_PtJakart_test_helpers)))
(rule
(alias runtest_micheline_rewriting_data)
(action (run %{exe:test_sampling_data.exe} 1234)))
(rule
(alias runtest_micheline_rewriting_code)
(action (run %{exe:test_sampling_code.exe} 1234)))
(rule
(alias runtest)
(package tezos-benchmark-013-PtJakart)
(deps
(alias runtest_micheline_rewriting_data)
(alias runtest_micheline_rewriting_code))
(action (progn)))
| |
register.ml | (* This file is part of Bisect_ppx, released under the MIT license. See
LICENSE.md for details, or visit
https://github.com/aantron/bisect_ppx/blob/master/LICENSE.md. *)
let conditional = ref false
let enabled () =
match !conditional with
| false ->
`Enabled
| true ->
match Sys.getenv "BISECT_ENABLE" with
| exception Not_found ->
`Disabled
| s when String.uppercase_ascii s = "YES" ->
`Enabled
| _ ->
`Disabled
let conditional_exclude_file filename =
match enabled () with
| `Enabled -> Exclusions.add_from_file filename
| `Disabled -> ()
let switches = [
("--exclude-files",
Arg.String Exclusions.add_file,
"<regexp> Exclude files matching <regexp>");
("--exclusions",
Arg.String conditional_exclude_file,
"<filename> Exclude functions listed in given file");
("--conditional",
Arg.Set conditional,
" Instrument only when BISECT_ENABLE is YES");
("--bisect-file",
Arg.String (fun s -> Instrument.bisect_file := Some s),
" Default value for BISECT_FILE environment variable");
("--bisect-silent",
Arg.String (fun s -> Instrument.bisect_silent := Some s),
" Default value for BISECT_SILENT environment variable");
("--bisect-sigterm",
Arg.Set Instrument.bisect_sigterm,
(" Install a signal handler writing coverage data and" ^
" terminating on reception of SIGTERM"));
]
let () =
Arg.align switches
|> List.iter (fun (key, spec, doc) -> Ppxlib.Driver.add_arg key spec ~doc)
let () =
let impl ctxt ast =
match enabled () with
| `Enabled ->
new Instrument.instrumenter#transform_impl_file ctxt ast
| `Disabled ->
ast
in
let instrument = Ppxlib.Driver.Instrument.V2.make impl ~position:After in
Ppxlib.Driver.register_transformation ~instrument "bisect_ppx"
| (* This file is part of Bisect_ppx, released under the MIT license. See
LICENSE.md for details, or visit
https://github.com/aantron/bisect_ppx/blob/master/LICENSE.md. *) |
ones.ml |
open Pp_binary_ints.Int
open Pp_binary_ints.Flags
let configs =
[ { default with separators = false; prefix_non_zero = false }
; { default with separators = false; prefix_non_zero = true }
; { default with separators = true; prefix_non_zero = false }
; { default with separators = true; prefix_non_zero = true }
]
let zero_ocaml_configs =
List.map (fun x -> { x with padding = Zeros; zero_printing = OCaml }) configs
let left_ocaml_configs =
List.map (fun x -> { x with padding = Left; zero_printing = OCaml }) configs
let right_ocaml_configs =
List.map (fun x -> { x with padding = Right; zero_printing = OCaml }) configs
let zero_inherit_configs =
List.map (fun x -> { x with padding = Zeros; zero_printing = InheritNonZero }) configs
let left_inherit_configs =
List.map (fun x -> { x with padding = Left; zero_printing = InheritNonZero }) configs
let right_inherit_configs =
List.map (fun x -> { x with padding = Right; zero_printing = InheritNonZero }) configs
let test_width configs min_width n : string list =
List.map (fun flags -> to_string_with ~flags ~min_width n) configs
(** * One printing *)
let%test "one default" =
"0b1" =
to_string 1
let%test "one default manual" =
"0b1" =
to_string_with ~flags:default ~min_width:1 1
(** ** Zero Padding, OCaml *)
let%test "zero ocaml 1" =
["1";"0b1";"1";"0b1"] =
test_width zero_ocaml_configs 1 1
let%test "zero ocaml 2" =
["01";"0b1";"01";"0b1"] =
test_width zero_ocaml_configs 2 1
let%test "zero ocaml 3" =
["001";"0b1";"001";"0b1"] =
test_width zero_ocaml_configs 3 1
let%test "zero ocaml 4" =
["0001";"0b01";"0001";"0b01"] =
test_width zero_ocaml_configs 4 1
let%test "zero ocaml 5" =
["00001";"0b001";"00001";"0b001"] =
test_width zero_ocaml_configs 5 1
let%test "zero ocaml 6" =
["000001";"0b0001";"0_0001";"0b0001"] =
test_width zero_ocaml_configs 6 1
let%test "zero ocaml 7" =
["0000001";"0b00001";"00_0001";"0b00001"] =
test_width zero_ocaml_configs 7 1
let%test "zero ocaml 8" =
["00000001";"0b000001";"000_0001";"0b0_0001"] =
test_width zero_ocaml_configs 8 1
(** ** Left Padding, OCaml *)
let%test "left ocaml 1" =
["1";"0b1";"1";"0b1"] =
test_width left_ocaml_configs 1 1
let%test "left ocaml 2" =
[" 1";"0b1";" 1";"0b1"] =
test_width left_ocaml_configs 2 1
let%test "left ocaml 3" =
[" 1";"0b1";" 1";"0b1"] =
test_width left_ocaml_configs 3 1
let%test "left ocaml 4" =
[" 1";" 0b1";" 1";" 0b1"] =
test_width left_ocaml_configs 4 1
let%test "left ocaml 5" =
[" 1";" 0b1";" 1";" 0b1"] =
test_width left_ocaml_configs 5 1
(** ** Right Padding, OCaml *)
let%test "right ocaml 1" =
["1";"0b1";"1";"0b1"] =
test_width right_ocaml_configs 1 1
let%test "right ocaml 2" =
["1 ";"0b1";"1 ";"0b1"] =
test_width right_ocaml_configs 2 1
let%test "right ocaml 3" =
["1 ";"0b1";"1 ";"0b1"] =
test_width right_ocaml_configs 3 1
let%test "right ocaml 4" =
["1 ";"0b1 ";"1 ";"0b1 "] =
test_width right_ocaml_configs 4 1
let%test "right ocaml 5" =
["1 ";"0b1 ";"1 ";"0b1 "] =
test_width right_ocaml_configs 5 1
(** ** Zero Padding, Inherit *)
let%test "zero inherit 1" =
["1";"0b1";"1";"0b1"] =
test_width zero_inherit_configs 1 1
let%test "zero inherit 2" =
["01";"0b1";"01";"0b1"] =
test_width zero_inherit_configs 2 1
let%test "zero inherit 3" =
["001";"0b1";"001";"0b1"] =
test_width zero_inherit_configs 3 1
let%test "zero inherit 4" =
["0001";"0b01";"0001";"0b01"] =
test_width zero_inherit_configs 4 1
let%test "zero inherit 5" =
["00001";"0b001";"00001";"0b001"] =
test_width zero_inherit_configs 5 1
let%test "zero inherit 6" =
["000001";"0b0001";"0_0001";"0b0001"] =
test_width zero_inherit_configs 6 1
let%test "zero inherit 7" =
["0000001";"0b00001";"00_0001";"0b00001"] =
test_width zero_inherit_configs 7 1
let%test "zero inherit 8" =
["00000001";"0b000001";"000_0001";"0b0_0001"] =
test_width zero_inherit_configs 8 1
(** ** Left Padding, Inherit *)
let%test "left inherit 1" =
["1";"0b1";"1";"0b1"] =
test_width left_inherit_configs 1 1
let%test "left inherit 2" =
[" 1";"0b1";" 1";"0b1"] =
test_width left_inherit_configs 2 1
let%test "left inherit 3" =
[" 1";"0b1";" 1";"0b1"] =
test_width left_inherit_configs 3 1
let%test "left inherit 4" =
[" 1";" 0b1";" 1";" 0b1"] =
test_width left_inherit_configs 4 1
let%test "left inherit 5" =
[" 1";" 0b1";" 1";" 0b1"] =
test_width left_inherit_configs 5 1
(** ** Right Padding, Inherit *)
let%test "right inherit 1" =
["1";"0b1";"1";"0b1"] =
test_width right_inherit_configs 1 1
let%test "right inherit 2" =
["1 ";"0b1";"1 ";"0b1"] =
test_width right_inherit_configs 2 1
let%test "right inherit 3" =
["1 ";"0b1";"1 ";"0b1"] =
test_width right_inherit_configs 3 1
let%test "right inherit 4" =
["1 ";"0b1 ";"1 ";"0b1 "] =
test_width right_inherit_configs 4 1
let%test "right inherit 5" =
["1 ";"0b1 ";"1 ";"0b1 "] =
test_width right_inherit_configs 5 1
| |
hangul.ml | (* 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 2 of *)
(* the License, or (at your option) any later version. *)
(* As a special exception to the GNU Library General Public License, you *)
(* may link, statically or dynamically, a "work that uses this library" *)
(* with a publicly distributed version of this library to produce an *)
(* executable file containing portions of this library, and distribute *)
(* that executable file under terms of your choice, without any of the *)
(* additional requirements listed in clause 6 of the GNU Library General *)
(* Public License. By "a publicly distributed version of this library", *)
(* we mean either the unmodified Library as distributed by the authors, *)
(* or a modified version of this library that is distributed under the *)
(* conditions defined in clause 3 of the GNU Library General Public *)
(* License. This exception does not however invalidate any other reasons *)
(* why the executable file might be covered by the GNU Library General *)
(* Public 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 GNU *)
(* Lesser General Public License for more details. *)
(* You should have received a copy of the GNU Lesser General Public *)
(* License along with this library; if not, write to the Free Software *)
(* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *)
(* USA *)
(* You can contact the authour by sending email to *)
(* yoriyuki.y@gmail.com *)
let sbase = 0xac00
let lbase = 0x1100
let vbase = 0x1161
let tbase = 0x11a7
let lcount = 19
let vcount = 21
let tcount = 28
let ncount = vcount * tcount
let scount = lcount * ncount
let decompose u =
let n = UChar.uint_code u - sbase in
let l = lbase + (n / ncount) in
let v = vbase + (n mod ncount / tcount) in
let t = tbase + (n mod tcount) in
if t = tbase then [UChar.chr_of_uint l; UChar.chr_of_uint v]
else [UChar.chr_of_uint l; UChar.chr_of_uint v; UChar.chr_of_uint t]
let add_decomposition x u =
let n = UChar.uint_code u - sbase in
if n < 0 || n >= scount then XString.add_char x u
else begin
XString.add_char x (UChar.chr_of_uint (lbase + (n / ncount)));
XString.add_char x (UChar.chr_of_uint (vbase + (n mod ncount / tcount)));
let t = tbase + (n mod tcount) in
if t = tbase then () else XString.add_char x (UChar.chr_of_uint t)
end
let compose x' x =
if XString.length x = 0 then ()
else (
let pos = ref 0 in
let last = ref (UChar.uint_code (XString.get x 0)) in
for i = 1 to XString.length x - 1 do
let n = UChar.uint_code (XString.get x i) in
let l = !last - lbase in
let v = n - vbase in
if 0 <= l && l < lcount && 0 <= v && v < vcount then
last := sbase + (((l * vcount) + v) * tcount)
else (
let s = !last - sbase in
let t = n - tbase in
if 0 <= s && s < scount && s mod tcount = 0 && 0 <= t && t < tcount then
last := !last + t
else begin
XString.set x' !pos (UChar.chr_of_uint !last);
last := n;
incr pos
end)
done;
XString.set x' !pos (UChar.chr_of_uint !last);
XString.shrink x' (!pos + 1))
| (** Hangul *)
(* Copyright (C) 2003 Yamagata Yoriyuki. *)
|
mol2_tool.ml |
(* basic operations on the Tripos Mol2 File Format:
- extract multiple molecules
- correct the atom names to be unique if necessary
Reference document: Tripos Mol2 File Format, SYBYL 7.1 (Mid-2005),
http://www.tripos.com/data/support/mol2.pdf *)
(* This tool reads the whole MOL2 file in memory at once and hence
will blow up on too big files *)
open Batteries
open Printf
module A = Array
module F = Filename
module L = List
module Log = Dolog.Log
module MU = My_utils
module Mol2 = Mol2_parser
module S = String
type parser_state = Reading_atoms | Other
let process_mol2_line state_r count_r l acc =
if (S.starts_with l "@<TRIPOS>MOLECULE") then
match acc with
[] -> (None , [l]) (* first molecule in the file *)
| _ -> (Some (L.rev acc), [l])
else begin
let l' =
if (S.starts_with l " ") && (!state_r = Reading_atoms) then
match Str.split (Str.regexp "[ ]+") l with
_id::name::x::_y::_z::_type::_optional_fields -> (
(* atom_name fields from the original mol2 file are made unique
so that pdb2pqr will not choke on them later on *)
let name_pos = S.find l name in
let x_pos = S.find l x in
let prfx = String.sub l 0 name_pos in
let sufx = String.sub l x_pos ((S.length l) - x_pos) in
let stripped =
Str.global_replace (Str.regexp "[0-9]*$") "" name in
let unique_name = stripped ^ (string_of_int !count_r) in
incr count_r;
let prev_len = x_pos - name_pos in
let new_name =
unique_name ^
(S.make (prev_len - (S.length unique_name)) ' ') in
sprintf "%s%s %s" prfx new_name sufx)
| _ -> failwith ("mol2_parser.ml: process_mol2_line: \
invalid atom line: " ^ l)
else l
in
if (S.starts_with l "@<TRIPOS>ATOM") then
(state_r := Reading_atoms; count_r := 0);
if (S.starts_with l "@<TRIPOS>BOND") then
state_r := Other;
(None, l' :: acc)
end
let molecule_name m = match m with
[] -> failwith "mol2_parser.ml: molecule_name: empty molecule"
| [_] -> failwith "mol2_parser.ml: molecule_name: molecule without a name"
| _ :: name :: _ -> name
(* remove all lines before the first '@<TRIPOS>MOLECULE' one *)
let rec skip_header mol2_lines =
match mol2_lines with
[] -> []
| x :: xs ->
if S.starts_with x "@<TRIPOS>MOLECULE"
then mol2_lines
else skip_header xs
(* get the list of molecules *)
let read_mol2_file f =
MU.enforce_any_file_extension f [".mol2"];
let state = ref Other in
let count = ref 0 in
let lines = skip_header (MU.string_list_of_file f) in
let molecules, molecule =
L.fold_left
(fun (global_acc, local_acc) l ->
match process_mol2_line state count l local_acc with
| Some molecule, new_local_acc ->
(molecule :: global_acc, new_local_acc)
| None , new_local_acc ->
(global_acc , new_local_acc))
([], []) lines in
let all_molecules = (L.rev molecule) :: molecules in
L.rev_map
(* the "@<TRIPOS>SUBSTRUCTURE" line is required at the end of
each molecule by pdb2pqr.py *)
(fun m ->
let corrected_m =
if L.mem "@<TRIPOS>SUBSTRUCTURE" m then
m
else
L.append m ["@<TRIPOS>SUBSTRUCTURE"] in
(corrected_m, molecule_name m))
all_molecules
(* explode a multiple molecules mol2 file: each molecule will be stored under
its own directory in a single molecule mol2 file
- return the list of files created *)
let explode input_f =
let molecules = read_mol2_file input_f in
let out_dir = F.chop_extension input_f in
Log.info "molecules in %s: %d" input_f (L.length molecules);
L.mapi
(fun j (m, m_name) ->
let new_dir = sprintf "%s_%07d" out_dir (j + 1) in
(* a directory needs at least rwx for the user so that we can
go and write into it later on *)
(try Unix.mkdir new_dir 0o700 with exn ->
(match exn with
| Unix.Unix_error (err_code, f_name, param) ->
(match err_code with
| Unix.EEXIST -> ()
(* dir already exist, we don't care so much in fact *)
(*
printf
"mol2_tool.ml: warning: directory already exist: %s\n"
new_dir
*)
| _ -> failwith (sprintf
"mol2_tool.ml: %s: %s %s"
(Unix.error_message err_code) f_name param))
| _ -> raise exn));
let new_file = sprintf "%s/%07d.mol2" new_dir (j + 1) in
MU.string_list_to_file new_file m;
(new_file, m_name)
)
molecules
let main () =
Log.set_log_level Log.INFO;
Log.color_on();
if A.length Sys.argv <> 2 then
(fprintf stderr "%s"
("error: incorrect number of parameters\n" ^
"usage: " ^ Sys.argv.(0) ^ " FILE.mol2\n");
(* 0 1 *)
exit 1)
else
let new_files = explode Sys.argv.(1) in
Log.info "Files created:";
L.iter
(fun (fn, _m_name) -> Log.info "%s" fn)
new_files
;;
main()
| |
dune |
(executable
(name pp)
(modules pp)
(libraries ppx_yojson ppxlib))
(executable
(name gen_dune_rules)
(modules gen_dune_rules))
| |
discover.ml | (* This file is part of Lwt, released under the MIT license. See LICENSE.md for
details, or visit https://github.com/ocsigen/lwt/blob/master/LICENSE.md. *)
(** Lwt_unix feature discovery script.
This program tests system features, and outputs four files:
- [src/unix/lwt_features.h]: feature test results for consumption by C code.
- [src/unix/lwt_features.ml]: test results for consumption by OCaml code.
- [src/unix/unix_c_flags.sexp]: C compiler flags for Lwt_unix C sources.
- [src/unix/unix_c_library_flags.sexp]: C linker flags for Lwt_unix.
[src/unix/lwt_features.h] contains only basic [#define] macros. It is
included in [src/unix/lwt_config.h], which computes a few more useful
macros. [src/unix/lwt_config.h] is the file that is then directly included
by all the C sources.
[src/unix/lwt_features.ml] is included by [src/unix/lwt_config.ml] in the
same way.
You can examine the generated [lwt_features.h] by running [dune build] and
looking in [_build/default/src/unix/lwt_features.h], and similarly for
[lwt_features.ml].
This program tries to detect everything automatically. If it is not behaving
correctly, its behavior can be tweaked by passing it arguments. There are
four ways to do so:
- By editing [src/unix/dune], to pass arguments to [discover.exe] on the
command line.
- By setting the environment variable [LWT_DISCOVER_ARGUMENTS]. The syntax
is the same as the command line.
- By writing a file [src/unix/discover_arguments]. The syntax is again the
same as the command line.
- By running [dune exec src/unix/config/discover.exe -- --save] with
additional arguments. Those arguments will be written to
[src/unix/discover_arguments] for the build to use later.
The possible arguments can be found by running
{v
dune exec src/unix/config/discover.exe -- --help
v}
In addition, the environment variables [LIBEV_CFLAGS], [LIBEV_LIBS],
[PTHREAD_CFLAGS], and [PTHREAD_LIBS] can be used to override the flags used
for compiling with libev and pthreads.
This [discover.ml] was added in Lwt 4.3.0, so if you pass arguments to
[discover.ml], 4.3.0 is the minimal required version of Lwt.
The code is broken up into sections, each of which is an OCaml module. If
your text editor supports code folding, it will make reading this file much
easier if you fold the structures.
Add feature tests at the end of module [Features]. For most cases, what to
do should be clear from the feature tests that are already in that
module. *)
module Configurator = Configurator.V1
let split = Configurator.Flags.extract_blank_separated_words
let uppercase = String.uppercase_ascii
(* Command-line arguments and environment variables. *)
module Arguments :
sig
val use_libev : bool option ref
val use_pthread : bool option ref
val android_target : bool option ref
val libev_default : bool option ref
val verbose : bool ref
val args : (Arg.key * Arg.spec * Arg.doc) list
val parse_environment_variable : unit -> unit
val parse_arguments_file : unit -> unit
end =
struct
let use_libev = ref None
let use_pthread = ref None
let android_target = ref None
let libev_default = ref None
let verbose = ref false
let set reference =
Arg.Bool (fun value -> reference := Some value)
let args = [
"--use-libev", set use_libev,
"BOOLEAN whether to check for libev";
"--use-pthread", set use_pthread,
"BOOLEAN whether to check for libpthread";
"--android-target", set android_target,
"BOOLEAN whether to compile for Android";
"--libev-default", set libev_default,
"BOOLEAN whether to use the libev backend by default";
"--verbose", Arg.Set verbose,
"BOOLEAN show results of feature detection";
]
let environment_variable = "LWT_DISCOVER_ARGUMENTS"
let arguments_file = "discover_arguments"
let parse arguments =
try
Arg.parse_argv
~current:(ref 0)
(Array.of_list ((Filename.basename Sys.argv.(0))::(split arguments)))
(Arg.align args)
(fun s ->
raise (Arg.Bad (Printf.sprintf "Unrecognized argument '%s'" s)))
(Printf.sprintf
"Environment variable usage: %s=[OPTIONS]" environment_variable)
with
| Arg.Bad s ->
prerr_string s;
exit 2
| Arg.Help s ->
print_string s;
exit 0
let parse_environment_variable () =
match Sys.getenv environment_variable with
| exception Not_found ->
()
| arguments ->
parse arguments
let parse_arguments_file () =
try
let channel = open_in arguments_file in
parse (input_line channel);
close_in channel
with _ ->
()
end
module C_library_flags :
sig
val detect :
?env_var:string ->
?package:string ->
?header:string ->
Configurator.t ->
library:string ->
unit
val ws2_32_lib : Configurator.t -> unit
val c_flags : unit -> string list
val link_flags : unit -> string list
val add_link_flags : string list -> unit
end =
struct
let c_flags = ref []
let link_flags = ref []
let extend c_flags' link_flags' =
c_flags := !c_flags @ c_flags';
link_flags := !link_flags @ link_flags'
let add_link_flags flags =
extend [] flags
let (//) = Filename.concat
let default_search_paths = [
"/usr";
"/usr/local";
"/usr/pkg";
"/opt";
"/opt/local";
"/sw";
"/mingw";
]
let path_separator =
if Sys.win32 then
';'
else
':'
let paths_from_environment_variable variable =
match Sys.getenv variable with
| exception Not_found ->
[]
| paths ->
Configurator.Flags.extract_words paths ~is_word_char:((<>) path_separator)
|> List.map Filename.dirname
let search_paths =
lazy begin
paths_from_environment_variable "C_INCLUDE_PATH" @
paths_from_environment_variable "LIBRARY_PATH" @
default_search_paths
end
let default argument fallback =
match argument with
| Some value -> value
| None -> fallback
let detect ?env_var ?package ?header context ~library =
let env_var = default env_var ("LIB" ^ uppercase library) in
let package = default package ("lib" ^ library) in
let header = default header (library ^ ".h") in
let flags_from_env_var =
let c_flags_var = env_var ^ "_CFLAGS" in
let link_flags_var = env_var ^ "_LIBS" in
match Sys.getenv c_flags_var, Sys.getenv link_flags_var with
| exception Not_found ->
None
| "", "" ->
None
| values ->
Some values
in
match flags_from_env_var with
| Some (c_flags', link_flags') ->
extend (split c_flags') (split link_flags')
| None ->
let flags_from_pkg_config =
match Configurator.Pkg_config.get context with
| None ->
None
| Some pkg_config ->
Configurator.Pkg_config.query pkg_config ~package
in
match flags_from_pkg_config with
| Some flags ->
extend flags.cflags flags.libs
| None ->
try
let path =
List.find
(fun path -> Sys.file_exists (path // "include" // header))
(Lazy.force search_paths)
in
extend
["-I" ^ (path // "include")]
["-L" ^ (path // "lib"); "-l" ^ library]
with Not_found ->
()
let ws2_32_lib context =
if Configurator.ocaml_config_var_exn context "os_type" = "Win32" then
let unicode = ["-DUNICODE"; "-D_UNICODE"] in
if Configurator.ocaml_config_var_exn context "ccomp_type" = "msvc" then
extend unicode ["ws2_32.lib"]
else
extend unicode ["-lws2_32"]
let c_flags () =
!c_flags
let link_flags () =
!link_flags
end
module Output :
sig
type t = {
name : string;
found : bool;
}
val write_c_header : ?extra:string list -> Configurator.t -> t list -> unit
val write_ml_file : ?extra:t list -> t list -> unit
val write_flags_files : unit -> unit
end =
struct
type t = {
name : string;
found : bool;
}
module C_define = Configurator.C_define
let c_header = "lwt_features.h"
let ml_file = "lwt_features.ml"
let c_flags_file = "unix_c_flags.sexp"
let link_flags_file = "unix_c_library_flags.sexp"
let write_c_header ?(extra = []) context macros =
macros
|> List.filter (fun {found; _} -> found)
|> List.map (fun {name; _} -> name, C_define.Value.Switch true)
|> (@) (List.map (fun s -> s, C_define.Value.Switch true) extra)
|> C_define.gen_header_file context ~fname:c_header
let write_ml_file ?(extra = []) macros =
macros
|> List.map (fun {name; found} -> Printf.sprintf "let _%s = %b" name found)
|> (@) (List.map
(fun {name; found} -> Printf.sprintf "let %s = %b" name found) extra)
|> Configurator.Flags.write_lines ml_file
let write_flags_files () =
Configurator.Flags.write_sexp
c_flags_file (C_library_flags.c_flags ());
Configurator.Flags.write_sexp
link_flags_file (C_library_flags.link_flags ());
end
module Features :
sig
val detect : Configurator.t -> Output.t list
end =
struct
type t = {
pretty_name : string;
macro_name : string;
detect : Configurator.t -> bool option;
}
let features = ref []
let feature the_feature =
features := !features @ [the_feature]
let verbose =
Printf.ksprintf (fun s ->
if !Arguments.verbose then
print_string s)
let dots feature to_column =
String.make (to_column - String.length feature.pretty_name) '.'
let right_column = 40
let detect context =
!features
|> List.map begin fun feature ->
verbose "%s " feature.pretty_name;
match feature.detect context with
| None ->
verbose "%s skipped\n" (dots feature right_column);
Output.{name = feature.macro_name; found = false}
| Some found ->
begin
if found then
verbose "%s available\n" (dots feature (right_column - 2))
else
verbose "%s unavailable\n" (dots feature (right_column - 4))
end;
Output.{name = feature.macro_name; found}
end
let compiles ?(werror = false) ?(link_flags = []) context code =
let c_flags = C_library_flags.c_flags () in
let c_flags =
if werror then
"-Werror"::c_flags
else
c_flags
in
let link_flags = link_flags @ (C_library_flags.link_flags ()) in
Configurator.c_test context ~c_flags ~link_flags code
|> fun result -> Some result
let skip_if_windows context k =
match Configurator.ocaml_config_var_exn context "os_type" with
| "Win32" -> None
| _ -> k ()
let skip_if_android _context k =
match !Arguments.android_target with
| Some true -> None
| _ -> k ()
let () = feature {
pretty_name = "libev";
macro_name = "HAVE_LIBEV";
detect = fun context ->
let detect_esy_wants_libev () =
match Sys.getenv "cur__target_dir" with
| exception Not_found -> None
| _ ->
match Sys.getenv "LIBEV_CFLAGS", Sys.getenv "LIBEV_LIBS" with
| exception Not_found -> Some false
| "", "" -> Some false
| _ -> Some true
in
let should_look_for_libev =
match !Arguments.use_libev with
| Some argument ->
argument
| None ->
match detect_esy_wants_libev () with
| Some result ->
result
| None ->
(* we're not under esy *)
let os = Configurator.ocaml_config_var_exn context "os_type" in
os <> "Win32" && !Arguments.android_target <> Some true
in
if not should_look_for_libev then
None
else begin
let code = {|
#include <ev.h>
int main()
{
ev_default_loop(0);
return 0;
}
|}
in
match compiles context code ~link_flags:["-lev"] with
| Some true ->
C_library_flags.add_link_flags ["-lev"];
Some true
| _ ->
C_library_flags.detect context ~library:"ev";
compiles context code
end
}
let () = feature {
pretty_name = "pthread";
macro_name = "HAVE_PTHREAD";
detect = fun context ->
if !Arguments.use_pthread = Some false then
None
else begin
skip_if_windows context @@ fun () ->
let code = {|
#include <pthread.h>
int main()
{
pthread_create(0, 0, 0, 0);
return 0;
}
|}
in
(* On some platforms, pthread is included in the standard library, but
linking with -lpthread fails. So, try to link the test code without
any flags first.
If that fails and we are not targeting Android, try to link with
-lpthread. If *that* fails, search for libpthread in the filesystem.
When targeting Android, compiling without -lpthread is the only way
to link with pthread, and we don't to search for libpthread, because
if we find it, it is likely the host's libpthread. *)
match compiles context code with
| Some true -> Some true
| no ->
if !Arguments.android_target = Some true then
no
else begin
match compiles context code ~link_flags:["-lpthread"] with
| Some true ->
C_library_flags.add_link_flags ["-lpthread"];
Some true
| _ ->
C_library_flags.detect context ~library:"pthread";
compiles context code
end
end
}
let () = feature {
pretty_name = "eventfd";
macro_name = "HAVE_EVENTFD";
detect = fun context ->
skip_if_windows context @@ fun () ->
compiles context {|
#include <sys/eventfd.h>
int main()
{
eventfd(0, 0);
return 0;
}
|}
}
let () = feature {
pretty_name = "fd passing";
macro_name = "HAVE_FD_PASSING";
detect = fun context ->
skip_if_windows context @@ fun () ->
compiles context {|
#include <sys/types.h>
#include <sys/socket.h>
int main()
{
struct msghdr msg;
msg.msg_controllen = 0;
msg.msg_control = 0;
return 0;
}
|}
}
let () = feature {
pretty_name = "sched_getcpu";
macro_name = "HAVE_GETCPU";
detect = fun context ->
skip_if_windows context @@ fun () ->
skip_if_android context @@ fun () ->
compiles context {|
#define _GNU_SOURCE
#include <sched.h>
int main()
{
sched_getcpu();
return 0;
}
|}
}
let () = feature {
pretty_name = "affinity getting/setting";
macro_name = "HAVE_AFFINITY";
detect = fun context ->
skip_if_windows context @@ fun () ->
skip_if_android context @@ fun () ->
compiles context {|
#define _GNU_SOURCE
#include <sched.h>
int main()
{
sched_getaffinity(0, 0, 0);
return 0;
}
|}
}
let get_credentials struct_name = {|
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/socket.h>
int main()
{
struct |} ^ struct_name ^ {| cred;
socklen_t cred_len = sizeof(cred);
getsockopt(0, SOL_SOCKET, SO_PEERCRED, &cred, &cred_len);
return 0;
}
|}
let () = feature {
pretty_name = "credentials getting (Linux)";
macro_name = "HAVE_GET_CREDENTIALS_LINUX";
detect = fun context ->
skip_if_windows context @@ fun () ->
compiles context (get_credentials "ucred")
}
let () = feature {
pretty_name = "credentials getting (NetBSD)";
macro_name = "HAVE_GET_CREDENTIALS_NETBSD";
detect = fun context ->
skip_if_windows context @@ fun () ->
compiles context (get_credentials "sockcred")
}
let () = feature {
pretty_name = "credentials getting (OpenBSD)";
macro_name = "HAVE_GET_CREDENTIALS_OPENBSD";
detect = fun context ->
skip_if_windows context @@ fun () ->
compiles context (get_credentials "sockpeercred")
}
let () = feature {
pretty_name = "credentials getting (FreeBSD)";
macro_name = "HAVE_GET_CREDENTIALS_FREEBSD";
detect = fun context ->
skip_if_windows context @@ fun () ->
compiles context (get_credentials "cmsgcred")
}
let () = feature {
pretty_name = "getpeereid";
macro_name = "HAVE_GETPEEREID";
detect = fun context ->
skip_if_windows context @@ fun () ->
compiles context {|
#include <sys/types.h>
#include <unistd.h>
int main()
{
uid_t euid;
gid_t egid;
getpeereid(0, &euid, &egid);
return 0;
}
|}
}
let () = feature {
pretty_name = "fdatasync";
macro_name = "HAVE_FDATASYNC";
detect = fun context ->
skip_if_windows context @@ fun () ->
compiles context {|
#include <unistd.h>
int main()
{
int (*fdatasyncp)(int) = fdatasync;
fdatasyncp(0);
return 0;
}
|}
}
let () = feature {
pretty_name = "netdb_reentrant";
macro_name = "HAVE_NETDB_REENTRANT";
detect = fun context ->
skip_if_windows context @@ fun () ->
skip_if_android context @@ fun () ->
compiles context {|
#define _POSIX_PTHREAD_SEMANTICS
#include <netdb.h>
#include <stddef.h>
int main()
{
struct hostent *he;
struct servent *se;
he =
gethostbyname_r(
(const char*)NULL,
(struct hostent*)NULL,
(char*)NULL,
(int)0,
(struct hostent**)NULL,
(int*)NULL);
he =
gethostbyaddr_r(
(const char*)NULL,
(int)0,
(int)0,
(struct hostent*)NULL,
(char*)NULL,
(int)0,
(struct hostent**)NULL,
(int*)NULL);
se =
getservbyname_r(
(const char*)NULL,
(const char*)NULL,
(struct servent*)NULL,
(char*)NULL,
(int)0,
(struct servent**)NULL);
se =
getservbyport_r(
(int)0,
(const char*)NULL,
(struct servent*)NULL,
(char*)NULL,
(int)0,
(struct servent**)NULL);
pr =
getprotoent_r(
(struct protoent*)NULL,
(char*)NULL,
(int)0,
(struct protoent**)NULL);
pr =
getprotobyname_r(
(const char*)NULL,
(struct protoent*)NULL,
(char*)NULL,
(int)0,
(struct protoent**)NULL);
pr =
getprotobynumber_r(
(int)0,
(struct protoent*)NULL,
(char*)NULL,
(int)0,
(struct protoent**)NULL);
return 0;
}
|}
}
let () = feature {
pretty_name = "reentrant gethost*";
macro_name = "HAVE_REENTRANT_HOSTENT";
detect = fun context ->
skip_if_windows context @@ fun () ->
compiles context {|
#define _GNU_SOURCE
#include <stddef.h>
#include <caml/config.h>
/* Helper functions for not re-entrant functions */
#if !defined(HAS_GETHOSTBYADDR_R) || \
(HAS_GETHOSTBYADDR_R != 7 && HAS_GETHOSTBYADDR_R != 8)
#define NON_R_GETHOSTBYADDR 1
#endif
#if !defined(HAS_GETHOSTBYNAME_R) || \
(HAS_GETHOSTBYNAME_R != 5 && HAS_GETHOSTBYNAME_R != 6)
#define NON_R_GETHOSTBYNAME 1
#endif
int main()
{
#if defined(NON_R_GETHOSTBYNAME) || defined(NON_R_GETHOSTBYNAME)
#error "not available"
#else
return 0;
#endif
}
|}
}
let nanosecond_stat projection = {|
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
struct stat *buf;
double a, m, c;
a = (double)buf->st_a|} ^ projection ^ {|;
m = (double)buf->st_m|} ^ projection ^ {|;
c = (double)buf->st_c|} ^ projection ^ {|;
return 0;
}
|}
let () = feature {
pretty_name = "st_mtim.tv_nsec";
macro_name = "HAVE_ST_MTIM_TV_NSEC";
detect = fun context ->
compiles context (nanosecond_stat "tim.tv_nsec")
}
let () = feature {
pretty_name = "st_mtimespec.tv_nsec";
macro_name = "HAVE_ST_MTIMESPEC_TV_NSEC";
detect = fun context ->
compiles context (nanosecond_stat "timespec.tv_nsec")
}
let () = feature {
pretty_name = "st_mtimensec";
macro_name = "HAVE_ST_MTIMENSEC";
detect = fun context ->
compiles context (nanosecond_stat "timensec")
}
let () = feature {
pretty_name = "BSD mincore";
macro_name = "HAVE_BSD_MINCORE";
detect = fun context ->
skip_if_windows context @@ fun () ->
compiles ~werror:true context {|
#include <unistd.h>
#include <sys/mman.h>
int main()
{
int (*mincore_ptr)(const void*, size_t, char*) = mincore;
return (int)(mincore_ptr == NULL);
}
|}
}
let () = feature {
pretty_name = "accept4";
macro_name = "HAVE_ACCEPT4";
detect = fun context ->
skip_if_windows context @@ fun () ->
compiles context {|
#define _GNU_SOURCE
#include <sys/socket.h>
#include <stddef.h>
int main()
{
accept4(0, NULL, 0, 0);
return 0;
}
|}
}
end
let () =
begin match List.partition ((=) "--save") (Array.to_list Sys.argv) with
| ["--save"], rest ->
Configurator.Flags.write_lines
"src/unix/discover_arguments" [String.concat " " (List.tl rest)];
exit 0
| _ ->
()
end;
Configurator.main ~args:Arguments.args ~name:"lwt" begin fun context ->
(* Parse arguments from additional sources. *)
Arguments.parse_environment_variable ();
Arguments.parse_arguments_file ();
(* Detect features. *)
let macros = Features.detect context in
(* Link with ws2_32.lib on Windows. *)
C_library_flags.ws2_32_lib context;
(* Write lwt_features.h. *)
let extra =
match Configurator.ocaml_config_var_exn context "os_type" with
| "Win32" -> ["LWT_ON_WINDOWS"]
| _ -> []
in
Output.write_c_header ~extra context macros;
(* Write lwt_features.ml. *)
let libev_default =
match !Arguments.libev_default with
| Some argument ->
argument
| None ->
true
in
Output.write_ml_file
~extra:[
{
name = "android";
found = !Arguments.android_target = Some true;
};
{
name = "libev_default";
found = libev_default;
};
] macros;
(* Write unix_c_flags.sexp and unix_c_library_flags.sexp. *)
Output.write_flags_files ()
end
| (* This file is part of Lwt, released under the MIT license. See LICENSE.md for
details, or visit https://github.com/ocsigen/lwt/blob/master/LICENSE.md. *) |
plist.mli | (** A property list (“plist” for short) is a list of paired elements. Each of the pairs
associates a property name (usually a symbol) with a property or value.
- [(Info-goto-node "(elisp)Property Lists")] *)
open! Core
open! Import
type t [@@deriving sexp_of]
(** [(describe-function 'plist-get)]
[(Info-goto-node "(elisp)Plist Access")] *)
val get : t -> Symbol.t -> Value.t option
(** [(describe-function 'plist-put)]
[(Info-goto-node "(elisp)Plist Access")] *)
val set : t -> Symbol.t -> Value.t -> unit
(** [(describe-function 'symbol-plist)]
[(Info-goto-node "(elisp)Symbol Plists")] *)
val of_symbol : Symbol.t -> t
| (** A property list (“plist” for short) is a list of paired elements. Each of the pairs
associates a property name (usually a symbol) with a property or value.
- [(Info-goto-node "(elisp)Property Lists")] *) |
dune |
(library
(name foo)
(modules ())
(c_names foo))
(library
(name bar)
(modules ())
(cxx_names foo))
| |
gluQuadric.mli | (* $Id: gluQuadric.mli,v 1.2 1999-11-15 14:32:14 garrigue Exp $ *)
type t
val create : unit -> t
(* If you omit the quadric, a new one will be created *)
val cylinder :
base:float -> top:float ->
height:float -> slices:int -> stacks:int -> ?quad:t -> unit -> unit
val disk :
inner:float -> outer:float ->
slices:int -> loops:int -> ?quad:t -> unit -> unit
val partial_disk :
inner:float ->
outer:float ->
slices:int ->
loops:int -> start:float -> sweep:float -> ?quad:t -> unit -> unit
val sphere :
radius:float -> slices:int -> stacks:int -> ?quad:t -> unit -> unit
val draw_style : t -> [`fill|`line|`point|`silhouette] -> unit
val normals : t -> [`flat|`none|`smooth] -> unit
val orientation : t -> [`inside|`outside] -> unit
val texture : t -> bool -> unit
| (* $Id: gluQuadric.mli,v 1.2 1999-11-15 14:32:14 garrigue Exp $ *)
|
dune |
(library
(name forutop_impl_2)
(implements forutop))
| |
batcher.ml | open Protocol
open Alpha_context
open Batcher_worker_types
module Message_queue = Hash_queue.Make (L2_message.Hash) (L2_message)
module L2_batched_message = struct
type t = {content : string; l1_hash : L1_operation.hash}
end
module Batched_messages = Hash_queue.Make (L2_message.Hash) (L2_batched_message)
module type S = sig
type status = Pending_batch | Batched of L1_operation.hash
val init :
Configuration.batcher ->
signer:public_key_hash ->
_ Node_context.t ->
unit tzresult Lwt.t
val active : unit -> bool
val find_message : L2_message.hash -> L2_message.t option tzresult
val get_queue : unit -> (L2_message.hash * L2_message.t) list tzresult
val register_messages : string list -> L2_message.hash list tzresult Lwt.t
val batch : unit -> unit tzresult Lwt.t
val new_head : Layer1.head -> unit tzresult Lwt.t
val shutdown : unit -> unit Lwt.t
val message_status : L2_message.hash -> (status * string) option tzresult
end
module Make (Simulation : Simulation.S) : S = struct
module PVM = Simulation.PVM
type status = Pending_batch | Batched of L1_operation.hash
type state = {
node_ctxt : Node_context.ro;
signer : Tezos_crypto.Signature.public_key_hash;
conf : Configuration.batcher;
messages : Message_queue.t;
batched : Batched_messages.t;
mutable simulation_ctxt : Simulation.t option;
}
let message_size s =
(* Encoded as length of s on 4 bytes + s *)
4 + String.length s
let inject_batch state (l2_messages : L2_message.t list) =
let open Lwt_result_syntax in
let messages = List.map L2_message.content l2_messages in
let operation = Sc_rollup_add_messages {messages} in
let+ l1_hash =
Injector.add_pending_operation ~source:state.signer operation
in
List.iter
(fun msg ->
let content = L2_message.content msg in
let hash = L2_message.hash msg in
Batched_messages.replace state.batched hash {content; l1_hash})
l2_messages
let inject_batches state = List.iter_es (inject_batch state)
let get_batches state ~only_full =
let ( current_rev_batch,
current_batch_size,
current_batch_elements,
full_batches ) =
Message_queue.fold
(fun msg_hash
message
( current_rev_batch,
current_batch_size,
current_batch_elements,
full_batches ) ->
let size = message_size (L2_message.content message) in
let new_batch_size = current_batch_size + size in
let new_batch_elements = current_batch_elements + 1 in
if
new_batch_size <= state.conf.max_batch_size
&& new_batch_elements <= state.conf.max_batch_elements
then
(* We can add the message to the current batch because we are still
within the bounds. *)
( (msg_hash, message) :: current_rev_batch,
new_batch_size,
new_batch_elements,
full_batches )
else
(* The batch augmented with the message would be too big but it is
below the limit without it. We finalize the current batch and
create a new one for the message. NOTE: Messages in the queue are
always < [state.conf.max_batch_size] because {!on_register} only
accepts those. *)
let batch = List.rev current_rev_batch in
([(msg_hash, message)], size, 1, batch :: full_batches))
state.messages
([], 0, 0, [])
in
let batches =
if
(not only_full)
|| current_batch_size >= state.conf.min_batch_size
&& current_batch_elements >= state.conf.min_batch_elements
then
(* We have enough to make a batch with the last non-full batch. *)
List.rev current_rev_batch :: full_batches
else full_batches
in
List.fold_left
(fun (batches, to_remove) -> function
| [] -> (batches, to_remove)
| batch ->
let msg_hashes, batch = List.split batch in
let to_remove = List.rev_append msg_hashes to_remove in
(batch :: batches, to_remove))
([], [])
batches
let produce_batches state ~only_full =
let open Lwt_result_syntax in
let batches, to_remove = get_batches state ~only_full in
match batches with
| [] -> return_unit
| _ ->
let* () = inject_batches state batches in
let*! () =
Batcher_events.(emit batched)
(List.length batches, List.length to_remove)
in
List.iter
(fun tr_hash -> Message_queue.remove state.messages tr_hash)
to_remove ;
return_unit
let on_batch state = produce_batches state ~only_full:false
let simulate node_ctxt simulation_ctxt (messages : L2_message.t list) =
let open Lwt_result_syntax in
let ext_messages =
List.map
(fun m -> Sc_rollup.Inbox_message.External (L2_message.content m))
messages
in
let+ simulation_ctxt, _ticks =
Simulation.simulate_messages node_ctxt simulation_ctxt ext_messages
in
simulation_ctxt
let on_register state (messages : string list) =
let open Lwt_result_syntax in
let max_size_msg =
min
(Protocol.Constants_repr.sc_rollup_message_size_limit
+ 4 (* We add 4 because [message_size] adds 4. *))
state.conf.max_batch_size
in
let*? messages =
List.mapi_e
(fun i message ->
if message_size message > max_size_msg then
error_with "Message %d is too large (max size is %d)" i max_size_msg
else Ok (L2_message.make message))
messages
in
let* () =
if not state.conf.simulate then return_unit
else
match state.simulation_ctxt with
| None -> failwith "Simulation context of batcher not initialized"
| Some simulation_ctxt ->
let+ simulation_ctxt =
simulate state.node_ctxt simulation_ctxt messages
in
state.simulation_ctxt <- Some simulation_ctxt
in
let*! () = Batcher_events.(emit queue) (List.length messages) in
let hashes =
List.map
(fun message ->
let msg_hash = L2_message.hash message in
Message_queue.replace state.messages msg_hash message ;
msg_hash)
messages
in
let+ () = produce_batches state ~only_full:true in
hashes
let on_new_head state head =
let open Lwt_result_syntax in
let* simulation_ctxt =
Simulation.start_simulation ~reveal_map:None state.node_ctxt head
in
(* TODO: https://gitlab.com/tezos/tezos/-/issues/4224
Replay with simulation may be too expensive *)
let+ simulation_ctxt, failing =
if not state.conf.simulate then return (simulation_ctxt, [])
else
(* Re-simulate one by one *)
Message_queue.fold_es
(fun msg_hash msg (simulation_ctxt, failing) ->
let*! result = simulate state.node_ctxt simulation_ctxt [msg] in
match result with
| Ok simulation_ctxt -> return (simulation_ctxt, failing)
| Error _ -> return (simulation_ctxt, msg_hash :: failing))
state.messages
(simulation_ctxt, [])
in
state.simulation_ctxt <- Some simulation_ctxt ;
(* Forget failing messages *)
List.iter (Message_queue.remove state.messages) failing
let init_batcher_state node_ctxt ~signer conf =
let open Lwt_syntax in
return
{
node_ctxt;
signer;
conf;
messages = Message_queue.create 100_000 (* ~ 400MB *);
batched = Batched_messages.create 100_000 (* ~ 400MB *);
simulation_ctxt = None;
}
module Types = struct
type nonrec state = state
type parameters = {
node_ctxt : Node_context.ro;
signer : Tezos_crypto.Signature.public_key_hash;
conf : Configuration.batcher;
}
end
module Worker = Worker.MakeSingle (Name) (Request) (Types)
type worker = Worker.infinite Worker.queue Worker.t
module Handlers = struct
type self = worker
let on_request :
type r request_error.
worker ->
(r, request_error) Request.t ->
(r, request_error) result Lwt.t =
fun w request ->
let state = Worker.state w in
match request with
| Request.Register messages ->
protect @@ fun () -> on_register state messages
| Request.Batch -> protect @@ fun () -> on_batch state
| Request.New_head head -> protect @@ fun () -> on_new_head state head
type launch_error = error trace
let on_launch _w () Types.{node_ctxt; signer; conf} =
let open Lwt_result_syntax in
let*! state = init_batcher_state node_ctxt ~signer conf in
return state
let on_error (type a b) _w st (r : (a, b) Request.t) (errs : b) :
unit tzresult Lwt.t =
let open Lwt_result_syntax in
let request_view = Request.view r in
let emit_and_return_errors errs =
let*! () =
Batcher_events.(emit Worker.request_failed) (request_view, st, errs)
in
return_unit
in
match r with
| Request.Register _ -> emit_and_return_errors errs
| Request.Batch -> emit_and_return_errors errs
| Request.New_head _ -> emit_and_return_errors errs
let on_completion _w r _ st =
match Request.view r with
| Request.View (Register _ | New_head _) ->
Batcher_events.(emit Worker.request_completed_debug)
(Request.view r, st)
| View Batch ->
Batcher_events.(emit Worker.request_completed_notice)
(Request.view r, st)
let on_no_request _ = Lwt.return_unit
let on_close _w = Lwt.return_unit
end
let table = Worker.create_table Queue
let worker_promise, worker_waker = Lwt.task ()
let init conf ~signer node_ctxt =
let open Lwt_result_syntax in
let node_ctxt = Node_context.readonly node_ctxt in
let+ worker =
Worker.launch table () {node_ctxt; signer; conf} (module Handlers)
in
Lwt.wakeup worker_waker worker
(* This is a batcher worker for a single scoru *)
let worker =
lazy
(match Lwt.state worker_promise with
| Lwt.Return worker -> ok worker
| Lwt.Fail _ | Lwt.Sleep -> error Sc_rollup_node_errors.No_batcher)
let active () =
match Lwt.state worker_promise with
| Lwt.Return _ -> true
| Lwt.Fail _ | Lwt.Sleep -> false
let find_message hash =
let open Result_syntax in
let+ w = Lazy.force worker in
let state = Worker.state w in
Message_queue.find_opt state.messages hash
let get_queue () =
let open Result_syntax in
let+ w = Lazy.force worker in
let state = Worker.state w in
Message_queue.bindings state.messages
let handle_request_error rq =
let open Lwt_syntax in
let* rq = rq in
match rq with
| Ok res -> return_ok res
| Error (Worker.Request_error errs) -> Lwt.return_error errs
| Error (Closed None) -> Lwt.return_error [Worker_types.Terminated]
| Error (Closed (Some errs)) -> Lwt.return_error errs
| Error (Any exn) -> Lwt.return_error [Exn exn]
let register_messages messages =
let open Lwt_result_syntax in
let*? w = Lazy.force worker in
Worker.Queue.push_request_and_wait w (Request.Register messages)
|> handle_request_error
let batch () =
let w = Lazy.force worker in
match w with
| Error _ ->
(* There is no batcher, nothing to do *)
return_unit
| Ok w ->
Worker.Queue.push_request_and_wait w Request.Batch
|> handle_request_error
let new_head b =
let open Lwt_result_syntax in
let w = Lazy.force worker in
match w with
| Error _ ->
(* There is no batcher, nothing to do *)
return_unit
| Ok w ->
let*! (_pushed : bool) =
Worker.Queue.push_request w (Request.New_head b)
in
return_unit
let shutdown () =
let w = Lazy.force worker in
match w with
| Error _ ->
(* There is no batcher, nothing to do *)
Lwt.return_unit
| Ok w -> Worker.shutdown w
let message_status state msg_hash =
match Message_queue.find_opt state.messages msg_hash with
| Some msg -> Some (Pending_batch, L2_message.content msg)
| None -> (
match Batched_messages.find_opt state.batched msg_hash with
| Some {content; l1_hash} -> Some (Batched l1_hash, content)
| None -> None)
let message_status msg_hash =
let open Result_syntax in
let+ w = Lazy.force worker in
let state = Worker.state w in
message_status state msg_hash
end
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2022 Nomadic Labs, <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
Mc2_propositional.mli |
(** {1 Propositional Literal} *)
open Mc2_core
module F : Tseitin.S with type atom := atom
(** Formulas *)
val k_cnf : (?simplify:bool -> F.t -> atom list list) Service.Key.t
(** Service for computing CNF *)
val k_fresh : (unit -> atom) Service.Key.t
(** Service for making fresh terms *)
val plugin : Plugin.Factory.t
(** Plugin providing boolean terms and the {!cnf} service *)
| |
describeLoadBalancers.mli |
open Types
type input = DescribeAccessPointsInput.t
type output = DescribeAccessPointsOutput.t
type error = Errors_internal.t
include
Aws.Call with type input := input and type output := output and type
error := error | |
dune |
(library (name sexp_macro_test)
(libraries core expect_test_helpers_core core_unix.filename_unix sexp_macro)
(preprocess (pps ppx_jane))) | |
roundtrips.ml | let test_rt_opt name testable enc dec input =
let roundtripped = dec (enc input) in
Alcotest.check (Alcotest.option testable) name (Some input) roundtripped
let test_decode_opt_safe name testable dec encoded =
match dec encoded with
| Some _ | None -> ()
| exception exc ->
Alcotest.failf
"%s failed for %a: exception whilst decoding: %s"
name
(Alcotest.pp testable)
encoded
(Printexc.to_string exc)
let test_decode_opt_fail name testable dec encoded =
try
let decoded = dec encoded in
Alcotest.check (Alcotest.option testable) name None decoded
with exc ->
Alcotest.failf
"%s failed: exception whilst decoding: %s"
name
(Printexc.to_string exc)
| (*****************************************************************************)
(* *)
(* 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. *)
(* *)
(*****************************************************************************)
|
add_fmpz.c | /*=============================================================================
This file is part of Antic.
Antic 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/>.
=============================================================================*/
/******************************************************************************
Copyright (C) 2015 William Hart
******************************************************************************/
#include "nf_elem.h"
void nf_elem_add_fmpz(nf_elem_t a, const nf_elem_t b, const fmpz_t c, const nf_t nf)
{
if (nf->flag & NF_LINEAR)
{
fmpz * den = LNF_ELEM_DENREF(a);
fmpz * num = LNF_ELEM_NUMREF(a);
const fmpz * const den2 = LNF_ELEM_DENREF(b);
const fmpz * const num2 = LNF_ELEM_NUMREF(b);
_fmpq_add_fmpz(num, den, num2, den2, c);
}
else if (nf->flag & NF_QUADRATIC)
{
fmpz * den = QNF_ELEM_DENREF(a);
fmpz * num = QNF_ELEM_NUMREF(a);
slong len = 2;
nf_elem_set(a, b, nf);
while (len != 0 && fmpz_is_zero(num + len - 1))
len--;
fmpz_addmul(num, den, c);
_fmpq_poly_canonicalise(num, den, len);
} else
{
fmpq_poly_add_fmpz(NF_ELEM(a), NF_ELEM(b), c);
}
}
| /*=============================================================================
This file is part of Antic.
Antic 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/>.
=============================================================================*/ |
test_lru_cache.ml | module IntTable = Hashtbl.Make (struct
type t = int
let equal = Compare.Int.equal
let hash x = x
end)
module Int_cache = Lru_cache.Make (IntTable)
let test_bad_create _ =
Alcotest.check_raises
"below capacity"
(Invalid_argument "Lru_cache.create: negative or null capacity")
(fun () ->
ignore (Int_cache.create ~capacity:(-1)) ;
Alcotest.fail "Creation with negative capacity")
let test_singleton _ =
let cache = Int_cache.create ~capacity:1 in
Int_cache.check_consistency cache ;
Int_cache.push cache 5 5 ;
assert (Int_cache.size cache = 1) ;
assert (Int_cache.is_cached cache 5) ;
Int_cache.check_consistency cache ;
Int_cache.push cache 5 5 ;
assert (Int_cache.is_cached cache 5) ;
Int_cache.check_consistency cache ;
Int_cache.push cache 4 4 ;
assert (Int_cache.is_cached cache 4) ;
assert (not (Int_cache.is_cached cache 5)) ;
Int_cache.check_consistency cache ;
Int_cache.push cache 4 4 ;
Int_cache.check_consistency cache ;
Int_cache.push cache 6 6 ;
Int_cache.check_consistency cache ;
assert (Int_cache.is_cached cache 6) ;
assert (not (Int_cache.is_cached cache 4)) ;
assert (not (Int_cache.is_cached cache 5)) ;
Int_cache.remove cache 6 ;
Int_cache.check_consistency cache ;
assert (Int_cache.size cache = 0) ;
assert (not (Int_cache.is_cached cache 6)) ;
assert (Int_cache.bindings cache = [])
open Utils.Infix
let test_casual_cache _ =
let cache = Int_cache.create ~capacity:5 in
Int_cache.check_consistency cache ;
List.iter (fun i -> Int_cache.push cache i i) (1 -- 5) ;
Int_cache.check_consistency cache ;
assert (Int_cache.size cache = 5) ;
List.iter (fun i -> assert (Int_cache.is_cached cache i)) (1 -- 5) ;
List.iter (fun i -> Int_cache.push cache i i) (1 -- 5) ;
Int_cache.check_consistency cache ;
assert (Int_cache.size cache = 5) ;
List.iter (fun i -> assert (Int_cache.is_cached cache i)) (1 -- 5) ;
List.iter (fun i -> Int_cache.push cache i i) (6 -- 9) ;
Int_cache.check_consistency cache ;
assert (Int_cache.size cache = 5) ;
List.iter (fun i -> assert (not (Int_cache.is_cached cache i))) (1 -- 4) ;
List.iter (fun i -> assert (Int_cache.is_cached cache i)) (5 -- 9) ;
Int_cache.remove cache 5 ;
assert (Int_cache.size cache = 4) ;
Int_cache.check_consistency cache ;
assert (not (Int_cache.is_cached cache 5)) ;
let expected_elements = List.rev (List.map (fun i -> (i, i)) (6 -- 9)) in
List.iter (fun i -> assert (Int_cache.is_cached cache i)) (6 -- 9) ;
assert (Int_cache.bindings cache = expected_elements) ;
List.iter (fun i -> Int_cache.remove cache i) (6 -- 9) ;
Int_cache.check_consistency cache ;
assert (Int_cache.size cache = 0)
let test_get_cache _ =
let cache = Int_cache.create ~capacity:10 in
let fetch x = x in
let fetch_fail _ = Alcotest.fail "unexpected fetch" in
List.iter
(fun i ->
(* acts as push *)
let x = Int_cache.get cache fetch i in
assert (i = x))
(1 -- 5) ;
Int_cache.check_consistency cache ;
assert (Int_cache.size cache = 5) ;
List.iter (fun i -> assert (Int_cache.is_cached cache i)) (1 -- 5) ;
List.iter
(fun i ->
let x = Int_cache.get cache fetch_fail i in
assert (i = x) ;
assert (Int_cache.is_cached cache i))
(1 -- 5) ;
Int_cache.check_consistency cache ;
assert (Int_cache.size cache = 5) ;
let expected_elements = List.rev (List.map (fun i -> (i, i)) (1 -- 5)) in
assert (Int_cache.bindings cache = expected_elements)
let tests =
[ ("bad create", `Quick, test_bad_create);
("singleton cache", `Quick, test_singleton);
("casual cache", `Quick, test_casual_cache);
("get cache", `Quick, test_get_cache) ]
let () = Alcotest.run "stdlib" [("lru_cache", 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. *)
(* *)
(*****************************************************************************)
|
dune | (copy_files ../../certificates/*.crt)
(copy_files ../../certificates/*.key)
(copy_files ../../certificates/*.pem)
(mdx
(package tls-eio)
(deps
server.pem
server.key
server-ec.pem
server-ec.key
(package tls-eio)
(package mirage-crypto-rng-eio)
(package eio_main)))
; "dune runtest" just does a quick run with random inputs.
;
; To run with afl-fuzz instead (make sure you have a compiler with the afl option on!):
;
; dune runtest
; mkdir input
; echo hi > input/foo
; cp certificates/server.{key,pem} .
; afl-fuzz -m 1000 -i input -o output ./_build/default/eio/tests/fuzz.exe @@
(test
(package tls-eio)
(libraries crowbar tls-eio eio.mock logs logs.fmt)
(deps server.pem server.key)
(name fuzz)
(action (run %{test} --repeat 200)))
| (copy_files ../../certificates/*.crt)
(copy_files ../../certificates/*.key)
(copy_files ../../certificates/*.pem)
(mdx
(package tls-eio)
(deps
server.pem
server.key
server-ec.pem
server-ec.key
(package tls-eio)
(package mirage-crypto-rng-eio)
(package eio_main)))
; "dune runtest" just does a quick run with random inputs.
;
; To run with afl-fuzz instead (make sure you have a compiler with the afl option on!):
;
; dune runtest
; mkdir input
; echo hi > input/foo
; cp certificates/server.{key,pem} .
; afl-fuzz -m 1000 -i input -o output ./_build/default/eio/tests/fuzz.exe @@
(test
(package tls-eio)
(libraries crowbar tls-eio eio.mock logs logs.fmt)
(deps server.pem server.key)
(name fuzz)
(action (run %{test} --repeat 200)))
|
dune |
(library
(name lib)
(modules :standard \ test))
(executable
(name test)
(libraries lib))
| |
build_system.mli | (** The core of the build system *)
open Import
module Action_builder := Action_builder0
(** Build a file. *)
val build_file : Path.t -> unit Memo.t
(** Build a file and access its contents with [f]. *)
val read_file : Path.t -> f:(Path.t -> 'a) -> 'a Memo.t
(** Return [true] if a file exists or is buildable *)
val file_exists : Path.t -> bool Memo.t
(** Build a set of dependencies and return learned facts about them. *)
val build_deps : Dep.Set.t -> Dep.Facts.t Memo.t
(** [eval_pred glob] returns the list of files in [File_selector.dir glob] that
matches [File_selector.predicate glob]. The list of files includes the list
of file targets. Currently, this function ignores directory targets, which
is a limitation we'd like to remove in future. *)
val eval_pred : File_selector.t -> Path.Set.t Memo.t
(** Same as [eval_pred] with [Predicate.true_] as predicate. *)
val files_of : dir:Path.t -> Path.Set.t Memo.t
(** Like [eval_pred] but also builds the resulting set of files. This function
doesn't have [eval_pred]'s limitation about directory targets and takes them
into account. *)
val build_pred : File_selector.t -> Dep.Fact.Files.t Memo.t
(** Execute an action. The execution is cached. *)
val execute_action :
observing_facts:Dep.Facts.t -> Rule.Anonymous_action.t -> unit Memo.t
(** Execute an action and capture its stdout. The execution is cached. *)
val execute_action_stdout :
observing_facts:Dep.Facts.t -> Rule.Anonymous_action.t -> string Memo.t
type rule_execution_result =
{ deps : Dep.Fact.t Dep.Map.t
; targets : Digest.t Path.Build.Map.t
}
val execute_rule : Rule.t -> rule_execution_result Memo.t
val dep_on_alias_definition :
Rules.Dir_rules.Alias_spec.item -> unit Action_builder.t
(** {2 Running the build system} *)
val run : (unit -> 'a Memo.t) -> ('a, [ `Already_reported ]) Result.t Fiber.t
(** A variant of [run] that raises an [Already_reported] exception on error. *)
val run_exn : (unit -> 'a Memo.t) -> 'a Fiber.t
(** {2 Misc} *)
module Progress : sig
(** Measures for the progress of the build. *)
type t =
{ number_of_rules_discovered : int
; number_of_rules_executed : int
}
(** Initialize with zeros on all measures. *)
val init : t
end
module State : sig
type t =
| Initializing
| Building of Progress.t
| Restarting_current_build
| Build_succeeded__now_waiting_for_changes
| Build_failed__now_waiting_for_changes
val equal : t -> t -> bool
end
val state : State.t Fiber.Svar.t
(** Errors found when building targets. *)
module Error : sig
type t
module Id : sig
type t
module Map : Map.S with type key = t
val compare : t -> t -> Ordering.t
val to_int : t -> int
val to_dyn : t -> Dyn.t
end
module Event : sig
type nonrec t =
| Add of t
| Remove of t
end
module Set : sig
type error := t
type t
(** [one_event_diff ~prev ~next] returns the event that constructs [next]
from [prev] if [next] is in the successive "generation" of [prev] *)
val one_event_diff : prev:t -> next:t -> Event.t option
val equal : t -> t -> bool
val current : t -> error Id.Map.t
val empty : t
end
val create : exn:Exn_with_backtrace.t -> t
val info : t -> User_message.t * User_message.t list * Path.t option
val promotion : t -> Diff_promotion.Annot.t option
val id : t -> Id.t
end
(** The current set of active errors. *)
val errors : Error.Set.t Fiber.Svar.t
| (** The core of the build system *)
|
builtinf_GetPixel.ml |
##ifdef CAMLTK
let pixels units =
let res =
tkEval
[|TkToken"winfo";
TkToken"pixels";
cCAMLtoTKwidget widget_any_table default_toplevel;
cCAMLtoTKunits units|] in
int_of_string res
##else
let pixels units =
let res =
tkEval
[|TkToken"winfo";
TkToken"pixels";
cCAMLtoTKwidget default_toplevel;
cCAMLtoTKunits units|] in
int_of_string res
##endif
| |
dune |
(library
(name compatcmdliner)
(libraries cmdliner))
| |
coercion.mli |
open Term
val coerce : sym
(** Symbol of the function that computes coercions. Coercion rules are added
on that symbol. *)
val apply : term -> term -> term -> term
(** [apply a b t] creates the coercion of term [t] from type [a] to type
[b]. *)
| |
match_exn_caught.ml |
match%nop print_endline "match"; failwith "qjdswflk" with
| None -> print_endline "none"
| Some true -> print_endline "true"
| exception Failure _ -> print_endline "failure"
| Some false -> print_endline "false"
| |
dune |
(library
(name util)
(libraries alcotest resp-server)
(modules util))
(executables
(libraries alcotest resp lwt.unix)
(names test)
(modules test))
(executables
(libraries alcotest util resp-unix)
(names test_unix)
(modules test_unix))
(rule
(alias runtest)
(package resp)
(deps test.exe)
(action
(run ./test.exe)))
(rule
(alias runtest)
(package resp-unix)
(deps test_unix.exe)
(action
(run ./test_unix.exe)))
| |
Unit_regexp_engine.mli | (*
Unit tests for SPcre
*)
val tests : Testutil.test list
| (*
Unit tests for SPcre
*) |
_kvm_timeofday.h |
uint64_t gettimeofday(void);
| /****************************************************************************/
/* 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. */
/****************************************************************************/
#include <stdint.h> |
owl_utils_infer_shape.ml |
open Owl_types
(* This module is for calculating the shape of an ndarray given inputs. *)
(* check if broadcasting is required *)
let require_broadcasting shape_x shape_y =
let shape_a, shape_b = Owl_utils_array.align `Left 1 shape_x shape_y in
(* NOTE: compare content, not physical address *)
shape_a <> shape_b
(* calculate the output shape of [conv2d] given input and kernel and stride *)
let calc_conv2d_output_shape
padding
input_cols
input_rows
kernel_cols
kernel_rows
row_stride
col_stride
=
let input_cols = float_of_int input_cols in
let input_rows = float_of_int input_rows in
let kernel_cols = float_of_int kernel_cols in
let kernel_rows = float_of_int kernel_rows in
let row_stride = float_of_int row_stride in
let col_stride = float_of_int col_stride in
let output_cols =
match padding with
| SAME -> input_cols /. col_stride |> ceil |> int_of_float
| VALID -> (input_cols -. kernel_cols +. 1.) /. col_stride |> ceil |> int_of_float
in
let output_rows =
match padding with
| SAME -> input_rows /. row_stride |> ceil |> int_of_float
| VALID -> (input_rows -. kernel_rows +. 1.) /. row_stride |> ceil |> int_of_float
in
output_cols, output_rows
(* calculate the output shape of [transpose_conv2d] given input and kernel and stride *)
let calc_transpose_conv2d_output_shape
padding
input_cols
input_rows
kernel_cols
kernel_rows
row_stride
col_stride
=
let output_cols =
match padding with
| SAME -> input_cols * col_stride
| VALID -> (input_cols * col_stride) + max (kernel_cols - col_stride) 0
in
let output_rows =
match padding with
| SAME -> input_rows * row_stride
| VALID -> (input_rows * row_stride) + max (kernel_rows - row_stride) 0
in
output_cols, output_rows
(* calculate the padding size along width and height *)
let calc_conv2d_padding
input_cols
input_rows
kernel_cols
kernel_rows
output_cols
output_rows
row_stride
col_stride
=
let pad_along_height =
Stdlib.max (((output_rows - 1) * row_stride) + kernel_rows - input_rows) 0
in
let pad_along_width =
Stdlib.max (((output_cols - 1) * col_stride) + kernel_cols - input_cols) 0
in
let pad_top = pad_along_height / 2 in
let pad_bottom = pad_along_height - pad_top in
let pad_left = pad_along_width / 2 in
let pad_right = pad_along_width - pad_left in
pad_top, pad_left, pad_bottom, pad_right
(* calc_conv1d_output_shape actually calls its 2d version *)
let calc_conv1d_output_shape padding input_cols kernel_cols col_stride =
let input_rows = 1 in
let kernel_rows = 1 in
let row_stride = 1 in
calc_conv2d_output_shape
padding
input_cols
input_rows
kernel_cols
kernel_rows
row_stride
col_stride
|> fst
(* calc_transpose_conv1d_output_shape actually calls its 2d version *)
let calc_transpose_conv1d_output_shape padding input_cols kernel_cols col_stride =
let input_rows = 1 in
let kernel_rows = 1 in
let row_stride = 1 in
calc_transpose_conv2d_output_shape
padding
input_cols
input_rows
kernel_cols
kernel_rows
row_stride
col_stride
|> fst
(* calculate the output shape of [conv3d] given input and kernel and stride *)
let calc_conv3d_output_shape
padding
input_cols
input_rows
input_dpts
kernel_cols
kernel_rows
kernel_dpts
row_stride
col_stride
dpt_stride
=
let input_cols = float_of_int input_cols in
let input_rows = float_of_int input_rows in
let input_dpts = float_of_int input_dpts in
let kernel_cols = float_of_int kernel_cols in
let kernel_rows = float_of_int kernel_rows in
let kernel_dpts = float_of_int kernel_dpts in
let row_stride = float_of_int row_stride in
let col_stride = float_of_int col_stride in
let dpt_stride = float_of_int dpt_stride in
let output_cols =
match padding with
| SAME -> input_cols /. col_stride |> ceil |> int_of_float
| VALID -> (input_cols -. kernel_cols +. 1.) /. col_stride |> ceil |> int_of_float
in
let output_rows =
match padding with
| SAME -> input_rows /. row_stride |> ceil |> int_of_float
| VALID -> (input_rows -. kernel_rows +. 1.) /. row_stride |> ceil |> int_of_float
in
let output_dpts =
match padding with
| SAME -> input_dpts /. dpt_stride |> ceil |> int_of_float
| VALID -> (input_dpts -. kernel_dpts +. 1.) /. dpt_stride |> ceil |> int_of_float
in
output_cols, output_rows, output_dpts
(* calculate the output shape of [transpose_conv3d] given input and kernel and stride *)
let calc_transpose_conv3d_output_shape
padding
input_cols
input_rows
input_dpts
kernel_cols
kernel_rows
kernel_dpts
row_stride
col_stride
dpt_stride
=
let output_cols =
match padding with
| SAME -> input_cols * col_stride
| VALID -> (input_cols * col_stride) + max (kernel_cols - col_stride) 0
in
let output_rows =
match padding with
| SAME -> input_rows * row_stride
| VALID -> (input_rows * row_stride) + max (kernel_rows - row_stride) 0
in
let output_dpts =
match padding with
| SAME -> input_dpts * dpt_stride
| VALID -> (input_dpts * dpt_stride) + max (kernel_dpts - dpt_stride) 0
in
output_cols, output_rows, output_dpts
(* calculate the padding size along width, height, and depth. *)
let calc_conv3d_padding
input_cols
input_rows
input_depth
kernel_cols
kernel_rows
kernel_depth
output_cols
output_rows
output_depth
row_stride
col_stride
depth_stride
=
let pad_along_height =
Stdlib.max (((output_rows - 1) * row_stride) + kernel_rows - input_rows) 0
in
let pad_along_width =
Stdlib.max (((output_cols - 1) * col_stride) + kernel_cols - input_cols) 0
in
let pad_along_depth =
Stdlib.max (((output_depth - 1) * depth_stride) + kernel_depth - input_depth) 0
in
let pad_top = pad_along_height / 2 in
let pad_bottom = pad_along_height - pad_top in
let pad_left = pad_along_width / 2 in
let pad_right = pad_along_width - pad_left in
let pad_shallow = pad_along_depth / 2 in
let pad_deep = pad_along_depth - pad_shallow in
pad_top, pad_left, pad_shallow, pad_bottom, pad_right, pad_deep
(* various functions to calculate output shape, used in computation graph. *)
let broadcast1 s0 s1 =
let sa, sb = Owl_utils_array.align `Left 1 s0 s1 in
Array.iter2
(fun a b ->
Owl_exception.(check (not (a <> 1 && b <> 1 && a <> b)) NOT_BROADCASTABLE))
sa
sb;
(* calculate the output shape *)
Array.map2 max sa sb
let broadcast2 s0 s1 s2 =
let sa, sb, sc = Owl_utils_array.align3 `Left 1 s0 s1 s2 in
let sd = Owl_utils_array.map3 (fun a b c -> max a (max b c)) sa sb sc in
Owl_utils_array.iter4
(fun a b c d ->
Owl_exception.(check (not (a <> 1 && a <> d)) NOT_BROADCASTABLE);
Owl_exception.(check (not (b <> 1 && b <> d)) NOT_BROADCASTABLE);
Owl_exception.(check (not (c <> 1 && c <> d)) NOT_BROADCASTABLE))
sa
sb
sc
sd;
sd
(* no need to align two shapes before passing in. *)
let broadcast1_stride s0 s1 =
let sa, sb = Owl_utils_array.align `Left 1 s0 s1 in
let stride_0 = Owl_utils_ndarray.calc_stride sa in
let stride_1 = Owl_utils_ndarray.calc_stride sb in
Owl_utils_array.iter2i
(fun i d0 d1 ->
if d0 <> d1 then if d0 = 1 then stride_0.(i) <- 0 else stride_1.(i) <- 0)
sa
sb;
stride_0, stride_1
let fold shape axis =
let d = Array.length shape in
let a = Owl_utils_ndarray.adjust_index axis d in
assert (a >= 0 && a < d);
let _shape = Array.copy shape in
_shape.(a) <- 1;
_shape
let tile shape repeats =
assert (Array.exists (( > ) 1) repeats = false);
let s, r = Owl_utils_array.align `Left 1 shape repeats in
Owl_utils_array.map2 (fun a b -> a * b) s r
let repeat shape repeats =
assert (Array.exists (( > ) 1) repeats = false);
assert (Array.length shape = Array.length repeats);
Owl_utils_array.map2 ( * ) shape repeats
let concatenate shape axis =
let d = Array.length shape.(0) in
let axis = Owl_utils_ndarray.adjust_index axis d in
let shapes = Array.(map copy shape) in
let shape0 = Array.copy shapes.(0) in
shape0.(axis) <- 0;
let acc_dim = ref 0 in
Array.iteri
(fun _i shape1 ->
acc_dim := !acc_dim + shape1.(axis);
shape1.(axis) <- 0;
assert (shape0 = shape1))
shapes;
shape0.(axis) <- !acc_dim;
shape0
let split shape axis parts =
let d = Array.length shape in
let a = Owl_utils_ndarray.adjust_index axis d in
let e = Array.fold_left ( + ) 0 parts in
assert (a < d);
assert (e = shape.(a));
Array.map
(fun n ->
let s = Array.copy shape in
s.(a) <- n;
s)
parts
let slice shape slice_spec =
let infer_len orig_len start stop ?step () =
let start = if start < 0 then orig_len + start else start in
let stop = if stop < 0 then orig_len + stop else stop in
let step =
match step with
| Some x -> x
| None -> if start <= stop then 1 else -1
in
assert (
(start <= stop && step > 0 && stop < orig_len)
|| (start > stop && step < 0 && start < orig_len));
let step_abs = abs step in
(abs (stop - start) + step_abs) / step_abs
in
let shape' =
List.mapi
(fun i slicei ->
let length = shape.(i) in
let infer_len_i = infer_len length in
match slicei with
| [] -> length
| [ index ] -> infer_len_i index index ()
| [ start; stop ] -> infer_len_i start stop ()
| [ start; stop; step ] -> infer_len_i start stop ~step ()
| _ -> failwith
"owl_utils_infer_shape: invalid slice specification")
slice_spec
in
let s = Array.copy shape in
List.iteri (fun i len -> s.(i) <- len) shape';
s
let draw shape axis n =
let d = Array.length shape in
let a = Owl_utils_ndarray.adjust_index axis d in
let s = Array.copy shape in
assert (a < d);
s.(a) <- n;
s
let reduce shape axis =
let d = Array.length shape in
let a = Array.map (fun i -> Owl_utils_ndarray.adjust_index i d) axis in
let s = Array.copy shape in
Array.iter
(fun i ->
assert (i < d);
s.(i) <- 1)
a;
s
let conv2d input_shape padding kernel_shape stride_shape =
let batches = input_shape.(0) in
let input_cols = input_shape.(1) in
let input_rows = input_shape.(2) in
let in_channel = input_shape.(3) in
let kernel_cols = kernel_shape.(0) in
let kernel_rows = kernel_shape.(1) in
let out_channel = kernel_shape.(3) in
assert (in_channel = kernel_shape.(2));
let col_stride = stride_shape.(0) in
let row_stride = stride_shape.(1) in
let output_cols, output_rows =
calc_conv2d_output_shape
padding
input_cols
input_rows
kernel_cols
kernel_rows
row_stride
col_stride
in
[| batches; output_cols; output_rows; out_channel |]
let conv1d input_shape padding kernel_shape stride_shape =
let batches = input_shape.(0) in
let input_cols = input_shape.(1) in
let in_channel = input_shape.(2) in
let input_shape = [| batches; 1; input_cols; in_channel |] in
let kernel_cols = kernel_shape.(0) in
let out_channel = kernel_shape.(2) in
assert (in_channel = kernel_shape.(1));
let kernel_shape = [| 1; kernel_cols; in_channel; out_channel |] in
let col_stride = stride_shape.(0) in
let stride_shape = [| 1; col_stride |] in
let output_shape = conv2d input_shape padding kernel_shape stride_shape in
let output_cols = output_shape.(2) in
[| batches; output_cols; out_channel |]
let conv3d input_shape padding kernel_shape stride_shape =
let batches = input_shape.(0) in
let input_cols = input_shape.(1) in
let input_rows = input_shape.(2) in
let input_dpts = input_shape.(3) in
let in_channel = input_shape.(4) in
let kernel_cols = kernel_shape.(0) in
let kernel_rows = kernel_shape.(1) in
let kernel_dpts = kernel_shape.(2) in
let out_channel = kernel_shape.(4) in
assert (in_channel = kernel_shape.(3));
let col_stride = stride_shape.(0) in
let row_stride = stride_shape.(1) in
let dpt_stride = stride_shape.(2) in
let output_cols, output_rows, output_dpts =
calc_conv3d_output_shape
padding
input_cols
input_rows
input_dpts
kernel_cols
kernel_rows
kernel_dpts
row_stride
col_stride
dpt_stride
in
[| batches; output_cols; output_rows; output_dpts; out_channel |]
let dilated_conv2d input_shape padding kernel_shape stride_shape rate_shape =
let kernel_cols = kernel_shape.(0) in
let kernel_rows = kernel_shape.(1) in
let in_channel = kernel_shape.(2) in
let out_channel = kernel_shape.(3) in
let rate_cols = rate_shape.(0) in
let rate_rows = rate_shape.(1) in
let col_up = kernel_cols + ((kernel_cols - 1) * (rate_cols - 1)) in
let row_up = kernel_rows + ((kernel_rows - 1) * (rate_rows - 1)) in
let kernel_shape' = [| col_up; row_up; in_channel; out_channel |] in
conv2d input_shape padding kernel_shape' stride_shape
let dilated_conv1d input_shape padding kernel_shape stride_shape rate_shape =
let batches = input_shape.(0) in
let input_cols = input_shape.(1) in
let in_channel = input_shape.(2) in
let input_shape = [| batches; 1; input_cols; in_channel |] in
let kernel_cols = kernel_shape.(0) in
let out_channel = kernel_shape.(2) in
assert (in_channel = kernel_shape.(1));
let kernel_shape = [| 1; kernel_cols; in_channel; out_channel |] in
let col_stride = stride_shape.(0) in
let stride_shape = [| 1; col_stride |] in
let col_rate = rate_shape.(0) in
let rate_shape = [| 1; col_rate |] in
let output_shape =
dilated_conv2d input_shape padding kernel_shape stride_shape rate_shape
in
let output_cols = output_shape.(2) in
[| batches; output_cols; out_channel |]
let dilated_conv3d input_shape padding kernel_shape stride_shape rate_shape =
let kernel_cols = kernel_shape.(0) in
let kernel_rows = kernel_shape.(1) in
let kernel_dpts = kernel_shape.(2) in
let in_channel = kernel_shape.(3) in
let out_channel = kernel_shape.(4) in
let rate_cols = rate_shape.(0) in
let rate_rows = rate_shape.(1) in
let rate_dpts = rate_shape.(2) in
let col_up = kernel_cols + ((kernel_cols - 1) * (rate_cols - 1)) in
let row_up = kernel_rows + ((kernel_rows - 1) * (rate_rows - 1)) in
let dpt_up = kernel_dpts + ((kernel_dpts - 1) * (rate_dpts - 1)) in
let kernel_shape' = [| col_up; row_up; dpt_up; in_channel; out_channel |] in
conv3d input_shape padding kernel_shape' stride_shape
let transpose_conv2d input_shape padding kernel_shape stride_shape =
let batches = input_shape.(0) in
let input_cols = input_shape.(1) in
let input_rows = input_shape.(2) in
let in_channel = input_shape.(3) in
let kernel_cols = kernel_shape.(0) in
let kernel_rows = kernel_shape.(1) in
let out_channel = kernel_shape.(3) in
assert (in_channel = kernel_shape.(2));
let col_stride = stride_shape.(0) in
let row_stride = stride_shape.(1) in
let output_cols, output_rows =
calc_transpose_conv2d_output_shape
padding
input_cols
input_rows
kernel_cols
kernel_rows
row_stride
col_stride
in
[| batches; output_cols; output_rows; out_channel |]
let transpose_conv1d input_shape padding kernel_shape stride_shape =
let batches = input_shape.(0) in
let input_cols = input_shape.(1) in
let in_channel = input_shape.(2) in
let input_shape = [| batches; 1; input_cols; in_channel |] in
let kernel_cols = kernel_shape.(0) in
let out_channel = kernel_shape.(2) in
assert (in_channel = kernel_shape.(1));
let kernel_shape = [| 1; kernel_cols; in_channel; out_channel |] in
let col_stride = stride_shape.(0) in
let stride_shape = [| 1; col_stride |] in
let output_shape = transpose_conv2d input_shape padding kernel_shape stride_shape in
let output_cols = output_shape.(2) in
[| batches; output_cols; out_channel |]
let transpose_conv3d input_shape padding kernel_shape stride_shape =
let batches = input_shape.(0) in
let input_cols = input_shape.(1) in
let input_rows = input_shape.(2) in
let input_dpts = input_shape.(3) in
let in_channel = input_shape.(4) in
let kernel_cols = kernel_shape.(0) in
let kernel_rows = kernel_shape.(1) in
let kernel_dpts = kernel_shape.(2) in
let out_channel = kernel_shape.(4) in
assert (in_channel = kernel_shape.(3));
let col_stride = stride_shape.(0) in
let row_stride = stride_shape.(1) in
let dpt_stride = stride_shape.(2) in
let output_cols, output_rows, output_dpts =
calc_transpose_conv3d_output_shape
padding
input_cols
input_rows
input_dpts
kernel_cols
kernel_rows
kernel_dpts
row_stride
col_stride
dpt_stride
in
[| batches; output_cols; output_rows; output_dpts; out_channel |]
let pool2d input_shape padding kernel_shape stride_shape =
let batches = input_shape.(0) in
let input_cols = input_shape.(1) in
let input_rows = input_shape.(2) in
let in_channel = input_shape.(3) in
let kernel_cols = kernel_shape.(0) in
let kernel_rows = kernel_shape.(1) in
let col_stride = stride_shape.(0) in
let row_stride = stride_shape.(1) in
let output_cols, output_rows =
calc_conv2d_output_shape
padding
input_cols
input_rows
kernel_cols
kernel_rows
row_stride
col_stride
in
[| batches; output_cols; output_rows; in_channel |]
let upsampling2d input_shape size =
let batches = input_shape.(0) in
let input_cols = input_shape.(1) in
let input_rows = input_shape.(2) in
let in_channel = input_shape.(3) in
let col_size = size.(0) in
let row_size = size.(1) in
[| batches; input_cols * col_size; input_rows * row_size; in_channel |]
let transpose input_shape axis = Array.map (fun j -> input_shape.(j)) axis
let dot x_shape y_shape = [| x_shape.(0); y_shape.(1) |]
let onehot input_shape depth = Array.append input_shape [| depth |]
(* ends here *)
| (*
* OWL - OCaml Scientific Computing
* Copyright (c) 2016-2022 Liang Wang <liang@ocaml.xyz>
*) |
dune |
(executable
(name test)
(modules test)
(libraries rosetta unstrctrd unstrctrd.parser alcotest fmt rresult result
angstrom multipart_form))
(executable
(name test_lwt)
(modules test_lwt)
(libraries fmt fmt.tty logs logs.fmt alcotest alcotest-lwt lwt
multipart_form multipart_form-lwt))
(rule
(alias runtest)
(package multipart_form)
(deps
(:test test.exe))
(action
(run %{test} --color=always)))
(rule
(alias runtest)
(package multipart_form-lwt)
(deps
(:test test_lwt.exe))
(action
(run %{test} --color=always)))
| |
dune |
; This file was automatically generated, do not edit.
; Edit file manifest/main.ml instead.
(library
(name tezos_protocol_plugin_011_PtHangz2)
(public_name tezos-protocol-plugin-011-PtHangz2)
(instrumentation (backend bisect_ppx))
(libraries
tezos-base
tezos-protocol-011-PtHangz2)
(flags
(:standard)
-open Tezos_base.TzPervasives
-open Tezos_base.TzPervasives.Error_monad.Legacy_monad_globals
-open Tezos_protocol_011_PtHangz2)
(modules (:standard \ Plugin_registerer)))
(library
(name tezos_protocol_plugin_011_PtHangz2_registerer)
(public_name tezos-protocol-plugin-011-PtHangz2-registerer)
(instrumentation (backend bisect_ppx))
(libraries
tezos-base
tezos-embedded-protocol-011-PtHangz2
tezos-protocol-plugin-011-PtHangz2
tezos-shell)
(flags
(:standard)
-open Tezos_base.TzPervasives
-open Tezos_base.TzPervasives.Error_monad.Legacy_monad_globals
-open Tezos_embedded_protocol_011_PtHangz2
-open Tezos_protocol_plugin_011_PtHangz2
-open Tezos_shell)
(modules Plugin_registerer))
| |
intmap.ml | (* -------------------------------------------------------------------------- *)
(* --- Bit library --- *)
(* -------------------------------------------------------------------------- *)
let hsb =
let hsb p = if p land 2 != 0 then 1 else 0
in let hsb p = let n = p lsr 2 in if n != 0 then 2 + hsb n else hsb p
in let hsb p = let n = p lsr 4 in if n != 0 then 4 + hsb n else hsb p
in let hsb = Array.init 256 hsb
in let hsb p = let n = p lsr 8 in if n != 0 then 8 + hsb.(n) else hsb.(p)
in let hsb p = let n = p lsr 16 in if n != 0 then 16 + hsb n else hsb p
in match Sys.word_size with
| 32 -> hsb
| 64 -> (function p -> let n = p lsr 32 in
if n != 0 then 32 + hsb n else hsb p)
| _ -> assert false (** absurd: No other possible achitecture supported *)
let highest_bit x = 1 lsl (hsb x)
let lowest_bit x = x land (-x)
(* -------------------------------------------------------------------------- *)
(* --- Bit utilities --- *)
(* -------------------------------------------------------------------------- *)
let decode_mask p = lowest_bit (lnot p)
let branching_bit p0 p1 = highest_bit (p0 lxor p1)
let mask p m = (p lor (m-1)) land (lnot m)
let zero_bit_int k m = (k land m) == 0
let zero_bit k p = zero_bit_int k (decode_mask p)
let match_prefix_int k p m = (mask k m) == p
let match_prefix k p = match_prefix_int k p (decode_mask p)
let included_mask_int m n =
(* m mask is strictly included into n *)
(* can not use (m < n) when n is (1 lsl 62) = min_int < 0 *)
(* must use (0 < (n-m) instead *)
0 > n - m
(* let included_mask p q = included_mask_int (decode_mask p) (decode_mask q) *)
let included_prefix p q =
let m = decode_mask p in
let n = decode_mask q in
included_mask_int m n && match_prefix_int q p m
(* -------------------------------------------------------------------------- *)
(* --- Debug --- *)
(* -------------------------------------------------------------------------- *)
let pp_mask m fmt p =
begin
let bits = Array.make 63 false in
let last = ref 0 in
for i = 0 to 62 do
let u = 1 lsl i in
if u land p <> 0 then
bits.(i) <- true ;
if u == m then last := i ;
done ;
Format.pp_print_char fmt '*' ;
for i = !last - 1 downto 0 do
Format.pp_print_char fmt (if bits.(i) then '1' else '0') ;
done ;
end
let pp_bits fmt k =
begin
let bits = Array.make 63 false in
let last = ref 0 in
for i = 0 to 62 do
if (1 lsl i) land k <> 0 then
( bits.(i) <- true ;
if i > !last then last := i ) ;
done ;
for i = !last downto 0 do
Format.pp_print_char fmt (if bits.(i) then '1' else '0') ;
done ;
end
(* ---------------------------------------------------------------------- *)
(* --- Patricia Trees By L. Correnson & P. Baudin & F. Bobot --- *)
(* ---------------------------------------------------------------------- *)
module Make(K:Map_intf.TaggedEqualType) :
Map_intf.Gen_Map_hashcons with type NT.key = K.t = struct
module Gen(G:sig
type (+'a) t
type 'a data
type 'a view = private
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
val view: 'a data t -> 'a data view
val mk_Empty: 'a data t
val mk_Lf: K.t -> 'a data -> 'a data t
val mk_Br: int -> 'a data t -> 'a data t -> 'a data t
val ktag : 'a data t -> int
end)
= struct
open G
type key = K.t
type 'a data = 'a G.data
type 'a t = 'a G.t
(* ---------------------------------------------------------------------- *)
(* --- Smart Constructors --- *)
(* ---------------------------------------------------------------------- *)
let empty = mk_Empty
let singleton = mk_Lf
let lf k = function None -> mk_Empty | Some x -> mk_Lf k x
(* good sharing *)
let lf0 k x' t' = function
| None -> mk_Empty
| Some x -> if x == x' then t' else mk_Lf k x
(* good sharing *)
let br0 p t0' t1' t' t0 = match view t0 with
| Empty -> t1'
| _ -> if t0' == t0 then t' else mk_Br p t0 t1'
(* good sharing *)
let br1 p t0' t1' t' t1 = match view t1 with
| Empty -> t0'
| _ -> if t1' == t1 then t' else mk_Br p t0' t1
let join p t0 q t1 =
let m = branching_bit p q in
let r = mask p m in
if zero_bit p r
then mk_Br r t0 t1
else mk_Br r t1 t0
let side p q = (* true this side, false inverse *)
let m = branching_bit p q in
let r = mask p m in
zero_bit p r
(* t0 and t1 has different prefix, but best common prefix is unknown *)
let glue t0 t1 =
match view t0 , view t1 with
| Empty,_ -> t1
| _,Empty -> t0
| _,_ -> join (ktag t0) t0 (ktag t1) t1
let glue' ~old ~cur ~other ~all =
if old == cur then all else glue cur other
let glue0 t0 t0' t1' t' =
if t0 == t0' then t' else glue t0 t1'
let glue1 t1 t0' t1' t' =
if t1 == t1' then t' else glue t0' t1
let glue01 t0 t1 t0' t1' t' =
if t0 == t0' && t1 == t1' then t' else glue t0 t1
let glue2 t0 t1 t0' t1' t' s0' s1' s' =
if t0 == s0' && t1 == s1' then s' else
if t0 == t0' && t1 == t1' then t' else glue t0 t1
(* ---------------------------------------------------------------------- *)
(* --- Access API --- *)
(* ---------------------------------------------------------------------- *)
let is_empty x = match view x with
| Empty -> true
| Lf _ | Br _ -> false
let size t =
let rec walk n t = match view t with
| Empty -> n
| Lf _ -> succ n
| Br(_,a,b) -> walk (walk n a) b
in walk 0 t
let cardinal = size
let rec mem k t = match view t with
| Empty -> false
| Lf(i,_) -> K.equal i k
| Br(p,t0,t1) ->
match_prefix (K.tag k) p &&
mem k (if zero_bit (K.tag k) p then t0 else t1)
(* let rec findq k t = match view t with
* | Empty -> raise Not_found
* | Lf(i,x) -> if K.equal k i then (x,t) else raise Not_found
* | Br(p,t0,t1) ->
* if match_prefix (K.tag k) p then
* findq k (if zero_bit (K.tag k) p then t0 else t1)
* else
* raise Not_found *)
let rec find_exn exn k t = match view t with
| Empty -> raise exn
| Lf(i,x) -> if K.equal k i then x else raise exn
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
find_exn exn k (if zero_bit (K.tag k) p then t0 else t1)
else
raise exn
let find k m = find_exn Not_found k m
let rec find_opt k t = match view t with
| Empty -> None
| Lf(i,x) -> if K.equal k i then Some x else None
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
find_opt k (if zero_bit (K.tag k) p then t0 else t1)
else
None
let rec find_def def k t = match view t with
| Empty -> def
| Lf(i,x) -> if K.equal k i then x else def
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
find_def def k (if zero_bit (K.tag k) p then t0 else t1)
else
def
(* good sharing *)
let rec find_remove k t = match view t with
| Empty -> mk_Empty, None
| Lf(i,y) ->
if K.equal i k then
mk_Empty, Some y
else
t, None
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
(* k belongs to tree *)
if zero_bit (K.tag k) p
then let t0', r = find_remove k t0 in
br0 p t0 t1 t t0', r (* k is in t0 *)
else let t1', r = find_remove k t1 in
br1 p t0 t1 t t1', r (* k is in t1 *)
else
(* k is disjoint from tree *)
t, None
(** shouldn't be used at top *)
let rec max_binding_opt t = match view t with
| Empty -> None
| Lf(k,x) -> Some(k,x)
| Br(_,_,t1) -> max_binding_opt t1
let rec find_smaller_opt' cand k t = match view t with
| Empty -> assert false
| Lf(i,y) ->
let c = Stdlib.compare (K.tag i) (K.tag k) in
if c <= 0 then Some(i,y)
else (* c > 0 *) max_binding_opt cand
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
(* k belongs to tree *)
if zero_bit (K.tag k) p
then find_smaller_opt' cand k t0
else find_smaller_opt' t0 k t1
else
(* k is disjoint from tree *)
if side (K.tag k) p
then (* k p *) max_binding_opt cand
else (* p k *) max_binding_opt t1
let find_smaller_opt k t = match view t with
| Empty -> None
| Br(p,t0,t1) when p = max_int ->
(* k belongs to tree *)
if zero_bit (K.tag k) p
then find_smaller_opt' t1 k t0
else find_smaller_opt' mk_Empty k t1
| _ ->
find_smaller_opt' mk_Empty k t
(* ---------------------------------------------------------------------- *)
(* --- Comparison --- *)
(* ---------------------------------------------------------------------- *)
let rec compare cmp s t =
if (Obj.magic s) == t then 0 else
match view s , view t with
| Empty , Empty -> 0
| Empty , _ -> (-1)
| _ , Empty -> 1
| Lf(i,x) , Lf(j,y) ->
let ck = Stdlib.compare (K.tag i) (K.tag j) in
if ck = 0 then cmp x y else ck
| Lf _ , _ -> (-1)
| _ , Lf _ -> 1
| Br(p,s0,s1) , Br(q,t0,t1) ->
let cp = Stdlib.compare p q in
if cp <> 0 then cp else
let c0 = compare cmp s0 t0 in
if c0 <> 0 then c0 else
compare cmp s1 t1
let rec equal eq s t =
if (Obj.magic s) == t then true else
match view s , view t with
| Empty , Empty -> true
| Lf(i,x) , Lf(j,y) -> K.equal i j && eq x y
| Br(p,s0,s1) , Br(q,t0,t1) ->
p==q && equal eq s0 t0 && equal eq s1 t1
| _ -> false
(* ---------------------------------------------------------------------- *)
(* --- Addition, Insert, Change, Remove --- *)
(* ---------------------------------------------------------------------- *)
(* good sharing *)
let rec change phi k x t = match view t with
| Empty -> (match phi k x None with
| None -> t
| Some w -> mk_Lf k w)
| Lf(i,y) ->
if K.equal i k then
lf0 k y t (phi k x (Some y))
else
(match phi k x None with
| None -> t
| Some w -> let s = mk_Lf k w in
join (K.tag k) s (K.tag i) t)
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
(* k belongs to tree *)
if zero_bit (K.tag k) p
then br0 p t0 t1 t (change phi k x t0) (* k is in t0 *)
else br1 p t0 t1 t (change phi k x t1) (* k is in t1 *)
else
(* k is disjoint from tree *)
(match phi k x None with
| None -> t
| Some w -> let s = mk_Lf k w in
join (K.tag k) s p t)
(* good sharing *)
let insert f k x = change (fun _k x -> function
| None -> Some x
| Some old -> Some (f k x old)) k x
(* good sharing *)
let add k x m = change (fun _k x _old -> Some x) k x m
(* good sharing *)
let remove k m = change (fun _k () _old -> None) k () m
(* good sharing *)
let add_new e x v m = change (fun _k (e,v) -> function
| Some _ -> raise e
| None -> Some v) x (e,v) m
(* good sharing *)
let rec add_change empty add k b t = match view t with
| Empty -> mk_Lf k (empty b)
| Lf(i,y) ->
if K.equal i k then
let y' = (add b y) in
if y == y' then t else mk_Lf i y'
else
let s = mk_Lf k (empty b) in
join (K.tag k) s (K.tag i) t
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
(* k belongs to tree *)
if zero_bit (K.tag k) p
then mk_Br p (add_change empty add k b t0) t1 (* k is in t0 *)
else mk_Br p t0 (add_change empty add k b t1) (* k is in t1 *)
else
(* k is disjoint from tree *)
let s = mk_Lf k (empty b) in
join (K.tag k) s p t
(* ---------------------------------------------------------------------- *)
(* --- Map --- *)
(* ---------------------------------------------------------------------- *)
let mapi phi t =
let rec mapi phi t = match view t with
| Empty -> mk_Empty
| Lf(k,x) -> mk_Lf k (phi k x)
| Br(p,t0,t1) ->
let t0 = mapi phi t0 in
let t1 = mapi phi t1 in
mk_Br p t0 t1
in match view t with (* in order to be sorted *)
| Empty -> mk_Empty
| Lf(k,x) -> mk_Lf k (phi k x)
| Br(p,t0,t1) when p = max_int -> let t1 = mapi phi t1 in
let t0 = mapi phi t0 in mk_Br p t0 t1
| Br(p,t0,t1) -> let t0 = mapi phi t0 in
let t1 = mapi phi t1 in mk_Br p t0 t1
let map phi = mapi (fun _ x -> phi x)
let mapf phi t =
let rec mapf phi t = match view t with
| Empty -> mk_Empty
| Lf(k,x) -> lf k (phi k x)
| Br(_,t0,t1) -> glue (mapf phi t0) (mapf phi t1)
in match view t with (* in order to be sorted *)
| Empty -> mk_Empty
| Lf(k,x) -> lf k (phi k x)
| Br(p,t0,t1) when p = max_int -> let t1 = mapf phi t1 in
let t0 = mapf phi t0 in glue t0 t1
| Br(_,t0,t1) -> let t0 = mapf phi t0 in
let t1 = mapf phi t1 in glue t0 t1
(* good sharing *)
(* let mapq phi t =
* let rec mapq phi t = match view t with
* | Empty -> t
* | Lf(k,x) -> lf0 k x t (phi k x)
* | Br(_,t0,t1) ->
* let t0' = mapq phi t0 in
* let t1' = mapq phi t1 in
* glue01 t0' t1' t0 t1 t
* in match view t with (\* to be sorted *\)
* | Empty -> t
* | Lf(k,x) -> lf0 k x t (phi k x)
* | Br(p,t0,t1) when p = max_int ->
* let t1' = mapq phi t1 in
* let t0' = mapq phi t0 in
* glue01 t0' t1' t0 t1 t
* | Br(_,t0,t1) ->
* let t0' = mapq phi t0 in
* let t1' = mapq phi t1 in
* glue01 t0' t1' t0 t1 t *)
(** bad sharing but polymorph *)
let mapq' :
type a b. (key -> a data -> b data option) -> a data t -> b data t=
fun phi t ->
let rec aux phi t = match view t with
| Empty -> mk_Empty
| Lf(k,x) -> lf k (phi k x)
| Br(_,t0,t1) ->
let t0' = aux phi t0 in
let t1' = aux phi t1 in
glue t0' t1'
in match view t with (* to be sorted *)
| Empty -> mk_Empty
| Lf(k,x) -> lf k (phi k x)
| Br(p,t0,t1) when p = max_int ->
let t1' = aux phi t1 in
let t0' = aux phi t0 in
glue t0' t1'
| Br(_,t0,t1) ->
let t0' = aux phi t0 in
let t1' = aux phi t1 in
glue t0' t1'
let filter f m = mapq' (fun k v -> if f k v then Some v else None) m
let mapi_filter = mapq'
let map_filter f m = mapq' (fun _ v -> f v) m
(*
bad sharing because the input type can be differente of the
output type it is possible but currently too many Obj.magic are
needed in lf0 and glue01
*)
let mapi_filter_fold:
type a b acc. (key -> a data -> acc -> acc * b data option) ->
a data t -> acc -> acc * b data t
= fun phi t acc ->
let rec aux phi t acc = match view t with
| Empty -> acc, mk_Empty
| Lf(k,x) -> let acc,x = (phi k x acc) in acc, lf k x
| Br(_,t0,t1) ->
let acc, t0' = aux phi t0 acc in
let acc, t1' = aux phi t1 acc in
acc, glue t0' t1'
in match view t with (* to be sorted *)
| Empty -> acc, mk_Empty
| Lf(k,x) -> let acc,x = (phi k x acc) in acc, lf k x
| Br(p,t0,t1) when p = max_int ->
let acc, t1' = aux phi t1 acc in
let acc, t0' = aux phi t0 acc in
acc, glue t0' t1'
| Br(_,t0,t1) ->
let acc, t0' = aux phi t0 acc in
let acc, t1' = aux phi t1 acc in
acc, glue t0' t1'
let mapi_fold phi t acc =
mapi_filter_fold (fun k v acc ->
let acc, v' = phi k v acc in
acc, Some v') t acc
(* good sharing *)
let rec partition p t = match view t with
| Empty -> (t,t)
| Lf(k,x) -> if p k x then t,mk_Empty else mk_Empty,t
| Br(_,t0,t1) ->
let (t0',u0') = partition p t0 in
let (t1',u1') = partition p t1 in
if t0'==t0 && t1'==t1 then (t, u0') (* u0' and u1' are empty *)
else if u0'==t0 && u1'==t1 then (t0', t) (* t0' and t1' are empty *)
else (glue t0' t1'),(glue u0' u1')
(* good sharing *)
let split k t =
let rec aux k t = match view t with
| Empty -> assert false (** absurd: only at top *)
| Lf(k',x) -> let c = Stdlib.compare (K.tag k) (K.tag k') in
if c = 0 then (mk_Empty,Some x,mk_Empty)
else if c < 0 then (mk_Empty, None, t)
else (* c > 0 *) (t, None, mk_Empty)
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
then
let (t0',r,t1') = aux k t0 in
(t0',r,glue' ~old:t0 ~cur:t1' ~other:t1 ~all:t )
else
let (t0',r,t1') = aux k t1 in
(glue' ~old:t1 ~cur:t0' ~other:t0 ~all:t,r,t1')
else
if side (K.tag k) p
then (* k p *) (mk_Empty, None, t)
else (* p k *) (t, None, mk_Empty)
in match view t with
| Empty -> mk_Empty, None, mk_Empty
| Br(p,t0,t1) when p = max_int -> (** inverted *)
if zero_bit (K.tag k) p
then
let (t0',r,t1') = aux k t0 in
(glue' ~old:t0 ~cur:t0' ~other:t1 ~all:t,r,t1' )
else
let (t0',r,t1') = aux k t1 in
(t0',r,glue' ~old:t1 ~cur:t1' ~other:t0 ~all:t)
| _ -> aux k t
(* good sharing *)
(* let rec partition_split p t = match view t with
* | Empty -> (t,t)
* | Lf(k,x) -> let u,v = p k x in (lf0 k x t u), (lf0 k x t v)
* | Br(_,t0,t1) ->
* let t0',u0' = partition_split p t0 in
* let t1',u1' = partition_split p t1 in
* if t0'==t0 && t1'==t1 then (t, u0') (\* u0' and u1' are empty *\)
* else if u0'==t0 && u1'==t1 then (t0', t) (\* t0' and t1' are empty *\)
* else (glue t0' t1'),(glue u0' u1') *)
(* ---------------------------------------------------------------------- *)
(* --- Iter --- *)
(* ---------------------------------------------------------------------- *)
let iteri phi t =
let rec aux t = match view t with
| Empty -> ()
| Lf(k,x) -> phi k x
| Br(_,t0,t1) -> aux t0 ; aux t1
in match view t with (* in order to be sorted *)
| Empty -> ()
| Lf(k,x) -> phi k x
| Br(p,t0,t1) when p = max_int -> aux t1 ; aux t0
| Br(_,t0,t1) -> aux t0 ; aux t1
let iter = iteri
let foldi phi t e = (* increasing order *)
let rec aux t e = match view t with
| Empty -> e
| Lf(i,x) -> phi i x e
| Br(_,t0,t1) -> aux t1 (aux t0 e)
in match view t with (* to be sorted *)
| Empty -> e
| Lf(i,x) -> phi i x e
| Br(p,t0,t1) when p = max_int -> aux t0 (aux t1 e)
| Br(_,t0,t1) -> aux t1 (aux t0 e)
let fold = foldi
let fold_left phi e t = (* increasing order *)
let rec aux t e = match view t with
| Empty -> e
| Lf(k,x) -> phi e k x
| Br(_,t0,t1) -> aux t1 (aux t0 e)
in match view t with (* to be sorted *)
| Empty -> e
| Lf(k,x) -> phi e k x
| Br(p,t0,t1) when p = max_int -> aux t0 (aux t1 e)
| Br(_,t0,t1) -> aux t1 (aux t0 e)
let foldd phi e t = (* decreasing order *)
let rec aux t e = match view t with
| Empty -> e
| Lf(i,x) -> phi e i x
| Br(_,t0,t1) -> aux t0 (aux t1 e)
in match view t with (* to be sorted *)
| Empty -> e
| Lf(i,x) -> phi e i x
| Br(p,t0,t1) when p = max_int -> aux t1 (aux t0 e)
| Br(_,t0,t1) -> aux t0 (aux t1 e)
let fold_decr = foldd
(* decreasing order on f to have the list in increasing order *)
let mapl f m = foldd (fun a k v -> (f k v)::a) [] m
let bindings m = mapl (fun k v -> (k,v)) m
let values m = mapl (fun _ v -> v) m
let keys m = mapl (fun k _ -> k) m
let for_all phi t = (* increasing order *)
let rec aux t = match view t with
| Empty -> true
| Lf(k,x) -> phi k x
| Br(_,t0,t1) -> aux t0 && aux t1
in match view t with (* in order to be sorted *)
| Empty -> true
| Lf(k,x) -> phi k x
| Br(p,t0,t1) when p = max_int -> aux t1 && aux t0
| Br(_,t0,t1) -> aux t0 && aux t1
let exists phi t = (* increasing order *)
let rec aux t = match view t with
| Empty -> false
| Lf(k,x) -> phi k x
| Br(_,t0,t1) -> aux t0 || aux t1
in match view t with (* in order to be sorted *)
| Empty -> false
| Lf(k,x) -> phi k x
| Br(p,t0,t1) when p = max_int -> aux t1 || aux t0
| Br(_,t0,t1) -> aux t0 || aux t1
let min_binding t = (* increasing order *)
let rec aux t = match view t with
| Empty -> assert false (** absurd: only at top *)
| Lf(k,x) -> (k,x)
| Br(_,t0,_) -> aux t0
in match view t with (* in order to be sorted *)
| Empty -> raise Not_found
| Lf(k,x) -> (k,x)
| Br(p,_,t1) when p = max_int -> aux t1
| Br(_,t0,_) -> aux t0
let max_binding t = (* increasing order *)
let rec aux t = match view t with
| Empty -> assert false (** absurd: only at top *)
| Lf(k,x) -> (k,x)
| Br(_,_,t1) -> aux t1
in match view t with (* in order to be sorted *)
| Empty -> raise Not_found
| Lf(k,x) -> (k,x)
| Br(p,t0,_) when p = max_int -> aux t0
| Br(_,_,t1) -> aux t1
let choose = min_binding
(* ---------------------------------------------------------------------- *)
(* --- Inter --- *)
(* ---------------------------------------------------------------------- *)
let occur i t = try Some (find i t) with Not_found -> None
let rec interi lf_phi s t =
match view s , view t with
| Empty , _ -> mk_Empty
| _ , Empty -> mk_Empty
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then lf_phi i x y
else mk_Empty
| Lf(i,x) , Br _ ->
(match occur i t with None -> mk_Empty | Some y -> lf_phi i x y)
| Br _ , Lf(j,y) ->
(match occur j s with None -> mk_Empty | Some x -> lf_phi j x y)
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
glue (interi lf_phi s0 t0) (interi lf_phi s1 t1)
else if included_prefix p q then
(* q contains p. Intersect t with a subtree of s *)
if zero_bit q p
then interi lf_phi s0 t (* t has bit m = 0 => t is inside s0 *)
else interi lf_phi s1 t (* t has bit m = 1 => t is inside s1 *)
else if included_prefix q p then
(* p contains q. Intersect s with a subtree of t *)
if zero_bit p q
then interi lf_phi s t0 (* s has bit n = 0 => s is inside t0 *)
else interi lf_phi s t1 (* t has bit n = 1 => s is inside t1 *)
else
(* prefix disagree *)
mk_Empty
let interf phi = interi (fun i x y -> mk_Lf i (phi i x y))
let inter phi = interi (fun i x y -> lf i (phi i x y))
(* good sharing with s *)
(* let lfq phi i x y s t =
* match phi i x y with
* | None -> mk_Empty
* | Some w -> if w == x then s else if w == y then t else mk_Lf i w *)
(* let occur0 phi i x s t =
* try let (y,t) = findq i t in lfq phi i x y s t
* with Not_found -> mk_Empty *)
(* let occur1 phi j y s t =
* try let (x,s) = findq j s in lfq phi j x y s t
* with Not_found -> mk_Empty *)
(* good sharing with s *)
(* let rec interq phi s t =
* match view s , view t with
* | Empty , _ -> s
* | _ , Empty -> t
* | Lf(i,x) , Lf(j,y) ->
* if K.equal i j
* then lfq phi i x y s t
* else mk_Empty
* | Lf(i,x) , Br _ -> occur0 phi i x s t
* | Br _ , Lf(j,y) -> occur1 phi j y s t
* | Br(p,s0,s1) , Br(q,t0,t1) ->
* if p == q then
* (\* prefixes agree *\)
* glue2 (interq phi s0 t0) (interq phi s1 t1) s0 s1 s t0 t1 t
* else if included_prefix p q then
* (\* q contains p. Intersect t with a subtree of s *\)
* if zero_bit q p
* then interq phi s0 t (\* t has bit m = 0 => t is inside s0 *\)
* else interq phi s1 t (\* t has bit m = 1 => t is inside s1 *\)
* else if included_prefix q p then
* (\* p contains q. Intersect s with a subtree of t *\)
* if zero_bit p q
* then interq phi s t0 (\* s has bit n = 0 => s is inside t0 *\)
* else interq phi s t1 (\* t has bit n = 1 => s is inside t1 *\)
* else
* (\* prefix disagree *\)
* mk_Empty *)
(* ---------------------------------------------------------------------- *)
(* --- Union --- *)
(* ---------------------------------------------------------------------- *)
(* good sharing with s *)
let br2u p s0' s1' s' t0' t1' t' t0 t1=
if s0'==t0 && s1'== t1 then s' else
if t0'==t0 && t1'== t1 then t' else
mk_Br p t0 t1
(* good sharing with s *)
let br0u p t0' t1' t' t0 = if t0'==t0 then t' else mk_Br p t0 t1'
let br1u p t0' t1' t' t1 = if t1'==t1 then t' else mk_Br p t0' t1
(* good sharing with s *)
let rec unionf phi s t =
match view s , view t with
| Empty , _ -> t
| _ , Empty -> s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then let w = phi i x y in
if w == x then s else if w == y then t else mk_Lf i w
else join (K.tag i) s (K.tag j) t
| Lf(i,x) , Br _ -> insert phi i x t
| Br _ , Lf(j,y) -> insert (fun j y x -> phi j x y) j y s
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
br2u p s0 s1 s t0 t1 t (unionf phi s0 t0) (unionf phi s1 t1)
else if included_prefix p q then
(* q contains p. Merge t with a subtree of s *)
if zero_bit q p
then
(* t has bit m = 0 => t is inside s0 *)
br0u p s0 s1 s (unionf phi s0 t)
else
(* t has bit m = 1 => t is inside s1 *)
br1u p s0 s1 s (unionf phi s1 t)
else if included_prefix q p then
(* p contains q. Merge s with a subtree of t *)
if zero_bit p q
then
(* s has bit n = 0 => s is inside t0 *)
br0u q t0 t1 t (unionf phi s t0)
else
(* t has bit n = 1 => s is inside t1 *)
br1u q t0 t1 t (unionf phi s t1)
else
(* prefix disagree *)
join p s q t
(* good sharing with s *)
let rec union phi s t =
match view s , view t with
| Empty , _ -> t
| _ , Empty -> s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then match phi i x y with
| Some w when w == x -> s
| Some w when w == y -> t
| Some w -> mk_Lf i w
| None -> mk_Empty
else join (K.tag i) s (K.tag j) t
| Lf(i,x) , Br _ ->
change (fun i x -> function | None -> Some x
| Some old -> (phi i x old)) i x t
| Br _ , Lf(j,y) ->
change (fun j y -> function | None -> Some y
| Some old -> (phi j old y)) j y s
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
glue2 (union phi s0 t0) (union phi s1 t1) s0 s1 s t0 t1 t
else if included_prefix p q then
(* q contains p. Merge t with a subtree of s *)
if zero_bit q p
then
(* t has bit m = 0 => t is inside s0 *)
br0 p s0 s1 s (union phi s0 t)
else
(* t has bit m = 1 => t is inside s1 *)
br1 p s0 s1 s (union phi s1 t)
else if included_prefix q p then
(* p contains q. Merge s with a subtree of t *)
if zero_bit p q
then
(* s has bit n = 0 => s is inside t0 *)
br0 q t0 t1 t (union phi s t0)
else
(* t has bit n = 1 => s is inside t1 *)
br1 q t0 t1 t (union phi s t1)
else
(* prefix disagree *)
join p s q t
(* ---------------------------------------------------------------------- *)
(* --- Merge --- *)
(* ---------------------------------------------------------------------- *)
let map1 phi s = mapf (fun i x -> phi i (Some x) None) s
let map2 phi t = mapf (fun j y -> phi j None (Some y)) t
let rec merge phi s t =
match view s , view t with
| Empty , _ -> map2 phi t
| _ , Empty -> map1 phi s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j then lf i (phi i (Some x) (Some y))
else
let a = lf i (phi i (Some x) None) in
let b = lf j (phi j None (Some y)) in
glue a b
| Lf(i,x) , Br(q,t0,t1) ->
if match_prefix (K.tag i) q then
(* leaf i is in tree t *)
if zero_bit (K.tag i) q
then glue (merge phi s t0) (map2 phi t1) (* s=i is in t0 *)
else glue (map2 phi t0) (merge phi s t1) (* s=i is in t1 *)
else
(* leaf i does not appear in t *)
glue (lf i (phi i (Some x) None)) (map2 phi t)
| Br(p,s0,s1) , Lf(j,y) ->
if match_prefix (K.tag j) p then
(* leaf j is in tree s *)
if zero_bit (K.tag j) p
then glue (merge phi s0 t) (map1 phi s1) (* t=j is in s0 *)
else glue (map1 phi s0) (merge phi s1 t) (* t=j is in s1 *)
else
(* leaf j does not appear in s *)
glue (map1 phi s) (lf j (phi j None (Some y)))
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
glue (merge phi s0 t0) (merge phi s1 t1)
else if included_prefix p q then
(* q contains p. Merge t with a subtree of s *)
if zero_bit q p
then (* t has bit m = 0 => t is inside s0 *)
glue (merge phi s0 t) (map1 phi s1)
else (* t has bit m = 1 => t is inside s1 *)
glue (map1 phi s0) (merge phi s1 t)
else if included_prefix q p then
(* p contains q. Merge s with a subtree of t *)
if zero_bit p q
then (* s has bit n = 0 => s is inside t0 *)
glue (merge phi s t0) (map2 phi t1)
else (* s has bit n = 1 => s is inside t1 *)
glue (map2 phi t0) (merge phi s t1)
else
glue (map1 phi s) (map2 phi t)
let map2 phi t = mapf (fun j y -> phi j None y) t
let rec union_merge phi s t =
match view s , view t with
| Empty , _ -> map2 phi t
| _ , Empty -> s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j then lf i (phi i (Some x) y)
else
let b = lf j (phi j None y) in
glue s b
| Lf(i,_) , Br(q,t0,t1) ->
if match_prefix (K.tag i) q then
(* leaf i is in tree t *)
if zero_bit (K.tag i) q
then glue (union_merge phi s t0) (map2 phi t1) (* s=i is in t0 *)
else glue (map2 phi t0) (union_merge phi s t1) (* s=i is in t1 *)
else
(* leaf i does not appear in t *)
glue s (map2 phi t)
| Br(p,s0,s1) , Lf(j,y) ->
if match_prefix (K.tag j) p then
(* leaf j is in tree s *)
if zero_bit (K.tag j) p
then glue (union_merge phi s0 t) s1 (* t=j is in s0 *)
else glue s0 (union_merge phi s1 t) (* t=j is in s1 *)
else
(* leaf j does not appear in s *)
glue s (lf j (phi j None y))
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
glue (union_merge phi s0 t0) (union_merge phi s1 t1)
else if included_prefix p q then
(* q contains p. Merge t with a subtree of s *)
if zero_bit q p
then (* t has bit m = 0 => t is inside s0 *)
glue (union_merge phi s0 t) s1
else (* t has bit m = 1 => t is inside s1 *)
glue s0 (union_merge phi s1 t)
else if included_prefix q p then
(* p contains q. Merge s with a subtree of t *)
if zero_bit p q
then (* s has bit n = 0 => s is inside t0 *)
glue (union_merge phi s t0) (map2 phi t1)
else (* s has bit n = 1 => s is inside t1 *)
glue (map2 phi t0) (union_merge phi s t1)
else
glue s (map2 phi t)
(* good sharing with s *)
(* let rec diffq phi s t =
* match view s , view t with
* | Empty , _ -> s
* | _ , Empty -> s
* | Lf(i,x) , Lf(j,y) ->
* if K.equal i j
* then lfq phi i x y s t
* else s
* | Lf(i,x) , Br _ ->
* (match occur i t with None -> s | Some y -> lfq phi i x y s t)
* | Br _ , Lf(j,y) -> change (fun j y x -> match x with
* | None -> None
* | Some x -> phi j x y) j y s
* | Br(p,s0,s1) , Br(q,t0,t1) ->
* if p == q then
* (\* prefixes agree *\)
* let t0' = (diffq phi s0 t0) in
* let t1' = (diffq phi s1 t1) in
* glue01 t0' t1' s0 s1 s
* else if included_prefix p q then
* (\* q contains p. *\)
* if zero_bit q p
* then (\* t has bit m = 0 => t is inside s0 *\)
* let s0' = (diffq phi s0 t) in
* glue0 s0' s0 s1 s
* else (\* t has bit m = 1 => t is inside s1 *\)
* let s1' = (diffq phi s1 t) in
* glue1 s1' s0 s1 s
* else if included_prefix q p then
* (\* p contains q. *\)
* if zero_bit p q
* then diffq phi s t0 (\* s has bit n = 0 => s is inside t0 *\)
* else diffq phi s t1 (\* t has bit n = 1 => s is inside t1 *\)
* else
* (\* prefix disagree *\)
* s *)
(* good sharing with s *)
let rec diff :
type a b. (key -> a data -> b data -> a data option) ->
a data t -> b data t -> a data t
= fun phi s t ->
match view s , view t with
| Empty , _ -> s
| _ , Empty -> s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then lf0 i x s (phi i x y)
else s
| Lf(i,x) , Br _ ->
(match occur i t with None -> s | Some y -> lf0 i x s (phi i x y))
| Br _ , Lf(j,y) -> change (fun j y x -> match x with
| None -> None
| Some x -> phi j x y) j y s
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
let t0' = (diff phi s0 t0) in
let t1' = (diff phi s1 t1) in
glue01 t0' t1' s0 s1 s
else if included_prefix p q then
(* q contains p. *)
if zero_bit q p
then (* t has bit m = 0 => t is inside s0 *)
let s0' = (diff phi s0 t) in
glue0 s0' s0 s1 s
else (* t has bit m = 1 => t is inside s1 *)
let s1' = (diff phi s1 t) in
glue1 s1' s0 s1 s
else if included_prefix q p then
(* p contains q. *)
if zero_bit p q
then diff phi s t0 (* s has bit n = 0 => s is inside t0 *)
else diff phi s t1 (* t has bit n = 1 => s is inside t1 *)
else
(* prefix disagree *)
s
(* ---------------------------------------------------------------------- *)
(* --- Iter Kernel --- *)
(* ---------------------------------------------------------------------- *)
(* let rec iterk phi s t =
* match view s , view t with
* | Empty , _ | _ , Empty -> ()
* | Lf(i,x) , Lf(j,y) -> if K.equal i j then phi i x y
* | Lf(i,x) , Br _ ->
* (match occur i t with None -> () | Some y -> phi i x y)
* | Br _ , Lf(j,y) ->
* (match occur j s with None -> () | Some x -> phi j x y)
* | Br(p,s0,s1) , Br(q,t0,t1) ->
* if p == q then
* (\* prefixes agree *\)
* (iterk phi s0 t0 ; iterk phi s1 t1)
* else if included_prefix p q then
* (\* q contains p. Intersect t with a subtree of s *\)
* if zero_bit q p
* then iterk phi s0 t (\* t has bit m = 0 => t is inside s0 *\)
* else iterk phi s1 t (\* t has bit m = 1 => t is inside s1 *\)
* else if included_prefix q p then
* (\* p contains q. Intersect s with a subtree of t *\)
* if zero_bit p q
* then iterk phi s t0 (\* s has bit n = 0 => s is inside t0 *\)
* else iterk phi s t1 (\* t has bit n = 1 => s is inside t1 *\)
* else
* (\* prefix disagree *\)
* () *)
(* ---------------------------------------------------------------------- *)
(* --- Iter2 --- *)
(* ---------------------------------------------------------------------- *)
(* let iter21 phi s = iteri (fun i x -> phi i (Some x) None) s *)
(* let iter22 phi t = iteri (fun j y -> phi j None (Some y)) t *)
(* let rec iter2 phi s t =
* match view s , view t with
* | Empty , _ -> iter22 phi t
* | _ , Empty -> iter21 phi s
* | Lf(i,x) , Lf(j,y) ->
* if K.equal i j then phi i (Some x) (Some y)
* else ( phi i (Some x) None ; phi j None (Some y) )
*
* | Lf(i,x) , Br(q,t0,t1) ->
* if match_prefix (K.tag i) q then
* (\* leaf i is in tree t *\)
* if zero_bit (K.tag i) q
* then (iter2 phi s t0 ; iter22 phi t1) (\* s=i is in t0 *\)
* else (iter22 phi t0 ; iter2 phi s t1) (\* s=i is in t1 *\)
* else
* (\* leaf i does not appear in t *\)
* (phi i (Some x) None ; iter22 phi t)
*
* | Br(p,s0,s1) , Lf(j,y) ->
* if match_prefix (K.tag j) p then
* (\* leaf j is in tree s *\)
* if zero_bit (K.tag j) p
* then (iter2 phi s0 t ; iter21 phi s1) (\* t=j is in s0 *\)
* else (iter21 phi s0 ; iter2 phi s1 t) (\* t=j is in s1 *\)
* else
* (\* leaf j does not appear in s *\)
* (iter21 phi s ; phi j None (Some y))
*
* | Br(p,s0,s1) , Br(q,t0,t1) ->
* if p == q then
* (\* prefixes agree *\)
* (iter2 phi s0 t0 ; iter2 phi s1 t1)
* else if included_prefix p q then
* (\* q contains p. Merge t with a subtree of s *\)
* if zero_bit q p
* then (\* t has bit m = 0 => t is inside s0 *\)
* (iter2 phi s0 t ; iter21 phi s1)
* else (\* t has bit m = 1 => t is inside s1 *\)
* (iter21 phi s0 ; iter2 phi s1 t)
* else if included_prefix q p then
* (\* p contains q. Merge s with a subtree of t *\)
* if zero_bit p q
* then (\* s has bit n = 0 => s is inside t0 *\)
* (iter2 phi s t0 ; iter22 phi t1)
* else (\* s has bit n = 1 => s is inside t1 *\)
* (iter22 phi t0 ; iter2 phi s t1)
* else
* (iter21 phi s ; iter22 phi t) *)
(* ---------------------------------------------------------------------- *)
(* --- Intersects --- *)
(* ---------------------------------------------------------------------- *)
(** TODO seems wrong *)
(* let rec intersectf phi s t =
* match view s , view t with
* | Empty , _ -> false
* | _ , Empty -> false
* | Lf(i,x) , Lf(j,y) -> if K.equal i j then phi i x y else false
* | Lf(i,x) , Br _ -> (match occur i t with None -> false
* | Some y -> phi i x y)
* | Br _ , Lf(j,y) -> (match occur j s with None -> false
* | Some x -> phi j x y)
* | Br(p,s0,s1) , Br(q,t0,t1) ->
* if p == q then
* (\* prefixes agree *\)
* (intersectf phi s0 t0) || (intersectf phi s1 t1)
* else if included_prefix p q then
* (\* q contains p. Intersect t with a subtree of s *\)
* if zero_bit q p
* then intersectf phi s0 t (\* t has bit m = 0 => t is inside s0 *\)
* else intersectf phi s1 t (\* t has bit m = 1 => t is inside s1 *\)
* else if included_prefix q p then
* (\* p contains q. Intersect s with a subtree of t *\)
* if zero_bit p q
* then intersectf phi s t0 (\* s has bit n = 0 => s is inside t0 *\)
* else intersectf phi s t1 (\* t has bit n = 1 => s is inside t1 *\)
* else
* (\* prefix disagree *\)
* false *)
let rec disjoint phi s t =
match view s , view t with
| Empty , _ -> true
| _ , Empty -> true
| Lf(i,x) , Lf(j,y) -> if K.equal i j then phi i x y else true
| Lf(i,x) , Br _ -> (match occur i t with None -> true
| Some y -> phi i x y)
| Br _ , Lf(j,y) -> (match occur j s with None -> true
| Some x -> phi j x y)
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
(disjoint phi s0 t0) && (disjoint phi s1 t1)
else if included_prefix p q then
(* q contains p. Intersect t with a subtree of s *)
if zero_bit q p
then disjoint phi s0 t (* t has bit m = 0 => t is inside s0 *)
else disjoint phi s1 t (* t has bit m = 1 => t is inside s1 *)
else if included_prefix q p then
(* p contains q. Intersect s with a subtree of t *)
if zero_bit p q
then disjoint phi s t0 (* s has bit n = 0 => s is inside t0 *)
else disjoint phi s t1 (* t has bit n = 1 => s is inside t1 *)
else
(* prefix disagree *)
true
(** fold2 *)
let fold21 phi m acc = fold (fun i x acc -> phi i (Some x) None acc) m acc
let fold22 phi m acc = fold (fun j y acc -> phi j None (Some y) acc) m acc
(* good sharing with s *)
let rec fold2_union:
type a b c.
(key -> a data option -> b data option -> c -> c) ->
a data t -> b data t -> c -> c
= fun phi s t acc ->
match view s , view t with
| Empty , _ -> fold22 phi t acc
| _ , Empty -> fold21 phi s acc
| Lf(i,x) , Lf(j,y) ->
let c = Stdlib.compare (K.tag i) (K.tag j) in
if c = 0
then phi i (Some x) (Some y) acc
else if c < 0 then phi j None (Some y) (phi i (Some x) None acc)
else (* c > 0 *) phi i (Some x) None (phi j None (Some y) acc)
| Lf(k,x) , Br(p,t1,t2) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
then fold22 phi t2 (fold2_union phi s t1 acc)
else fold2_union phi s t2 (fold22 phi t1 acc)
else
if side (K.tag k) p
then (* k p *) fold22 phi t (phi k (Some x) None acc)
else (* p k *) phi k (Some x) None (fold22 phi t acc)
| Br(p,s1,s2) , Lf(k,y) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
then fold21 phi s2 (fold2_union phi s1 t acc)
else fold2_union phi s2 t (fold21 phi s1 acc)
else
if side (K.tag k) p
then (* k p *) fold21 phi s (phi k None (Some y) acc)
else (* p k *) phi k None (Some y) (fold21 phi s acc)
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
fold2_union phi s1 t1 (fold2_union phi s0 t0 acc)
else if included_prefix p q then
(* q contains p. Merge t with a subtree of s *)
if zero_bit q p
then
(* t has bit m = 0 => t is inside s0 *)
fold21 phi s1 (fold2_union phi s0 t acc)
else
(* t has bit m = 1 => t is inside s1 *)
fold2_union phi s1 t (fold21 phi s0 acc)
else if included_prefix q p then
(* p contains q. Merge s with a subtree of t *)
if zero_bit p q
then
(* s has bit n = 0 => s is inside t0 *)
fold22 phi t1 (fold2_union phi s t0 acc)
else
(* t has bit n = 1 => s is inside t1 *)
fold2_union phi s t1 (fold22 phi t0 acc)
else
(* prefix disagree *)
if side p q
then (* p q *) fold22 phi t (fold21 phi s acc)
else (* q p *) fold21 phi s (fold22 phi t acc)
(* good sharing with s *)
let rec fold2_inter phi s t acc =
match view s , view t with
| Empty , _ -> acc
| _ , Empty -> acc
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then phi i x y acc
else acc
| Lf(k,x) , Br _ ->
begin match find_opt k t with
| Some y -> phi k x y acc
| None -> acc
end
| Br _ , Lf(k,y) ->
begin match find_opt k s with
| Some x -> phi k x y acc
| None -> acc
end
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
fold2_inter phi s1 t1 (fold2_inter phi s0 t0 acc)
else if included_prefix p q then
(* q contains p. Merge t with a subtree of s *)
if zero_bit q p
then
(* t has bit m = 0 => t is inside s0 *)
fold2_inter phi s0 t acc
else
(* t has bit m = 1 => t is inside s1 *)
fold2_inter phi s1 t acc
else if included_prefix q p then
(* p contains q. Merge s with a subtree of t *)
if zero_bit p q
then
(* s has bit n = 0 => s is inside t0 *)
fold2_inter phi s t0 acc
else
(* t has bit n = 1 => s is inside t1 *)
fold2_inter phi s t1 acc
else
(* prefix disagree *)
acc
(* ---------------------------------------------------------------------- *)
(* --- Subset --- *)
(* ---------------------------------------------------------------------- *)
let rec subsetf phi s t =
match view s , view t with
| Empty , _ -> true
| _ , Empty -> false
| Lf(i,x) , Lf(j,y) -> if K.equal i j then phi i x y else false
| Lf(i,x) , Br _ ->
(match occur i t with None -> false | Some y -> phi i x y)
| Br _ , Lf _ -> false
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
(subsetf phi s0 t0 && subsetf phi s1 t1)
else if included_prefix p q then
(* q contains p: t is included in a (strict) subtree of s *)
false
else if included_prefix q p then
(* p contains q: s is included in a subtree of t *)
if zero_bit p q
then subsetf phi s t0 (* s has bit n = 0 => s is inside t0 *)
else subsetf phi s t1 (* t has bit n = 1 => s is inside t1 *)
else
(* prefix disagree *)
false
(* let subset = subsetf
* let subsetk s t = subsetf (fun _i _x _y -> true) s t *)
let submap = subsetf
(* ---------------------------------------------------------------------- *)
let rec _pp_tree tab fmt t =
match view t with
| Empty -> ()
| Lf(k,_) ->
let k = K.tag k in
Format.fprintf fmt "%sL%a=%d" tab pp_bits k k
| Br(p,l,r) ->
let next = tab ^ " " in
_pp_tree next fmt l ;
Format.fprintf fmt "%s@@%a" tab (pp_mask (decode_mask p)) p ;
_pp_tree next fmt r
let is_num_elt n m =
try
fold (fun _ _ n -> if n < 0 then raise Exit else n-1) m n = 0
with Exit -> false
let of_list l =
List.fold_left (fun acc (k,d) -> add k d acc) empty l
let translate f m =
fold (fun k v acc -> add (f k) v acc) m empty
(** set_* *)
let set_union m1 m2 = unionf (fun _ x _ -> x) m1 m2
let set_inter m1 m2 = interf (fun _ x _ -> x) m1 m2
let set_diff m1 m2 = diff (fun _ _ _ -> None) m1 m2
let set_submap m1 m2 = submap (fun _ _ _ -> true) m1 m2
let set_disjoint m1 m2 = disjoint (fun _ _ _ -> false) m1 m2
let set_compare m1 m2 = compare (fun _ _ -> 0) m1 m2
let set_equal m1 m2 = equal (fun _ _ -> true) m1 m2
(** the goal is to choose randomly but often the same than [choose] *)
let choose_rnd f m =
let rec aux f m ret =
match view m with
| Empty -> ()
| Lf(k,v) -> if f () then (ret := (k,v); raise Exit)
| Br(_,t1,t2) ->
aux f t1 ret; aux f t2 ret
in
let ret = ref (Obj.magic 0) in
try
begin match view m with (* in order to be sorted *)
| Empty -> raise Not_found
| Br(p,_,t1) when p = max_int -> aux f t1 ret
| _ -> aux f m ret
end;
choose m
with Exit -> !ret
(** Enumeration *)
type 'a enumeration =
| EEmpty
| ELf of K.t * 'a * 'a enum2
and 'a enum2 =
| End
| EBr of 'a t * 'a enum2
let rec cons_enum m e =
match view m with
| Empty -> assert false (** absurd: Empty can appear only a toplevel *)
| Lf(i,x) -> ELf(i,x,e)
| Br(_,t1,t2) -> cons_enum t1 (EBr(t2,e))
let start_enum m = (* in order to be sorted *)
match view m with
| Empty -> EEmpty
| Lf(i,x) -> ELf(i,x,End)
| Br(p,t1,t2) when p = max_int -> cons_enum t2 (EBr(t1, End))
| Br(_,t1,t2) -> cons_enum t1 (EBr(t2, End))
let val_enum = function
| EEmpty -> None
| ELf(i,x,_) -> Some (i,x)
let next_enum_br = function
| End -> EEmpty
| EBr(t2,e) -> cons_enum t2 e
let next_enum = function
| EEmpty -> EEmpty
| ELf(_,_,e) -> next_enum_br e
let rec cons_ge_enum k m e =
match view m with
| Empty -> assert false (** absurd: Empty can appear only a toplevel *)
| Lf(i,x) ->
if side (K.tag i) (K.tag k)
then (* i k *) next_enum_br e
else (* k i *) ELf(i,x,e)
| Br(p,t1,t2) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
then cons_ge_enum k t1 (EBr(t2,e))
else cons_ge_enum k t2 e
else
if side (K.tag k) p
then (* k p *) cons_enum t1 (EBr(t2,e))
else (* p k *) next_enum_br e
let start_ge_enum k m =
match view m with
| Empty -> EEmpty
| Br(p,t1,t2) when p = max_int ->
if zero_bit (K.tag k) p
then cons_ge_enum k t1 End
else cons_ge_enum k t2 (EBr(t1,End))
| _ -> cons_ge_enum k m End
let rec next_ge_enum_br k = function
| End -> EEmpty
| EBr(t,e) -> match view t with
| Empty -> assert false (** absurd: Empty only at top *)
| Lf(i,d) when (K.tag k) <= (K.tag i) -> ELf(i,d,e)
| Lf(_,_) -> next_ge_enum_br k e
| Br(p,t1,t2) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
then cons_ge_enum k t1 (EBr(t2,e))
else cons_ge_enum k t2 e
else
if side (K.tag k) p
then (* k p *) cons_enum t1 (EBr(t2,e))
else (* p k *) next_ge_enum_br k e
let next_ge_enum k = function
| EEmpty -> EEmpty
| ELf(i,_,_) as e when (K.tag k) <= (K.tag i)-> e
| ELf(_,_,e) -> next_ge_enum_br k e
let change f k m = change (fun _ () v -> f v) k () m
let add_opt x o m =
match o with
| None -> remove x m
| Some y -> add x y m
(** TODO more checks? *)
let check_invariant m =
match view m with
| Empty -> true
| _ ->
let rec aux m =
match view m with
| Empty -> false
| Lf _ -> true
| Br (_,t1,t2) -> aux t1 && aux t2 in
aux m
let pp pp =
if pp == Fmt.nop || pp == Pp.nothing then
Pp.iter2 iter Pp.comma Fmt.nop
K.pp Fmt.nop
else
Pp.iter2 iter Pp.comma Pp.arrow
K.pp pp
end
module Def = struct
type 'a t =
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
end
module NT = struct
module M : sig
type 'a t = 'a Def.t
type 'a data = 'a
type 'a view = private
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
val view: 'a data t -> 'a data view
val ktag : 'a data t -> int
val mk_Empty: 'a data t
val mk_Lf: K.t -> 'a data -> 'a data t
val mk_Br: int -> 'a data t -> 'a data t -> 'a data t
end = struct
type 'a t = 'a Def.t
type 'a data = 'a
let ktag = function
| Def.Empty -> assert false (** absurd: precondition: not Empty *)
| Def.Lf(i,_) -> K.tag i
| Def.Br(i,_,_) -> i
let mk_Empty = Def.Empty
let mk_Lf k d = Def.Lf(k,d)
let mk_Br i t1 t2 =
(* assert (t1 != Def.Empty && t2 != Def.Empty); *)
Def.Br(i,t1,t2)
type 'a view = 'a Def.t =
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
let view x = x
end
include Gen(M)
let hash_fold_t h s t =
fold (fun k v s -> (Base.Hash.fold_int (h s v) (K.tag k))) t s
end
module Make(Data: Map_intf.HashType) :
Map_intf.Map_hashcons with type 'a data = Data.t
and type 'a poly := 'a NT.t
and type key = K.t = struct
(** Tag *)
module Tag: sig
type t
type gen
val mk_gen: unit -> gen
val to_int: t -> int
val dtag : t
val next_tag: gen -> t
val incr_tag: gen -> unit
(** all of them are different from dtag *)
end = struct
type t = int
type gen = int ref
let to_int x = x
let dtag = min_int (** tag used in the polymorphic non hashconsed case *)
let mk_gen () = ref (min_int + 1)
let next_tag gen = !gen
let incr_tag gen = incr gen; assert (!gen != dtag)
end
module M : sig
type (+'a) t
type 'a data = Data.t
val nt: 'a data t -> 'a data NT.t
val rebuild: 'a data NT.t -> 'a data t
type 'a view = private
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
val view: 'a data t -> 'a data view
val tag : 'a data t -> int
val ktag : 'a data t -> int
val mk_Empty: 'a data t
val mk_Lf: K.t -> 'a data -> 'a data t
val mk_Br: int -> 'a data t -> 'a data t -> 'a data t
end = struct
module Check = struct
type 'a def = 'a Def.t = (** check the type of Def.t *)
| Empty
| Lf of K.t * 'a
| Br of int * 'a def * 'a def
end
type 'a t =
| Empty
| Lf of K.t * 'a * Tag.t
| Br of int * 'a t * 'a t * Tag.t
type 'a data = Data.t
(** This obj.magic "just" hide the last field *)
let nt x = (Obj.magic (x : 'a t) : 'a Check.def)
let tag = function
| Empty -> Tag.to_int Tag.dtag
| Lf(_,_,tag) | Br(_,_,_,tag) -> Tag.to_int tag
let ktag = function
| Empty -> assert false (** absurd: Should'nt be used on Empty *)
| Lf(k,_,_) -> K.tag k
| Br(i,_,_,_) -> i
module WH = Weak.Make(struct
type 'a t' = 'a t
type t = Data.t t'
let equal x y =
match x, y with
| Empty, Empty -> true
| Lf(i1,d1,_), Lf(i2,d2,_) ->
K.equal i1 i2 && Data.equal d1 d2
| Br(_,l1,r1,_), Br(_,l2,r2,_) -> l1 == l2 && r1 == r2
| _ -> false
let hash = function
| Empty -> 0
| Lf(i1,d1,_) ->
65599 * ((K.tag i1) + (Data.hash d1 * 65599 + 31))
| Br(_,l,r,_) ->
65599 * ((tag l) + ((tag r) * 65599 + 17))
end)
let gentag = Tag.mk_gen ()
let htable = WH.create 5003
let hashcons d =
let o = WH.merge htable d in
if o == d then Tag.incr_tag gentag;
o
let mk_Empty = Empty
let mk_Lf k x = hashcons (Lf(k,x,Tag.next_tag gentag))
let mk_Br k t0 t1 =
(* assert (t0 != Empty && t1 != Empty); *)
hashcons (Br(k,t0,t1,Tag.next_tag gentag))
let rec rebuild t = match t with
| Def.Empty -> mk_Empty
| Def.Lf(i,d) -> mk_Lf i d
| Def.Br(i,l,r) -> mk_Br i (rebuild l) (rebuild r)
type 'a view =
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
(** implementation without obj but with copy of the next function *)
let _view_ : 'a t -> 'a view = function
| Empty -> Empty
| Lf(k,v,_) -> Lf(k,v)
| Br(i,t1,t2,_) -> Br(i,t1,t2)
(** This obj.magic "just" hide the last field of the root node *)
let view x = (Obj.magic (x : 'a t): 'a view)
end
include Gen(M)
let mk_Empty = M.mk_Empty
let mk_Lf = M.mk_Lf
let nt = M.nt
let rebuild = M.rebuild
let compare_t s t = Stdlib.compare (M.tag s) (M.tag t)
let equal_t (s:'a data t) t = s == t
(** with Def.t *)
let rec interi_nt lf_phi s t =
match M.view s , t with
| M.Empty , _ -> mk_Empty
| _ , Def.Empty -> mk_Empty
| M.Lf(i,x) , Def.Lf(j,y) ->
if K.equal i j
then lf_phi i x y
else mk_Empty
| M.Lf(i,x) , Def.Br _ ->
(match NT.occur i t with None -> mk_Empty | Some y -> lf_phi i x y)
| M.Br _ , Def.Lf(j,y) ->
(match occur j s with None -> mk_Empty | Some x -> lf_phi j x y)
| M.Br(p,s0,s1) , Def.Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
glue (interi_nt lf_phi s0 t0) (interi_nt lf_phi s1 t1)
else if included_prefix p q then
(* q contains p. Intersect t with a subtree of s *)
if zero_bit q p
then interi_nt lf_phi s0 t (* t has bit m = 0 => t is inside s0 *)
else interi_nt lf_phi s1 t (* t has bit m = 1 => t is inside s1 *)
else if included_prefix q p then
(* p contains q. Intersect s with a subtree of t *)
if zero_bit p q
then interi_nt lf_phi s t0 (* s has bit n = 0 => s is inside t0 *)
else interi_nt lf_phi s t1 (* t has bit n = 1 => s is inside t1 *)
else
(* prefix disagree *)
mk_Empty
let inter_nt phi = interi_nt (fun i x y -> mk_Lf i (phi i x y))
let interf_nt phi = interi_nt (fun i x y -> lf i (phi i x y))
let set_inter_nt m1 m2 = interi_nt (fun i x _ -> mk_Lf i x) m1 m2
let hash_fold_t h s t =
fold (fun k v s -> (Base.Hash.fold_int (h s v) (K.tag k))) t s
end
end
| (*************************************************************************)
(* *)
(* This file is part of Frama-C. *)
(* *)
(* Copyright (C) 2007-2017 *)
(* CEA (Commissariat à l'énergie atomique et aux énergies *)
(* alternatives) *)
(* *)
(* 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). *)
(* *)
(*************************************************************************)
|
spacer_expand_bnd_generalizer.h |
#pragma once
/*++
Copyright (c) 2020 Arie Gurfinkel
Module Name:
spacer_expand_bnd_generalizer.h
Abstract:
Strengthen lemmas by changing numeral constants inside arithmetic literals
Author:
Hari Govind V K
Arie Gurfinkel
--*/
#include "muz/spacer/spacer_context.h"
namespace spacer {
class lemma_expand_bnd_generalizer : public lemma_generalizer {
struct stats {
unsigned atmpts;
unsigned success;
stopwatch watch;
stats() { reset(); }
void reset() {
watch.reset();
atmpts = 0;
success = 0;
}
};
stats m_st;
ast_manager &m;
arith_util m_arith;
/// A set of numeral values that can be used to expand bound
vector<rational> m_values;
public:
lemma_expand_bnd_generalizer(context &ctx);
~lemma_expand_bnd_generalizer() override {}
void operator()(lemma_ref &lemma) override;
void collect_statistics(statistics &st) const override;
void reset_statistics() override { m_st.reset(); }
private:
/// Check whether lit ==> lit[val |--> n] (barring special cases). That is,
/// whether \p lit becomes weaker if \p val is replaced with \p n
///
/// \p lit has to be of the form t <= v where v is a numeral.
/// Special cases:
/// In the trivial case in which \p val == \p n, return false.
/// if lit is an equality or the negation of an equality, return true.
bool is_interesting(const expr *lit, rational val, rational n);
/// check whether \p conj is a possible generalization for \p lemma.
/// update \p lemma if it is.
bool check_inductive(lemma_ref &lemma, expr_ref_vector &candiate);
};
} // namespace spacer
| |
dune |
(library
(name dune_site_private)
(libraries dune-private-libs.dune-section)
(public_name dune-site.private))
| |
argument_parser.mli |
open Module_types
module type S =
sig
type a (* The result of the argument parser *)
type key = string (* option key, must start with '-' *)
type doc = string (* option description *)
type spec (* specification of an option *)
=
| Unit of (a -> a) (* option with no argument *)
| String of (string -> a -> a) (* option with string argument *)
| Int of (int -> a -> a) (* option with integer argument *)
type anon = string -> a -> a (* function taking an anonymus argument into
the result *)
type error =
| Unknown_option of string
| Missing_argument of key*spec*doc
| Invalid_argument of key*spec*doc*string
val parse: string array ->
a ->
(key*spec*doc) list ->
anon ->
(a,error) result
val string_of_error: error -> string
val argument_type: spec -> string
end
module Make (A:ANY): S with type a = A.t
| |
t-mul_array_threaded.c |
#include <stdio.h>
#include <stdlib.h>
#include "nmod_mpoly.h"
#include "ulong_extras.h"
int
main(void)
{
int i, j, result, max_threads = 5;
int tmul = 50;
#ifdef _WIN32
tmul = 1;
#endif
FLINT_TEST_INIT(state);
flint_printf("mul_array_threaded....");
fflush(stdout);
/* Check mul_array_threaded matches mul_johnson */
for (i = 0; i < tmul * flint_test_multiplier(); i++)
{
nmod_mpoly_ctx_t ctx;
nmod_mpoly_t f, g, h, k;
slong len, len1, len2, exp_bound, exp_bound1, exp_bound2;
slong n, max_bound;
mp_limb_t modulus;
modulus = n_randint(state, SMALL_FMPZ_BITCOUNT_MAX) + 2;
modulus = n_randbits(state, modulus);
nmod_mpoly_ctx_init_rand(ctx, state, 5, modulus);
nmod_mpoly_init(f, ctx);
nmod_mpoly_init(g, ctx);
nmod_mpoly_init(h, ctx);
nmod_mpoly_init(k, ctx);
len = n_randint(state, 100);
len1 = n_randint(state, 100);
len2 = n_randint(state, 100);
max_bound = ctx->minfo->ord == ORD_LEX ? 200 : 100;
n = FLINT_MAX(WORD(1), ctx->minfo->nvars);
max_bound = max_bound/n/n;
exp_bound = n_randint(state, max_bound) + 1;
exp_bound1 = n_randint(state, max_bound) + 1;
exp_bound2 = n_randint(state, max_bound) + 1;
for (j = 0; j < 4; j++)
{
nmod_mpoly_randtest_bound(f, state, len1, exp_bound1, ctx);
nmod_mpoly_randtest_bound(g, state, len2, exp_bound2, ctx);
nmod_mpoly_randtest_bound(h, state, len, exp_bound, ctx);
nmod_mpoly_randtest_bound(k, state, len, exp_bound, ctx);
flint_set_num_threads(n_randint(state, max_threads) + 1);
nmod_mpoly_mul_johnson(h, f, g, ctx);
nmod_mpoly_assert_canonical(h, ctx);
result = nmod_mpoly_mul_array_threaded(k, f, g, ctx);
if (!result)
{
continue;
}
nmod_mpoly_assert_canonical(k, ctx);
result = nmod_mpoly_equal(h, k, ctx);
if (!result)
{
printf("FAIL\n");
flint_printf("Check mul_array_threaded matches mul_johnson\ni = %wd, j = %wd\n", i, j);
fflush(stdout);
flint_abort();
}
}
nmod_mpoly_clear(f, ctx);
nmod_mpoly_clear(g, ctx);
nmod_mpoly_clear(h, ctx);
nmod_mpoly_clear(k, ctx);
nmod_mpoly_ctx_clear(ctx);
}
/* Check aliasing first argument */
for (i = 0; i < tmul * flint_test_multiplier(); i++)
{
nmod_mpoly_ctx_t ctx;
nmod_mpoly_t f, g, h;
slong len, len1, len2, exp_bound, exp_bound1, exp_bound2;
slong n, max_bound;
mp_limb_t modulus;
modulus = n_randint(state, SMALL_FMPZ_BITCOUNT_MAX) + 2;
modulus = n_randbits(state, modulus);
nmod_mpoly_ctx_init_rand(ctx, state, 10, modulus);
nmod_mpoly_init(f, ctx);
nmod_mpoly_init(g, ctx);
nmod_mpoly_init(h, ctx);
len = n_randint(state, 50);
len1 = n_randint(state, 50);
len2 = n_randint(state, 50);
n = FLINT_MAX(WORD(1), ctx->minfo->nvars);
max_bound = 200/n/n;
exp_bound = n_randint(state, max_bound) + 1;
exp_bound1 = n_randint(state, max_bound) + 1;
exp_bound2 = n_randint(state, max_bound) + 1;
for (j = 0; j < 4; j++)
{
nmod_mpoly_randtest_bound(f, state, len1, exp_bound1, ctx);
nmod_mpoly_randtest_bound(g, state, len2, exp_bound2, ctx);
nmod_mpoly_randtest_bound(h, state, len, exp_bound, ctx);
flint_set_num_threads(n_randint(state, max_threads) + 1);
nmod_mpoly_mul_johnson(h, f, g, ctx);
nmod_mpoly_assert_canonical(h, ctx);
result = nmod_mpoly_mul_array_threaded(f, f, g, ctx);
if (!result)
continue;
nmod_mpoly_assert_canonical(f, ctx);
result = nmod_mpoly_equal(h, f, ctx);
if (!result)
{
printf("FAIL\n");
flint_printf("Check aliasing first argument\ni = %wd, j = %wd\n", i, j);
fflush(stdout);
flint_abort();
}
}
nmod_mpoly_clear(f, ctx);
nmod_mpoly_clear(g, ctx);
nmod_mpoly_clear(h, ctx);
nmod_mpoly_ctx_clear(ctx);
}
/* Check aliasing second argument */
for (i = 0; i < tmul * flint_test_multiplier(); i++)
{
nmod_mpoly_ctx_t ctx;
nmod_mpoly_t f, g, h;
slong len, len1, len2, exp_bound, exp_bound1, exp_bound2;
slong n, max_bound;
mp_limb_t modulus;
modulus = n_randint(state, SMALL_FMPZ_BITCOUNT_MAX) + 2;
modulus = n_randbits(state, modulus);
nmod_mpoly_ctx_init_rand(ctx, state, 10, modulus);
nmod_mpoly_init(f, ctx);
nmod_mpoly_init(g, ctx);
nmod_mpoly_init(h, ctx);
len = n_randint(state, 50);
len1 = n_randint(state, 50);
len2 = n_randint(state, 50);
n = FLINT_MAX(WORD(1), ctx->minfo->nvars);
max_bound = 200/n/n;
exp_bound = n_randint(state, max_bound) + 1;
exp_bound1 = n_randint(state, max_bound) + 1;
exp_bound2 = n_randint(state, max_bound) + 1;
for (j = 0; j < 4; j++)
{
nmod_mpoly_randtest_bound(f, state, len1, exp_bound1, ctx);
nmod_mpoly_randtest_bound(g, state, len2, exp_bound2, ctx);
nmod_mpoly_randtest_bound(h, state, len, exp_bound, ctx);
flint_set_num_threads(n_randint(state, max_threads) + 1);
nmod_mpoly_mul_johnson(h, f, g, ctx);
nmod_mpoly_assert_canonical(h, ctx);
result = nmod_mpoly_mul_array_threaded(g, f, g, ctx);
if (!result)
continue;
nmod_mpoly_assert_canonical(g, ctx);
result = nmod_mpoly_equal(h, g, ctx);
if (!result)
{
printf("FAIL\n");
flint_printf("Check aliasing second argument\ni = %wd, j = %wd\n", i, j);
fflush(stdout);
flint_abort();
}
}
nmod_mpoly_clear(f, ctx);
nmod_mpoly_clear(g, ctx);
nmod_mpoly_clear(h, ctx);
nmod_mpoly_ctx_clear(ctx);
}
FLINT_TEST_CLEANUP(state);
flint_printf("PASS\n");
return 0;
}
| /*
Copyright (C) 2019 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/>.
*/ |
printtyp.ml | (* Printing functions *)
open Misc
open Ctype
open Format
open Longident
open Path
open Asttypes
open Types
open Btype
open Outcometree
module String = Misc.Stdlib.String
(* Print a long identifier *)
let rec longident ppf = function
| Lident s -> pp_print_string ppf s
| Ldot(p, s) -> fprintf ppf "%a.%s" longident p s
| Lapply(p1, p2) -> fprintf ppf "%a(%a)" longident p1 longident p2
let () = Env.print_longident := longident
(* Print an identifier avoiding name collisions *)
module Out_name = struct
let create x = { printed_name = x }
let print x = x.printed_name
let set out_name x = out_name.printed_name <- x
end
(** Some identifiers may require hiding when printing *)
type bound_ident = { hide:bool; ident:Ident.t }
(* printing environment for path shortening and naming *)
let printing_env = ref Env.empty
(* When printing, it is important to only observe the
current printing environment, without reading any new
cmi present on the file system *)
let in_printing_env f = Env.without_cmis f !printing_env
let human_unique n id = Printf.sprintf "%s/%d" (Ident.name id) n
type namespace =
| Type
| Module
| Module_type
| Class
| Class_type
| Other (** Other bypasses the unique name identifier mechanism *)
module Namespace = struct
let id = function
| Type -> 0
| Module -> 1
| Module_type -> 2
| Class -> 3
| Class_type -> 4
| Other -> 5
let size = 1 + id Other
let show =
function
| Type -> "type"
| Module -> "module"
| Module_type -> "module type"
| Class -> "class"
| Class_type -> "class type"
| Other -> ""
let pp ppf x = Format.pp_print_string ppf (show x)
(** The two functions below should never access the filesystem,
and thus use {!in_printing_env} rather than directly
accessing the printing environment *)
let lookup =
let to_lookup f lid = fst @@ in_printing_env (f (Lident lid)) in
function
| Type -> to_lookup Env.find_type_by_name
| Module -> to_lookup Env.find_module_by_name
| Module_type -> to_lookup Env.find_modtype_by_name
| Class -> to_lookup Env.find_class_by_name
| Class_type -> to_lookup Env.find_cltype_by_name
| Other -> fun _ -> raise Not_found
let location namespace id =
let path = Path.Pident id in
try Some (
match namespace with
| Type -> (in_printing_env @@ Env.find_type path).type_loc
| Module -> (in_printing_env @@ Env.find_module path).md_loc
| Module_type -> (in_printing_env @@ Env.find_modtype path).mtd_loc
| Class -> (in_printing_env @@ Env.find_class path).cty_loc
| Class_type -> (in_printing_env @@ Env.find_cltype path).clty_loc
| Other -> Location.none
) with Not_found -> None
let best_class_namespace = function
| Papply _ | Pdot _ -> Module
| Pident c ->
match location Class c with
| Some _ -> Class
| None -> Class_type
end
(** {2 Conflicts printing}
Conflicts arise when multiple items are attributed the same name,
the following module stores the global conflict references and
provides the printing functions for explaining the source of
the conflicts.
*)
module Conflicts = struct
module M = String.Map
type explanation =
{ kind: namespace; name:string; root_name:string; location:Location.t}
let explanations = ref M.empty
let collect_explanation namespace n id =
let name = human_unique n id in
let root_name = Ident.name id in
if not (M.mem name !explanations) then
match Namespace.location namespace id with
| None -> ()
| Some location ->
let explanation = { kind = namespace; location; name; root_name } in
explanations := M.add name explanation !explanations
let pp_explanation ppf r=
Format.fprintf ppf "@[<v 2>%a:@,Definition of %s %s@]"
Location.print_loc r.location (Namespace.show r.kind) r.name
let print_located_explanations ppf l =
Format.fprintf ppf "@[<v>%a@]" (Format.pp_print_list pp_explanation) l
let reset () = explanations := M.empty
let list_explanations () =
let c = !explanations in
reset ();
c |> M.bindings |> List.map snd |> List.sort Stdlib.compare
let print_toplevel_hint ppf l =
let conj ppf () = Format.fprintf ppf " and@ " in
let pp_namespace_plural ppf n = Format.fprintf ppf "%as" Namespace.pp n in
let root_names = List.map (fun r -> r.kind, r.root_name) l in
let unique_root_names = List.sort_uniq Stdlib.compare root_names in
let submsgs = Array.make Namespace.size [] in
let () = List.iter (fun (n,_ as x) ->
submsgs.(Namespace.id n) <- x :: submsgs.(Namespace.id n)
) unique_root_names in
let pp_submsg ppf names =
match names with
| [] -> ()
| [namespace, a] ->
Format.fprintf ppf
"@ \
@[<2>Hint: The %a %s has been defined multiple times@ \
in@ this@ toplevel@ session.@ \
Some toplevel values still refer to@ old@ versions@ of@ this@ %a.\
@ Did you try to redefine them?@]"
Namespace.pp namespace a Namespace.pp namespace
| (namespace, _) :: _ :: _ ->
Format.fprintf ppf
"@ \
@[<2>Hint: The %a %a have been defined multiple times@ \
in@ this@ toplevel@ session.@ \
Some toplevel values still refer to@ old@ versions@ of@ those@ %a.\
@ Did you try to redefine them?@]"
pp_namespace_plural namespace
Format.(pp_print_list ~pp_sep:conj pp_print_string) (List.map snd names)
pp_namespace_plural namespace in
Array.iter (pp_submsg ppf) submsgs
let print_explanations ppf =
let ltop, l =
(* isolate toplevel locations, since they are too imprecise *)
let from_toplevel a =
a.location.Location.loc_start.Lexing.pos_fname = "//toplevel//" in
List.partition from_toplevel (list_explanations ())
in
begin match l with
| [] -> ()
| l -> Format.fprintf ppf "@,%a" print_located_explanations l
end;
(* if there are name collisions in a toplevel session,
display at least one generic hint by namespace *)
print_toplevel_hint ppf ltop
let exists () = M.cardinal !explanations >0
end
module Naming_context = struct
module M = String.Map
module S = String.Set
let enabled = ref true
let enable b = enabled := b
(** Name mapping *)
type mapping =
| Need_unique_name of int Ident.Map.t
(** The same name has already been attributed to multiple types.
The [map] argument contains the specific binding time attributed to each
types.
*)
| Uniquely_associated_to of Ident.t * out_name
(** For now, the name [Ident.name id] has been attributed to [id],
[out_name] is used to expand this name if a conflict arises
at a later point
*)
| Associated_to_pervasives of out_name
(** [Associated_to_pervasives out_name] is used when the item
[Stdlib.$name] has been associated to the name [$name].
Upon a conflict, this name will be expanded to ["Stdlib." ^ name ] *)
let hid_start = 0
let add_hid_id id map =
let new_id = 1 + Ident.Map.fold (fun _ -> Int.max) map hid_start in
new_id, Ident.Map.add id new_id map
let find_hid id map =
try Ident.Map.find id map, map with
Not_found -> add_hid_id id map
let pervasives name = "Stdlib." ^ name
let map = Array.make Namespace.size M.empty
let get namespace = map.(Namespace.id namespace)
let set namespace x = map.(Namespace.id namespace) <- x
(* Names used in recursive definitions are not considered when determining
if a name is already attributed in the current environment.
This is a complementary version of hidden_rec_items used by short-path. *)
let protected = ref S.empty
(* When dealing with functor arguments, identity becomes fuzzy because the same
syntactic argument may be represented by different identifers during the
error processing, we are thus disabling disambiguation on the argument name
*)
let fuzzy = ref S.empty
let with_arg id f =
protect_refs [ R(fuzzy, S.add (Ident.name id) !fuzzy) ] f
let fuzzy_id namespace id = namespace = Module && S.mem (Ident.name id) !fuzzy
let with_hidden ids f =
let update m id = S.add (Ident.name id.ident) m in
protect_refs [ R(protected, List.fold_left update !protected ids)] f
let pervasives_name namespace name =
if not !enabled then Out_name.create name else
match M.find name (get namespace) with
| Associated_to_pervasives r -> r
| Need_unique_name _ -> Out_name.create (pervasives name)
| Uniquely_associated_to (id',r) ->
let hid, map = add_hid_id id' Ident.Map.empty in
Out_name.set r (human_unique hid id');
Conflicts.collect_explanation namespace hid id';
set namespace @@ M.add name (Need_unique_name map) (get namespace);
Out_name.create (pervasives name)
| exception Not_found ->
let r = Out_name.create name in
set namespace @@ M.add name (Associated_to_pervasives r) (get namespace);
r
(** Lookup for preexisting named item within the current {!printing_env} *)
let env_ident namespace name =
if S.mem name !protected then None else
match Namespace.lookup namespace name with
| Pident id -> Some id
| _ -> None
| exception Not_found -> None
(** Associate a name to the identifier [id] within [namespace] *)
let ident_name_simple namespace id =
if not !enabled || fuzzy_id namespace id then
Out_name.create (Ident.name id)
else
let name = Ident.name id in
match M.find name (get namespace) with
| Uniquely_associated_to (id',r) when Ident.same id id' ->
r
| Need_unique_name map ->
let hid, m = find_hid id map in
Conflicts.collect_explanation namespace hid id;
set namespace @@ M.add name (Need_unique_name m) (get namespace);
Out_name.create (human_unique hid id)
| Uniquely_associated_to (id',r) ->
let hid', m = find_hid id' Ident.Map.empty in
let hid, m = find_hid id m in
Out_name.set r (human_unique hid' id');
List.iter (fun (id,hid) -> Conflicts.collect_explanation namespace hid id)
[id, hid; id', hid' ];
set namespace @@ M.add name (Need_unique_name m) (get namespace);
Out_name.create (human_unique hid id)
| Associated_to_pervasives r ->
Out_name.set r ("Stdlib." ^ Out_name.print r);
let hid, m = find_hid id Ident.Map.empty in
set namespace @@ M.add name (Need_unique_name m) (get namespace);
Out_name.create (human_unique hid id)
| exception Not_found ->
let r = Out_name.create name in
set namespace
@@ M.add name (Uniquely_associated_to (id,r) ) (get namespace);
r
(** Same as {!ident_name_simple} but lookup to existing named identifiers
in the current {!printing_env} *)
let ident_name namespace id =
begin match env_ident namespace (Ident.name id) with
| Some id' -> ignore (ident_name_simple namespace id')
| None -> ()
end;
ident_name_simple namespace id
let reset () =
Array.iteri ( fun i _ -> map.(i) <- M.empty ) map
let with_ctx f =
let old = Array.copy map in
try_finally f
~always:(fun () -> Array.blit old 0 map 0 (Array.length map))
end
let ident_name = Naming_context.ident_name
let reset_naming_context = Naming_context.reset
let ident ppf id = pp_print_string ppf
(Out_name.print (Naming_context.ident_name_simple Other id))
(* Print a path *)
let ident_stdlib = Ident.create_persistent "Stdlib"
let non_shadowed_pervasive = function
| Pdot(Pident id, s) as path ->
Ident.same id ident_stdlib &&
(match in_printing_env (Env.find_type_by_name (Lident s)) with
| (path', _) -> Path.same path path'
| exception Not_found -> true)
| _ -> false
let find_double_underscore s =
let len = String.length s in
let rec loop i =
if i + 1 >= len then
None
else if s.[i] = '_' && s.[i + 1] = '_' then
Some i
else
loop (i + 1)
in
loop 0
let rec module_path_is_an_alias_of env path ~alias_of =
match Env.find_module path env with
| { md_type = Mty_alias path'; _ } ->
Path.same path' alias_of ||
module_path_is_an_alias_of env path' ~alias_of
| _ -> false
| exception Not_found -> false
(* Simple heuristic to print Foo__bar.* as Foo.Bar.* when Foo.Bar is an alias
for Foo__bar. This pattern is used by the stdlib. *)
let rec rewrite_double_underscore_paths env p =
match p with
| Pdot (p, s) ->
Pdot (rewrite_double_underscore_paths env p, s)
| Papply (a, b) ->
Papply (rewrite_double_underscore_paths env a,
rewrite_double_underscore_paths env b)
| Pident id ->
let name = Ident.name id in
match find_double_underscore name with
| None -> p
| Some i ->
let better_lid =
Ldot
(Lident (String.sub name 0 i),
String.capitalize_ascii
(String.sub name (i + 2) (String.length name - i - 2)))
in
match Env.find_module_by_name better_lid env with
| exception Not_found -> p
| p', _ ->
if module_path_is_an_alias_of env p' ~alias_of:p then
p'
else
p
let rewrite_double_underscore_paths env p =
if env == Env.empty then
p
else
rewrite_double_underscore_paths env p
let rec tree_of_path namespace = function
| Pident id ->
Oide_ident (ident_name namespace id)
| Pdot(_, s) as path when non_shadowed_pervasive path ->
Oide_ident (Naming_context.pervasives_name namespace s)
| Pdot(Pident t, s)
when namespace=Type && not (Path.is_uident (Ident.name t)) ->
(* [t.A]: inline record of the constructor [A] from type [t] *)
Oide_dot (Oide_ident (ident_name Type t), s)
| Pdot(p, s) ->
Oide_dot (tree_of_path Module p, s)
| Papply(p1, p2) ->
Oide_apply (tree_of_path Module p1, tree_of_path Module p2)
let tree_of_path namespace p =
tree_of_path namespace (rewrite_double_underscore_paths !printing_env p)
let path ppf p =
!Oprint.out_ident ppf (tree_of_path Other p)
let string_of_path p =
Format.asprintf "%a" path p
let strings_of_paths namespace p =
reset_naming_context ();
let trees = List.map (tree_of_path namespace) p in
List.map (Format.asprintf "%a" !Oprint.out_ident) trees
let () = Env.print_path := path
(* Print a recursive annotation *)
let tree_of_rec = function
| Trec_not -> Orec_not
| Trec_first -> Orec_first
| Trec_next -> Orec_next
(* Print a raw type expression, with sharing *)
let raw_list pr ppf = function
[] -> fprintf ppf "[]"
| a :: l ->
fprintf ppf "@[<1>[%a%t]@]" pr a
(fun ppf -> List.iter (fun x -> fprintf ppf ";@,%a" pr x) l)
let kind_vars = ref []
let kind_count = ref 0
let rec safe_kind_repr v = function
Fvar {contents=Some k} ->
if List.memq k v then "Fvar loop" else
safe_kind_repr (k::v) k
| Fvar r ->
let vid =
try List.assq r !kind_vars
with Not_found ->
let c = incr kind_count; !kind_count in
kind_vars := (r,c) :: !kind_vars;
c
in
Printf.sprintf "Fvar {None}@%d" vid
| Fpresent -> "Fpresent"
| Fabsent -> "Fabsent"
let rec safe_commu_repr v = function
Cok -> "Cok"
| Cunknown -> "Cunknown"
| Clink r ->
if List.memq r v then "Clink loop" else
safe_commu_repr (r::v) !r
let rec safe_repr v = function
{desc = Tlink t} when not (List.memq t v) ->
safe_repr (t::v) t
| t -> t
let rec list_of_memo = function
Mnil -> []
| Mcons (_priv, p, _t1, _t2, rem) -> p :: list_of_memo rem
| Mlink rem -> list_of_memo !rem
let print_name ppf = function
None -> fprintf ppf "None"
| Some name -> fprintf ppf "\"%s\"" name
let string_of_label = function
Nolabel -> ""
| Labelled s -> s
| Optional s -> "?"^s
let visited = ref []
let rec raw_type ppf ty =
let ty = safe_repr [] ty in
if List.memq ty !visited then fprintf ppf "{id=%d}" ty.id else begin
visited := ty :: !visited;
fprintf ppf "@[<1>{id=%d;level=%d;scope=%d;desc=@,%a}@]" ty.id ty.level
ty.scope raw_type_desc ty.desc
end
and raw_type_list tl = raw_list raw_type tl
and raw_type_desc ppf = function
Tvar name -> fprintf ppf "Tvar %a" print_name name
| Tarrow(l,t1,t2,c) ->
fprintf ppf "@[<hov1>Tarrow(\"%s\",@,%a,@,%a,@,%s)@]"
(string_of_label l) raw_type t1 raw_type t2
(safe_commu_repr [] c)
| Ttuple tl ->
fprintf ppf "@[<1>Ttuple@,%a@]" raw_type_list tl
| Tconstr (p, tl, abbrev) ->
fprintf ppf "@[<hov1>Tconstr(@,%a,@,%a,@,%a)@]" path p
raw_type_list tl
(raw_list path) (list_of_memo !abbrev)
| Tobject (t, nm) ->
fprintf ppf "@[<hov1>Tobject(@,%a,@,@[<1>ref%t@])@]" raw_type t
(fun ppf ->
match !nm with None -> fprintf ppf " None"
| Some(p,tl) ->
fprintf ppf "(Some(@,%a,@,%a))" path p raw_type_list tl)
| Tfield (f, k, t1, t2) ->
fprintf ppf "@[<hov1>Tfield(@,%s,@,%s,@,%a,@;<0 -1>%a)@]" f
(safe_kind_repr [] k)
raw_type t1 raw_type t2
| Tnil -> fprintf ppf "Tnil"
| Tlink t -> fprintf ppf "@[<1>Tlink@,%a@]" raw_type t
| Tsubst (t, None) -> fprintf ppf "@[<1>Tsubst@,(%a,None)@]" raw_type t
| Tsubst (t, Some t') ->
fprintf ppf "@[<1>Tsubst@,(%a,@ Some%a)@]" raw_type t raw_type t'
| Tunivar name -> fprintf ppf "Tunivar %a" print_name name
| Tpoly (t, tl) ->
fprintf ppf "@[<hov1>Tpoly(@,%a,@,%a)@]"
raw_type t
raw_type_list tl
| Tvariant row ->
fprintf ppf
"@[<hov1>{@[%s@,%a;@]@ @[%s@,%a;@]@ %s%B;@ %s%a;@ @[<1>%s%t@]}@]"
"row_fields="
(raw_list (fun ppf (l, f) ->
fprintf ppf "@[%s,@ %a@]" l raw_field f))
row.row_fields
"row_more=" raw_type row.row_more
"row_closed=" row.row_closed
"row_fixed=" raw_row_fixed row.row_fixed
"row_name="
(fun ppf ->
match row.row_name with None -> fprintf ppf "None"
| Some(p,tl) ->
fprintf ppf "Some(@,%a,@,%a)" path p raw_type_list tl)
| Tpackage (p, fl) ->
fprintf ppf "@[<hov1>Tpackage(@,%a@,%a)@]" path p
raw_type_list (List.map snd fl)
and raw_row_fixed ppf = function
| None -> fprintf ppf "None"
| Some Types.Fixed_private -> fprintf ppf "Some Fixed_private"
| Some Types.Rigid -> fprintf ppf "Some Rigid"
| Some Types.Univar t -> fprintf ppf "Some(Univar(%a))" raw_type t
| Some Types.Reified p -> fprintf ppf "Some(Reified(%a))" path p
and raw_field ppf = function
Rpresent None -> fprintf ppf "Rpresent None"
| Rpresent (Some t) -> fprintf ppf "@[<1>Rpresent(Some@,%a)@]" raw_type t
| Reither (c,tl,m,e) ->
fprintf ppf "@[<hov1>Reither(%B,@,%a,@,%B,@,@[<1>ref%t@])@]" c
raw_type_list tl m
(fun ppf ->
match !e with None -> fprintf ppf " None"
| Some f -> fprintf ppf "@,@[<1>(%a)@]" raw_field f)
| Rabsent -> fprintf ppf "Rabsent"
let raw_type_expr ppf t =
visited := []; kind_vars := []; kind_count := 0;
raw_type ppf t;
visited := []; kind_vars := []
let () = Btype.print_raw := raw_type_expr
(* Normalize paths *)
type param_subst = Id | Nth of int | Map of int list
let is_nth = function
Nth _ -> true
| _ -> false
let compose l1 = function
| Id -> Map l1
| Map l2 -> Map (List.map (List.nth l1) l2)
| Nth n -> Nth (List.nth l1 n)
let apply_subst s1 tyl =
if tyl = [] then []
(* cf. PR#7543: Typemod.type_package doesn't respect type constructor arity *)
else
match s1 with
Nth n1 -> [List.nth tyl n1]
| Map l1 -> List.map (List.nth tyl) l1
| Id -> tyl
type best_path = Paths of Path.t list | Best of Path.t
(** Short-paths cache: the five mutable variables below implement a one-slot
cache for short-paths
*)
let printing_old = ref Env.empty
let printing_pers = ref Concr.empty
(** {!printing_old} and {!printing_pers} are the keys of the one-slot cache *)
let printing_depth = ref 0
let printing_cont = ref ([] : Env.iter_cont list)
let printing_map = ref Path.Map.empty
(**
- {!printing_map} is the main value stored in the cache.
Note that it is evaluated lazily and its value is updated during printing.
- {!printing_dep} is the current exploration depth of the environment,
it is used to determine whenever the {!printing_map} should be evaluated
further before completing a request.
- {!printing_cont} is the list of continuations needed to evaluate
the {!printing_map} one level further (see also {!Env.run_iter_cont})
*)
let same_type t t' = repr t == repr t'
let rec index l x =
match l with
[] -> raise Not_found
| a :: l -> if x == a then 0 else 1 + index l x
let rec uniq = function
[] -> true
| a :: l -> not (List.memq a l) && uniq l
let rec normalize_type_path ?(cache=false) env p =
try
let (params, ty, _) = Env.find_type_expansion p env in
let params = List.map repr params in
match repr ty with
{desc = Tconstr (p1, tyl, _)} ->
let tyl = List.map repr tyl in
if List.length params = List.length tyl
&& List.for_all2 (==) params tyl
then normalize_type_path ~cache env p1
else if cache || List.length params <= List.length tyl
|| not (uniq tyl) then (p, Id)
else
let l1 = List.map (index params) tyl in
let (p2, s2) = normalize_type_path ~cache env p1 in
(p2, compose l1 s2)
| ty ->
(p, Nth (index params ty))
with
Not_found ->
(Env.normalize_type_path None env p, Id)
let penalty s =
if s <> "" && s.[0] = '_' then
10
else
match find_double_underscore s with
| None -> 1
| Some _ -> 10
let rec path_size = function
Pident id ->
penalty (Ident.name id), -Ident.scope id
| Pdot (p, _) ->
let (l, b) = path_size p in (1+l, b)
| Papply (p1, p2) ->
let (l, b) = path_size p1 in
(l + fst (path_size p2), b)
let same_printing_env env =
let used_pers = Env.used_persistent () in
Env.same_types !printing_old env && Concr.equal !printing_pers used_pers
let set_printing_env env =
printing_env := env;
if !Clflags.real_paths ||
!printing_env == Env.empty ||
same_printing_env env then
()
else begin
(* printf "Reset printing_map@."; *)
printing_old := env;
printing_pers := Env.used_persistent ();
printing_map := Path.Map.empty;
printing_depth := 0;
(* printf "Recompute printing_map.@."; *)
let cont =
Env.iter_types
(fun p (p', _decl) ->
let (p1, s1) = normalize_type_path env p' ~cache:true in
(* Format.eprintf "%a -> %a = %a@." path p path p' path p1 *)
if s1 = Id then
try
let r = Path.Map.find p1 !printing_map in
match !r with
Paths l -> r := Paths (p :: l)
| Best p' -> r := Paths [p; p'] (* assert false *)
with Not_found ->
printing_map := Path.Map.add p1 (ref (Paths [p])) !printing_map)
env in
printing_cont := [cont];
end
let wrap_printing_env env f =
set_printing_env env; reset_naming_context ();
try_finally f ~always:(fun () -> set_printing_env Env.empty)
let wrap_printing_env ~error env f =
if error then Env.without_cmis (wrap_printing_env env) f
else wrap_printing_env env f
let rec lid_of_path = function
Path.Pident id ->
Longident.Lident (Ident.name id)
| Path.Pdot (p1, s) ->
Longident.Ldot (lid_of_path p1, s)
| Path.Papply (p1, p2) ->
Longident.Lapply (lid_of_path p1, lid_of_path p2)
let is_unambiguous path env =
let l = Env.find_shadowed_types path env in
List.exists (Path.same path) l || (* concrete paths are ok *)
match l with
[] -> true
| p :: rem ->
(* allow also coherent paths: *)
let normalize p = fst (normalize_type_path ~cache:true env p) in
let p' = normalize p in
List.for_all (fun p -> Path.same (normalize p) p') rem ||
(* also allow repeatedly defining and opening (for toplevel) *)
let id = lid_of_path p in
List.for_all (fun p -> lid_of_path p = id) rem &&
Path.same p (fst (Env.find_type_by_name id env))
let rec get_best_path r =
match !r with
Best p' -> p'
| Paths [] -> raise Not_found
| Paths l ->
r := Paths [];
List.iter
(fun p ->
(* Format.eprintf "evaluating %a@." path p; *)
match !r with
Best p' when path_size p >= path_size p' -> ()
| _ -> if is_unambiguous p !printing_env then r := Best p)
(* else Format.eprintf "%a ignored as ambiguous@." path p *)
l;
get_best_path r
let best_type_path p =
if !printing_env == Env.empty
then (p, Id)
else if !Clflags.real_paths
then (p, Id)
else
let (p', s) = normalize_type_path !printing_env p in
let get_path () = get_best_path (Path.Map.find p' !printing_map) in
while !printing_cont <> [] &&
try fst (path_size (get_path ())) > !printing_depth with Not_found -> true
do
printing_cont := List.map snd (Env.run_iter_cont !printing_cont);
incr printing_depth;
done;
let p'' = try get_path () with Not_found -> p' in
(* Format.eprintf "%a = %a -> %a@." path p path p' path p''; *)
(p'', s)
(* Print a type expression *)
let names = ref ([] : (type_expr * string) list)
let name_counter = ref 0
let named_vars = ref ([] : string list)
let weak_counter = ref 1
let weak_var_map = ref TypeMap.empty
let named_weak_vars = ref String.Set.empty
let reset_names () = names := []; name_counter := 0; named_vars := []
let add_named_var ty =
match ty.desc with
Tvar (Some name) | Tunivar (Some name) ->
if List.mem name !named_vars then () else
named_vars := name :: !named_vars
| _ -> ()
let name_is_already_used name =
List.mem name !named_vars
|| List.exists (fun (_, name') -> name = name') !names
|| String.Set.mem name !named_weak_vars
let rec new_name () =
let name =
if !name_counter < 26
then String.make 1 (Char.chr(97 + !name_counter))
else String.make 1 (Char.chr(97 + !name_counter mod 26)) ^
Int.to_string(!name_counter / 26) in
incr name_counter;
if name_is_already_used name then new_name () else name
let rec new_weak_name ty () =
let name = "weak" ^ Int.to_string !weak_counter in
incr weak_counter;
if name_is_already_used name then new_weak_name ty ()
else begin
named_weak_vars := String.Set.add name !named_weak_vars;
weak_var_map := TypeMap.add ty name !weak_var_map;
name
end
let name_of_type name_generator t =
(* We've already been through repr at this stage, so t is our representative
of the union-find class. *)
try List.assq t !names with Not_found ->
try TypeMap.find t !weak_var_map with Not_found ->
let name =
match t.desc with
Tvar (Some name) | Tunivar (Some name) ->
(* Some part of the type we've already printed has assigned another
* unification variable to that name. We want to keep the name, so try
* adding a number until we find a name that's not taken. *)
let current_name = ref name in
let i = ref 0 in
while List.exists (fun (_, name') -> !current_name = name') !names do
current_name := name ^ (Int.to_string !i);
i := !i + 1;
done;
!current_name
| _ ->
(* No name available, create a new one *)
name_generator ()
in
(* Exception for type declarations *)
if name <> "_" then names := (t, name) :: !names;
name
let check_name_of_type t = ignore(name_of_type new_name t)
let remove_names tyl =
let tyl = List.map repr tyl in
names := List.filter (fun (ty,_) -> not (List.memq ty tyl)) !names
let visited_objects = ref ([] : type_expr list)
let aliased = ref ([] : type_expr list)
let delayed = ref ([] : type_expr list)
let add_delayed t =
if not (List.memq t !delayed) then delayed := t :: !delayed
let is_aliased ty = List.memq (proxy ty) !aliased
let add_alias ty =
let px = proxy ty in
if not (is_aliased px) then begin
aliased := px :: !aliased;
add_named_var px
end
let aliasable ty =
match ty.desc with
Tvar _ | Tunivar _ | Tpoly _ -> false
| Tconstr (p, _, _) ->
not (is_nth (snd (best_type_path p)))
| _ -> true
let namable_row row =
row.row_name <> None &&
List.for_all
(fun (_, f) ->
match row_field_repr f with
| Reither(c, l, _, _) ->
row.row_closed && if c then l = [] else List.length l = 1
| _ -> true)
row.row_fields
let rec mark_loops_rec visited ty =
let ty = repr ty in
let px = proxy ty in
if List.memq px visited && aliasable ty then add_alias px else
let visited = px :: visited in
match ty.desc with
| Tvar _ -> add_named_var ty
| Tarrow(_, ty1, ty2, _) ->
mark_loops_rec visited ty1; mark_loops_rec visited ty2
| Ttuple tyl -> List.iter (mark_loops_rec visited) tyl
| Tconstr(p, tyl, _) ->
let (_p', s) = best_type_path p in
List.iter (mark_loops_rec visited) (apply_subst s tyl)
| Tpackage (_, fl) ->
List.iter (fun (_n, ty) -> mark_loops_rec visited ty) fl
| Tvariant row ->
if List.memq px !visited_objects then add_alias px else
begin
let row = row_repr row in
if not (static_row row) then
visited_objects := px :: !visited_objects;
match row.row_name with
| Some(_p, tyl) when namable_row row ->
List.iter (mark_loops_rec visited) tyl
| _ ->
iter_row (mark_loops_rec visited) row
end
| Tobject (fi, nm) ->
if List.memq px !visited_objects then add_alias px else
begin
if opened_object ty then
visited_objects := px :: !visited_objects;
begin match !nm with
| None ->
let fields, _ = flatten_fields fi in
List.iter
(fun (_, kind, ty) ->
if field_kind_repr kind = Fpresent then
mark_loops_rec visited ty)
fields
| Some (_, l) ->
List.iter (mark_loops_rec visited) (List.tl l)
end
end
| Tfield(_, kind, ty1, ty2) when field_kind_repr kind = Fpresent ->
mark_loops_rec visited ty1; mark_loops_rec visited ty2
| Tfield(_, _, _, ty2) ->
mark_loops_rec visited ty2
| Tnil -> ()
| Tsubst _ -> () (* we do not print arguments *)
| Tlink _ -> fatal_error "Printtyp.mark_loops_rec (2)"
| Tpoly (ty, tyl) ->
List.iter (fun t -> add_alias t) tyl;
mark_loops_rec visited ty
| Tunivar _ -> add_named_var ty
let mark_loops ty =
normalize_type ty;
mark_loops_rec [] ty;;
let reset_loop_marks () =
visited_objects := []; aliased := []; delayed := []
let reset_except_context () =
reset_names (); reset_loop_marks ()
let reset () =
reset_naming_context (); Conflicts.reset ();
reset_except_context ()
let reset_and_mark_loops ty =
reset_except_context (); mark_loops ty
let reset_and_mark_loops_list tyl =
reset_except_context (); List.iter mark_loops tyl
(* Disabled in classic mode when printing an unification error *)
let print_labels = ref true
let rec tree_of_typexp sch ty =
let ty = repr ty in
let px = proxy ty in
if List.mem_assq px !names && not (List.memq px !delayed) then
let mark = is_non_gen sch ty in
let name = name_of_type (if mark then new_weak_name ty else new_name) px in
Otyp_var (mark, name) else
let pr_typ () =
match ty.desc with
| Tvar _ ->
(*let lev =
if is_non_gen sch ty then "/" ^ Int.to_string ty.level else "" in*)
let non_gen = is_non_gen sch ty in
let name_gen = if non_gen then new_weak_name ty else new_name in
Otyp_var (non_gen, name_of_type name_gen ty)
| Tarrow(l, ty1, ty2, _) ->
let lab =
if !print_labels || is_optional l then string_of_label l else ""
in
let t1 =
if is_optional l then
match (repr ty1).desc with
| Tconstr(path, [ty], _)
when Path.same path Predef.path_option ->
tree_of_typexp sch ty
| _ -> Otyp_stuff "<hidden>"
else tree_of_typexp sch ty1 in
Otyp_arrow (lab, t1, tree_of_typexp sch ty2)
| Ttuple tyl ->
Otyp_tuple (tree_of_typlist sch tyl)
| Tconstr(p, tyl, _abbrev) ->
let p', s = best_type_path p in
let tyl' = apply_subst s tyl in
if is_nth s && not (tyl'=[]) then tree_of_typexp sch (List.hd tyl') else
Otyp_constr (tree_of_path Type p', tree_of_typlist sch tyl')
| Tvariant row ->
let row = row_repr row in
let fields =
if row.row_closed then
List.filter (fun (_, f) -> row_field_repr f <> Rabsent)
row.row_fields
else row.row_fields in
let present =
List.filter
(fun (_, f) ->
match row_field_repr f with
| Rpresent _ -> true
| _ -> false)
fields in
let all_present = List.length present = List.length fields in
begin match row.row_name with
| Some(p, tyl) when namable_row row ->
let (p', s) = best_type_path p in
let id = tree_of_path Type p' in
let args = tree_of_typlist sch (apply_subst s tyl) in
let out_variant =
if is_nth s then List.hd args else Otyp_constr (id, args) in
if row.row_closed && all_present then
out_variant
else
let non_gen = is_non_gen sch px in
let tags =
if all_present then None else Some (List.map fst present) in
Otyp_variant (non_gen, Ovar_typ out_variant, row.row_closed, tags)
| _ ->
let non_gen =
not (row.row_closed && all_present) && is_non_gen sch px in
let fields = List.map (tree_of_row_field sch) fields in
let tags =
if all_present then None else Some (List.map fst present) in
Otyp_variant (non_gen, Ovar_fields fields, row.row_closed, tags)
end
| Tobject (fi, nm) ->
tree_of_typobject sch fi !nm
| Tnil | Tfield _ ->
tree_of_typobject sch ty None
| Tsubst _ ->
(* This case should only happen when debugging the compiler *)
Otyp_stuff "<Tsubst>"
| Tlink _ ->
fatal_error "Printtyp.tree_of_typexp"
| Tpoly (ty, []) ->
tree_of_typexp sch ty
| Tpoly (ty, tyl) ->
(*let print_names () =
List.iter (fun (_, name) -> prerr_string (name ^ " ")) !names;
prerr_string "; " in *)
let tyl = List.map repr tyl in
if tyl = [] then tree_of_typexp sch ty else begin
let old_delayed = !delayed in
(* Make the names delayed, so that the real type is
printed once when used as proxy *)
List.iter add_delayed tyl;
let tl = List.map (name_of_type new_name) tyl in
let tr = Otyp_poly (tl, tree_of_typexp sch ty) in
(* Forget names when we leave scope *)
remove_names tyl;
delayed := old_delayed; tr
end
| Tunivar _ ->
Otyp_var (false, name_of_type new_name ty)
| Tpackage (p, fl) ->
let fl =
List.map
(fun (li, ty) -> (
String.concat "." (Longident.flatten li),
tree_of_typexp sch ty
)) fl in
Otyp_module (tree_of_path Module_type p, fl)
in
if List.memq px !delayed then delayed := List.filter ((!=) px) !delayed;
if is_aliased px && aliasable ty then begin
check_name_of_type px;
Otyp_alias (pr_typ (), name_of_type new_name px) end
else pr_typ ()
and tree_of_row_field sch (l, f) =
match row_field_repr f with
| Rpresent None | Reither(true, [], _, _) -> (l, false, [])
| Rpresent(Some ty) -> (l, false, [tree_of_typexp sch ty])
| Reither(c, tyl, _, _) ->
if c (* contradiction: constant constructor with an argument *)
then (l, true, tree_of_typlist sch tyl)
else (l, false, tree_of_typlist sch tyl)
| Rabsent -> (l, false, [] (* actually, an error *))
and tree_of_typlist sch tyl =
List.map (tree_of_typexp sch) tyl
and tree_of_typobject sch fi nm =
begin match nm with
| None ->
let pr_fields fi =
let (fields, rest) = flatten_fields fi in
let present_fields =
List.fold_right
(fun (n, k, t) l ->
match field_kind_repr k with
| Fpresent -> (n, t) :: l
| _ -> l)
fields [] in
let sorted_fields =
List.sort
(fun (n, _) (n', _) -> String.compare n n') present_fields in
tree_of_typfields sch rest sorted_fields in
let (fields, rest) = pr_fields fi in
Otyp_object (fields, rest)
| Some (p, ty :: tyl) ->
let non_gen = is_non_gen sch (repr ty) in
let args = tree_of_typlist sch tyl in
let (p', s) = best_type_path p in
assert (s = Id);
Otyp_class (non_gen, tree_of_path Type p', args)
| _ ->
fatal_error "Printtyp.tree_of_typobject"
end
and is_non_gen sch ty =
sch && is_Tvar ty && ty.level <> generic_level
and tree_of_typfields sch rest = function
| [] ->
let rest =
match rest.desc with
| Tvar _ | Tunivar _ -> Some (is_non_gen sch rest)
| Tconstr _ -> Some false
| Tnil -> None
| _ -> fatal_error "typfields (1)"
in
([], rest)
| (s, t) :: l ->
let field = (s, tree_of_typexp sch t) in
let (fields, rest) = tree_of_typfields sch rest l in
(field :: fields, rest)
let typexp sch ppf ty =
!Oprint.out_type ppf (tree_of_typexp sch ty)
let marked_type_expr ppf ty = typexp false ppf ty
let type_expr ppf ty =
(* [type_expr] is used directly by error message printers,
we mark eventual loops ourself to avoid any misuse and stack overflow *)
reset_and_mark_loops ty;
marked_type_expr ppf ty
and type_sch ppf ty = typexp true ppf ty
and type_scheme ppf ty = reset_and_mark_loops ty; typexp true ppf ty
let type_path ppf p =
let (p', s) = best_type_path p in
let p = if (s = Id) then p' else p in
let t = tree_of_path Type p in
!Oprint.out_ident ppf t
(* Maxence *)
let type_scheme_max ?(b_reset_names=true) ppf ty =
if b_reset_names then reset_names () ;
typexp true ppf ty
(* End Maxence *)
let tree_of_type_scheme ty = reset_and_mark_loops ty; tree_of_typexp true ty
(* Print one type declaration *)
let tree_of_constraints params =
List.fold_right
(fun ty list ->
let ty' = unalias ty in
if proxy ty != proxy ty' then
let tr = tree_of_typexp true ty in
(tr, tree_of_typexp true ty') :: list
else list)
params []
let filter_params tyl =
let params =
List.fold_left
(fun tyl ty ->
let ty = repr ty in
if List.memq ty tyl then Btype.newgenty (Ttuple [ty]) :: tyl
else ty :: tyl)
(* Two parameters might be identical due to a constraint but we need to
print them differently in order to make the output syntactically valid.
We use [Ttuple [ty]] because it is printed as [ty]. *)
(* Replacing fold_left by fold_right does not work! *)
[] tyl
in List.rev params
let mark_loops_constructor_arguments = function
| Cstr_tuple l -> List.iter mark_loops l
| Cstr_record l -> List.iter (fun l -> mark_loops l.ld_type) l
let rec tree_of_type_decl id decl =
reset_except_context();
let params = filter_params decl.type_params in
begin match decl.type_manifest with
| Some ty ->
let vars = free_variables ty in
List.iter
(function {desc = Tvar (Some "_")} as ty ->
if List.memq ty vars then set_type_desc ty (Tvar None)
| _ -> ())
params
| None -> ()
end;
List.iter add_alias params;
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
let ty_manifest =
match decl.type_manifest with
| None -> None
| Some ty ->
let ty =
(* Special hack to hide variant name *)
match repr ty with {desc=Tvariant row} ->
let row = row_repr row in
begin match row.row_name with
Some (Pident id', _) when Ident.same id id' ->
newgenty (Tvariant {row with row_name = None})
| _ -> ty
end
| _ -> ty
in
mark_loops ty;
Some ty
in
begin match decl.type_kind with
| Type_abstract -> ()
| Type_variant (cstrs, _rep) ->
List.iter
(fun c ->
mark_loops_constructor_arguments c.cd_args;
Option.iter mark_loops c.cd_res)
cstrs
| Type_record(l, _rep) ->
List.iter (fun l -> mark_loops l.ld_type) l
| Type_open -> ()
end;
let type_param =
function
| Otyp_var (_, id) -> id
| _ -> "?"
in
let type_defined decl =
let abstr =
match decl.type_kind with
Type_abstract ->
decl.type_manifest = None || decl.type_private = Private
| Type_record _ ->
decl.type_private = Private
| Type_variant (tll, _rep) ->
decl.type_private = Private ||
List.exists (fun cd -> cd.cd_res <> None) tll
| Type_open ->
decl.type_manifest = None
in
let vari =
List.map2
(fun ty v ->
let is_var = is_Tvar (repr ty) in
if abstr || not is_var then
let inj =
decl.type_kind = Type_abstract && Variance.mem Inj v &&
match decl.type_manifest with
| None -> true
| Some ty -> (* only abstract or private row types *)
decl.type_private = Private &&
Btype.is_constr_row ~allow_ident:true (Btype.row_of_type ty)
and (co, cn) = Variance.get_upper v in
(if not cn then Covariant else
if not co then Contravariant else NoVariance),
(if inj then Injective else NoInjectivity)
else (NoVariance, NoInjectivity))
decl.type_params decl.type_variance
in
(Ident.name id,
List.map2 (fun ty cocn -> type_param (tree_of_typexp false ty), cocn)
params vari)
in
let tree_of_manifest ty1 =
match ty_manifest with
| None -> ty1
| Some ty -> Otyp_manifest (tree_of_typexp false ty, ty1)
in
let (name, args) = type_defined decl in
let constraints = tree_of_constraints params in
let ty, priv, unboxed =
match decl.type_kind with
| Type_abstract ->
begin match ty_manifest with
| None -> (Otyp_abstract, Public, false)
| Some ty ->
tree_of_typexp false ty, decl.type_private, false
end
| Type_variant (cstrs, rep) ->
tree_of_manifest (Otyp_sum (List.map tree_of_constructor cstrs)),
decl.type_private,
(rep = Variant_unboxed)
| Type_record(lbls, rep) ->
tree_of_manifest (Otyp_record (List.map tree_of_label lbls)),
decl.type_private,
(match rep with Record_unboxed _ -> true | _ -> false)
| Type_open ->
tree_of_manifest Otyp_open,
decl.type_private,
false
in
{ otype_name = name;
otype_params = args;
otype_type = ty;
otype_private = priv;
otype_immediate = Type_immediacy.of_attributes decl.type_attributes;
otype_unboxed = unboxed;
otype_cstrs = constraints }
and tree_of_constructor_arguments = function
| Cstr_tuple l -> tree_of_typlist false l
| Cstr_record l -> [ Otyp_record (List.map tree_of_label l) ]
and tree_of_constructor cd =
let name = Ident.name cd.cd_id in
let arg () = tree_of_constructor_arguments cd.cd_args in
match cd.cd_res with
| None -> (name, arg (), None)
| Some res ->
let nm = !names in
names := [];
let ret = tree_of_typexp false res in
let args = arg () in
names := nm;
(name, args, Some ret)
and tree_of_label l =
(Ident.name l.ld_id, l.ld_mutable = Mutable, tree_of_typexp false l.ld_type)
let constructor ppf c =
reset_except_context ();
!Oprint.out_constr ppf (tree_of_constructor c)
let label ppf l =
reset_except_context ();
!Oprint.out_label ppf (tree_of_label l)
let tree_of_type_declaration id decl rs =
Osig_type (tree_of_type_decl id decl, tree_of_rec rs)
let type_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_type_declaration id decl Trec_first)
let constructor_arguments ppf a =
let tys = tree_of_constructor_arguments a in
!Oprint.out_type ppf (Otyp_tuple tys)
(* Print an extension declaration *)
let extension_constructor_args_and_ret_type_subtree ext_args ext_ret_type =
match ext_ret_type with
| None -> (tree_of_constructor_arguments ext_args, None)
| Some res ->
let nm = !names in
names := [];
let ret = tree_of_typexp false res in
let args = tree_of_constructor_arguments ext_args in
names := nm;
(args, Some ret)
let tree_of_extension_constructor id ext es =
reset_except_context ();
let ty_name = Path.name ext.ext_type_path in
let ty_params = filter_params ext.ext_type_params in
List.iter add_alias ty_params;
List.iter mark_loops ty_params;
List.iter check_name_of_type (List.map proxy ty_params);
mark_loops_constructor_arguments ext.ext_args;
Option.iter mark_loops ext.ext_ret_type;
let type_param =
function
| Otyp_var (_, id) -> id
| _ -> "?"
in
let ty_params =
List.map (fun ty -> type_param (tree_of_typexp false ty)) ty_params
in
let name = Ident.name id in
let args, ret =
extension_constructor_args_and_ret_type_subtree
ext.ext_args
ext.ext_ret_type
in
let ext =
{ oext_name = name;
oext_type_name = ty_name;
oext_type_params = ty_params;
oext_args = args;
oext_ret_type = ret;
oext_private = ext.ext_private }
in
let es =
match es with
Text_first -> Oext_first
| Text_next -> Oext_next
| Text_exception -> Oext_exception
in
Osig_typext (ext, es)
let extension_constructor id ppf ext =
!Oprint.out_sig_item ppf (tree_of_extension_constructor id ext Text_first)
let extension_only_constructor id ppf ext =
reset_except_context ();
let name = Ident.name id in
let args, ret =
extension_constructor_args_and_ret_type_subtree
ext.ext_args
ext.ext_ret_type
in
Format.fprintf ppf "@[<hv>%a@]"
!Oprint.out_constr (name, args, ret)
(* Print a value declaration *)
let tree_of_value_description id decl =
(* Format.eprintf "@[%a@]@." raw_type_expr decl.val_type; *)
let id = Ident.name id in
let ty = tree_of_type_scheme decl.val_type in
let vd =
{ oval_name = id;
oval_type = ty;
oval_prims = [];
oval_attributes = [] }
in
let vd =
match decl.val_kind with
| Val_prim p -> Primitive.print p vd
| _ -> vd
in
Osig_value vd
let value_description id ppf decl =
!Oprint.out_sig_item ppf (tree_of_value_description id decl)
(* Print a class type *)
let method_type (_, kind, ty) =
match field_kind_repr kind, repr ty with
Fpresent, {desc=Tpoly(ty, tyl)} -> (ty, tyl)
| _ , ty -> (ty, [])
let tree_of_metho sch concrete csil (lab, kind, ty) =
if lab <> dummy_method then begin
let kind = field_kind_repr kind in
let priv = kind <> Fpresent in
let virt = not (Concr.mem lab concrete) in
let (ty, tyl) = method_type (lab, kind, ty) in
let tty = tree_of_typexp sch ty in
remove_names tyl;
Ocsg_method (lab, priv, virt, tty) :: csil
end
else csil
let rec prepare_class_type params = function
| Cty_constr (_p, tyl, cty) ->
let sty = Ctype.self_type cty in
if List.memq (proxy sty) !visited_objects
|| not (List.for_all is_Tvar params)
|| List.exists (deep_occur sty) tyl
then prepare_class_type params cty
else List.iter mark_loops tyl
| Cty_signature sign ->
let sty = repr sign.csig_self in
(* Self may have a name *)
let px = proxy sty in
if List.memq px !visited_objects then add_alias sty
else visited_objects := px :: !visited_objects;
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.csig_self)
in
List.iter (fun met -> mark_loops (fst (method_type met))) fields;
Vars.iter (fun _ (_, _, ty) -> mark_loops ty) sign.csig_vars
| Cty_arrow (_, ty, cty) ->
mark_loops ty;
prepare_class_type params cty
let rec tree_of_class_type sch params =
function
| Cty_constr (p', tyl, cty) ->
let sty = Ctype.self_type cty in
if List.memq (proxy sty) !visited_objects
|| not (List.for_all is_Tvar params)
then
tree_of_class_type sch params cty
else
let namespace = Namespace.best_class_namespace p' in
Octy_constr (tree_of_path namespace p', tree_of_typlist true tyl)
| Cty_signature sign ->
let sty = repr sign.csig_self in
let self_ty =
if is_aliased sty then
Some (Otyp_var (false, name_of_type new_name (proxy sty)))
else None
in
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.csig_self)
in
let csil = [] in
let csil =
List.fold_left
(fun csil (ty1, ty2) -> Ocsg_constraint (ty1, ty2) :: csil)
csil (tree_of_constraints params)
in
let all_vars =
Vars.fold (fun l (m, v, t) all -> (l, m, v, t) :: all) sign.csig_vars []
in
(* Consequence of PR#3607: order of Map.fold has changed! *)
let all_vars = List.rev all_vars in
let csil =
List.fold_left
(fun csil (l, m, v, t) ->
Ocsg_value (l, m = Mutable, v = Virtual, tree_of_typexp sch t)
:: csil)
csil all_vars
in
let csil =
List.fold_left (tree_of_metho sch sign.csig_concr) csil fields
in
Octy_signature (self_ty, List.rev csil)
| Cty_arrow (l, ty, cty) ->
let lab =
if !print_labels || is_optional l then string_of_label l else ""
in
let tr =
if is_optional l then
match (repr ty).desc with
| Tconstr(path, [ty], _) when Path.same path Predef.path_option ->
tree_of_typexp sch ty
| _ -> Otyp_stuff "<hidden>"
else tree_of_typexp sch ty in
Octy_arrow (lab, tr, tree_of_class_type sch params cty)
let class_type ppf cty =
reset ();
prepare_class_type [] cty;
!Oprint.out_class_type ppf (tree_of_class_type false [] cty)
let tree_of_class_param param variance =
(match tree_of_typexp true param with
Otyp_var (_, s) -> s
| _ -> "?"),
if is_Tvar (repr param) then Asttypes.(NoVariance, NoInjectivity)
else variance
let class_variance =
let open Variance in let open Asttypes in
List.map (fun v ->
(if not (mem May_pos v) then Contravariant else
if not (mem May_neg v) then Covariant else NoVariance),
NoInjectivity)
let tree_of_class_declaration id cl rs =
let params = filter_params cl.cty_params in
reset_except_context ();
List.iter add_alias params;
prepare_class_type params cl.cty_type;
let sty = Ctype.self_type cl.cty_type in
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
if is_aliased sty then check_name_of_type (proxy sty);
let vir_flag = cl.cty_new = None in
Osig_class
(vir_flag, Ident.name id,
List.map2 tree_of_class_param params (class_variance cl.cty_variance),
tree_of_class_type true params cl.cty_type,
tree_of_rec rs)
let class_declaration id ppf cl =
!Oprint.out_sig_item ppf (tree_of_class_declaration id cl Trec_first)
let tree_of_cltype_declaration id cl rs =
let params = List.map repr cl.clty_params in
reset_except_context ();
List.iter add_alias params;
prepare_class_type params cl.clty_type;
let sty = Ctype.self_type cl.clty_type in
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
if is_aliased sty then check_name_of_type (proxy sty);
let sign = Ctype.signature_of_class_type cl.clty_type in
let virt =
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.csig_self) in
List.exists
(fun (lab, _, _) ->
not (lab = dummy_method || Concr.mem lab sign.csig_concr))
fields
|| Vars.fold (fun _ (_,vr,_) b -> vr = Virtual || b) sign.csig_vars false
in
Osig_class_type
(virt, Ident.name id,
List.map2 tree_of_class_param params (class_variance cl.clty_variance),
tree_of_class_type true params cl.clty_type,
tree_of_rec rs)
let cltype_declaration id ppf cl =
!Oprint.out_sig_item ppf (tree_of_cltype_declaration id cl Trec_first)
(* Print a module type *)
let wrap_env fenv ftree arg =
(* We save the current value of the short-path cache *)
(* From keys *)
let env = !printing_env in
let old_pers = !printing_pers in
(* to data *)
let old_map = !printing_map in
let old_depth = !printing_depth in
let old_cont = !printing_cont in
set_printing_env (fenv env);
let tree = ftree arg in
if !Clflags.real_paths
|| same_printing_env env then ()
(* our cached key is still live in the cache, and we want to keep all
progress made on the computation of the [printing_map] *)
else begin
(* we restore the snapshotted cache before calling set_printing_env *)
printing_old := env;
printing_pers := old_pers;
printing_depth := old_depth;
printing_cont := old_cont;
printing_map := old_map
end;
set_printing_env env;
tree
let dummy =
{
type_params = [];
type_arity = 0;
type_kind = Type_abstract;
type_private = Public;
type_manifest = None;
type_variance = [];
type_separability = [];
type_is_newtype = false;
type_expansion_scope = Btype.lowest_level;
type_loc = Location.none;
type_attributes = [];
type_immediate = Unknown;
type_unboxed_default = false;
type_uid = Uid.internal_not_actually_unique;
}
(** we hide items being defined from short-path to avoid shortening
[type t = Path.To.t] into [type t = t].
*)
let ident_sigitem = function
| Types.Sig_type(ident,_,_,_) -> {hide=true;ident}
| Types.Sig_class(ident,_,_,_)
| Types.Sig_class_type (ident,_,_,_)
| Types.Sig_module(ident,_, _,_,_)
| Types.Sig_value (ident,_,_)
| Types.Sig_modtype (ident,_,_)
| Types.Sig_typext (ident,_,_,_) -> {hide=false; ident }
let hide ids env =
let hide_id id env =
(* Global idents cannot be renamed *)
if id.hide && not (Ident.global id.ident) then
Env.add_type ~check:false (Ident.rename id.ident) dummy env
else env
in
List.fold_right hide_id ids env
let with_hidden_items ids f =
let with_hidden_in_printing_env ids f =
wrap_env (hide ids) (Naming_context.with_hidden ids) f
in
if not !Clflags.real_paths then
with_hidden_in_printing_env ids f
else
Naming_context.with_hidden ids f
let add_sigitem env x =
Env.add_signature (Signature_group.flatten x) env
let rec tree_of_modtype ?(ellipsis=false) = function
| Mty_ident p ->
Omty_ident (tree_of_path Module_type p)
| Mty_signature sg ->
Omty_signature (if ellipsis then [Osig_ellipsis]
else tree_of_signature sg)
| Mty_functor(param, ty_res) ->
let param, env =
tree_of_functor_parameter param
in
let res = wrap_env env (tree_of_modtype ~ellipsis) ty_res in
Omty_functor (param, res)
| Mty_alias p ->
Omty_alias (tree_of_path Module p)
and tree_of_functor_parameter = function
| Unit ->
None, fun k -> k
| Named (param, ty_arg) ->
let name, env =
match param with
| None -> None, fun env -> env
| Some id ->
Some (Ident.name id),
Env.add_module ~arg:true id Mp_present ty_arg
in
Some (name, tree_of_modtype ~ellipsis:false ty_arg), env
and tree_of_signature sg =
wrap_env (fun env -> env)(fun sg ->
let tree_groups = tree_of_signature_rec !printing_env sg in
List.concat_map (fun (_env,l) -> List.map snd l) tree_groups
) sg
and tree_of_signature_rec env' sg =
let structured = List.of_seq (Signature_group.seq sg) in
let collect_trees_of_rec_group group =
let env = !printing_env in
let env', group_trees =
Naming_context.with_ctx
(fun () -> trees_of_recursive_sigitem_group env group)
in
set_printing_env env';
(env, group_trees) in
set_printing_env env';
List.map collect_trees_of_rec_group structured
and trees_of_recursive_sigitem_group env
(syntactic_group: Signature_group.rec_group) =
let display (x:Signature_group.sig_item) = x.src, tree_of_sigitem x.src in
let env = Env.add_signature syntactic_group.pre_ghosts env in
match syntactic_group.group with
| Not_rec x -> add_sigitem env x, [display x]
| Rec_group items ->
let ids = List.map (fun x -> ident_sigitem x.Signature_group.src) items in
List.fold_left add_sigitem env items,
with_hidden_items ids (fun () -> List.map display items)
and tree_of_sigitem = function
| Sig_value(id, decl, _) ->
tree_of_value_description id decl
| Sig_type(id, decl, rs, _) ->
tree_of_type_declaration id decl rs
| Sig_typext(id, ext, es, _) ->
tree_of_extension_constructor id ext es
| Sig_module(id, _, md, rs, _) ->
let ellipsis =
List.exists (function
| Parsetree.{attr_name = {txt="..."}; attr_payload = PStr []} -> true
| _ -> false)
md.md_attributes in
tree_of_module id md.md_type rs ~ellipsis
| Sig_modtype(id, decl, _) ->
tree_of_modtype_declaration id decl
| Sig_class(id, decl, rs, _) ->
tree_of_class_declaration id decl rs
| Sig_class_type(id, decl, rs, _) ->
tree_of_cltype_declaration id decl rs
and tree_of_modtype_declaration id decl =
let mty =
match decl.mtd_type with
| None -> Omty_abstract
| Some mty -> tree_of_modtype mty
in
Osig_modtype (Ident.name id, mty)
and tree_of_module id ?ellipsis mty rs =
Osig_module (Ident.name id, tree_of_modtype ?ellipsis mty, tree_of_rec rs)
let rec functor_parameters ~sep custom_printer = function
| [] -> ignore
| [id,param] ->
Format.dprintf "%t%t"
(custom_printer param)
(functor_param ~sep ~custom_printer id [])
| (id,param) :: q ->
Format.dprintf "%t%a%t"
(custom_printer param)
sep ()
(functor_param ~sep ~custom_printer id q)
and functor_param ~sep ~custom_printer id q =
match id with
| None -> functor_parameters ~sep custom_printer q
| Some id ->
Naming_context.with_arg id
(fun () -> functor_parameters ~sep custom_printer q)
let modtype ppf mty = !Oprint.out_module_type ppf (tree_of_modtype mty)
let modtype_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_modtype_declaration id decl)
(* For the toplevel: merge with tree_of_signature? *)
(* Refresh weak variable map in the toplevel *)
let refresh_weak () =
let refresh t name (m,s) =
if is_non_gen true (repr t) then
begin
TypeMap.add t name m,
String.Set.add name s
end
else m, s in
let m, s =
TypeMap.fold refresh !weak_var_map (TypeMap.empty ,String.Set.empty) in
named_weak_vars := s;
weak_var_map := m
let print_items showval env x =
refresh_weak();
reset_naming_context ();
Conflicts.reset ();
let extend_val env (sigitem,outcome) = outcome, showval env sigitem in
let post_process (env,l) = List.map (extend_val env) l in
List.concat_map post_process @@ tree_of_signature_rec env x
(* Print a signature body (used by -i when compiling a .ml) *)
let print_signature ppf tree =
fprintf ppf "@[<v>%a@]" !Oprint.out_signature tree
let signature ppf sg =
fprintf ppf "%a" print_signature (tree_of_signature sg)
(* Print a signature body (used by -i when compiling a .ml) *)
let printed_signature sourcefile ppf sg =
(* we are tracking any collision event for warning 63 *)
Conflicts.reset ();
reset_naming_context ();
let t = tree_of_signature sg in
if Warnings.(is_active @@ Erroneous_printed_signature "")
&& Conflicts.exists ()
then begin
let conflicts = Format.asprintf "%t" Conflicts.print_explanations in
Location.prerr_warning (Location.in_file sourcefile)
(Warnings.Erroneous_printed_signature conflicts);
Warnings.check_fatal ()
end;
fprintf ppf "%a" print_signature t
(* Print an unification error *)
let same_path t t' =
let t = repr t and t' = repr t' in
t == t' ||
match t.desc, t'.desc with
Tconstr(p,tl,_), Tconstr(p',tl',_) ->
let (p1, s1) = best_type_path p and (p2, s2) = best_type_path p' in
begin match s1, s2 with
Nth n1, Nth n2 when n1 = n2 -> true
| (Id | Map _), (Id | Map _) when Path.same p1 p2 ->
let tl = apply_subst s1 tl and tl' = apply_subst s2 tl' in
List.length tl = List.length tl' &&
List.for_all2 same_type tl tl'
| _ -> false
end
| _ ->
false
type 'a diff = Same of 'a | Diff of 'a * 'a
let trees_of_type_expansion (t,t') =
if same_path t t'
then begin add_delayed (proxy t); Same (tree_of_typexp false t) end
else
let t' = if proxy t == proxy t' then unalias t' else t' in
(* beware order matter due to side effect,
e.g. when printing object types *)
let first = tree_of_typexp false t in
let second = tree_of_typexp false t' in
if first = second then Same first
else Diff(first,second)
let type_expansion ppf = function
| Same t -> !Oprint.out_type ppf t
| Diff(t,t') ->
fprintf ppf "@[<2>%a@ =@ %a@]" !Oprint.out_type t !Oprint.out_type t'
let trees_of_trace = List.map (Errortrace.map_diff trees_of_type_expansion)
let trees_of_type_path_expansion (tp,tp') =
if Path.same tp tp' then Same(tree_of_path Type tp) else
Diff(tree_of_path Type tp, tree_of_path Type tp')
let type_path_expansion ppf = function
| Same p -> !Oprint.out_ident ppf p
| Diff(p,p') ->
fprintf ppf "@[<2>%a@ =@ %a@]"
!Oprint.out_ident p
!Oprint.out_ident p'
let rec trace fst txt ppf = function
| {Errortrace.got; expected} :: rem ->
if not fst then fprintf ppf "@,";
fprintf ppf "@[Type@;<1 2>%a@ %s@;<1 2>%a@] %a"
type_expansion got txt type_expansion expected
(trace false txt) rem
| _ -> ()
type printing_status =
| Discard
| Keep
| Optional_refinement
(** An [Optional_refinement] printing status is attributed to trace
elements that are focusing on a new subpart of a structural type.
Since the whole type should have been printed earlier in the trace,
we only print those elements if they are the last printed element
of a trace, and there is no explicit explanation for the
type error.
*)
let diff_printing_status { Errortrace.got=t1, t1'; expected=t2, t2'} =
if is_constr_row ~allow_ident:true t1'
|| is_constr_row ~allow_ident:true t2'
then Discard
else if same_path t1 t1' && same_path t2 t2' then Optional_refinement
else Keep
(* A configuration type that controls which trace we print. This could be
exposed, but we instead expose three separate
[report_{unification,equality,moregen}_error] functions. This also lets us
give the unification case an extra optional argument without adding it to the
equality and moregen cases. *)
type 'variety trace_format =
| Unification : Errortrace.unification trace_format
| Equality : Errortrace.comparison trace_format
| Moregen : Errortrace.comparison trace_format
let incompatibility_phrase (type variety) : variety trace_format -> string =
function
| Unification -> "is not compatible with type"
| Equality -> "is not equal to type"
| Moregen -> "is not compatible with type"
let printing_status = function
| Errortrace.Diff d -> diff_printing_status d
| Errortrace.Escape {kind = Constraint} -> Keep
| _ -> Keep
(** Flatten the trace and remove elements that are always discarded
during printing *)
(* Takes [printing_status] to change behavior for [Subtype] *)
let prepare_any_trace printing_status tr =
let clean_trace x l = match printing_status x with
| Keep -> x :: l
| Optional_refinement when l = [] -> [x]
| Optional_refinement | Discard -> l
in
match tr with
| [] -> []
| elt :: rem -> elt :: List.fold_right clean_trace rem []
let prepare_trace f tr =
prepare_any_trace printing_status (Errortrace.flatten f tr)
(** Keep elements that are not [Diff _ ] and take the decision
for the last element, require a prepared trace *)
let rec filter_trace trace_format keep_last = function
| [] -> []
| [Errortrace.Diff d as elt]
when printing_status elt = Optional_refinement ->
if keep_last then [d] else []
| Errortrace.Diff d :: rem -> d :: filter_trace trace_format keep_last rem
| _ :: rem -> filter_trace trace_format keep_last rem
let type_path_list =
Format.pp_print_list ~pp_sep:(fun ppf () -> Format.pp_print_break ppf 2 0)
type_path_expansion
(* Hide variant name and var, to force printing the expanded type *)
let hide_variant_name t =
match repr t with
| {desc = Tvariant row} as t when (row_repr row).row_name <> None ->
newty2 t.level
(Tvariant {(row_repr row) with row_name = None;
row_more = newvar2 (row_more row).level})
| _ -> t
let prepare_expansion (t, t') =
let t' = hide_variant_name t' in
mark_loops t;
if not (same_path t t') then mark_loops t';
(t, t')
let may_prepare_expansion compact (t, t') =
match (repr t').desc with
Tvariant _ | Tobject _ when compact ->
mark_loops t; (t, t)
| _ -> prepare_expansion (t, t')
let print_path p = Format.dprintf "%a" !Oprint.out_ident (tree_of_path Type p)
let print_tag ppf = fprintf ppf "`%s"
let print_tags =
let comma ppf () = Format.fprintf ppf ",@ " in
Format.pp_print_list ~pp_sep:comma print_tag
let is_unit env ty =
match (Ctype.expand_head env ty).desc with
| Tconstr (p, _, _) -> Path.same p Predef.path_unit
| _ -> false
let unifiable env ty1 ty2 =
let snap = Btype.snapshot () in
let res =
try Ctype.unify env ty1 ty2; true
with Unify _ -> false
in
Btype.backtrack snap;
res
let explanation_diff env t3 t4 : (Format.formatter -> unit) option =
match t3.desc, t4.desc with
| Tarrow (_, ty1, ty2, _), _
when is_unit env ty1 && unifiable env ty2 t4 ->
Some (fun ppf ->
fprintf ppf
"@,@[Hint: Did you forget to provide `()' as argument?@]")
| _, Tarrow (_, ty1, ty2, _)
when is_unit env ty1 && unifiable env t3 ty2 ->
Some (fun ppf ->
fprintf ppf
"@,@[Hint: Did you forget to wrap the expression using \
`fun () ->'?@]")
| _ ->
None
let explain_fixed_row_case ppf = function
| Errortrace.Cannot_be_closed ->
fprintf ppf "it cannot be closed"
| Errortrace.Cannot_add_tags tags ->
fprintf ppf "it may not allow the tag(s) %a" print_tags tags
let explain_fixed_row pos expl = match expl with
| Fixed_private ->
dprintf "The %a variant type is private" Errortrace.print_pos pos
| Univar x ->
dprintf "The %a variant type is bound to the universal type variable %a"
Errortrace.print_pos pos type_expr x
| Reified p ->
dprintf "The %a variant type is bound to %t"
Errortrace.print_pos pos (print_path p)
| Rigid -> ignore
let explain_variant (type variety) : variety Errortrace.variant -> _ = function
(* Common *)
| Errortrace.Incompatible_types_for s ->
Some(dprintf "@,Types for tag `%s are incompatible" s)
(* Unification *)
| Errortrace.No_intersection ->
Some(dprintf "@,These two variant types have no intersection")
| Errortrace.No_tags(pos,fields) -> Some(
dprintf
"@,@[The %a variant type does not allow tag(s)@ @[<hov>%a@]@]"
Errortrace.print_pos pos
print_tags (List.map fst fields)
)
| Errortrace.Fixed_row (pos,
k,
(Univar _ | Reified _ | Fixed_private as e)) ->
Some (
dprintf "@,@[%t,@ %a@]" (explain_fixed_row pos e)
explain_fixed_row_case k
)
| Errortrace.Fixed_row (_,_, Rigid) ->
(* this case never happens *)
None
(* Equality & Moregen *)
| Errortrace.Openness pos ->
Some(dprintf "@,The %a variant type is open and the %a is not"
Errortrace.print_pos pos
Errortrace.print_pos (Errortrace.swap_position pos))
let explain_escape pre = function
| Errortrace.Univ u -> Some(
dprintf "%t@,The universal variable %a would escape its scope"
pre type_expr u)
| Errortrace.Constructor p -> Some(
dprintf
"%t@,@[The type constructor@;<1 2>%a@ would escape its scope@]"
pre path p
)
| Errortrace.Module_type p -> Some(
dprintf
"%t@,@[The module type@;<1 2>%a@ would escape its scope@]"
pre path p
)
| Errortrace.Equation (_,t) -> Some(
dprintf "%t @,@[<hov>This instance of %a is ambiguous:@ %s@]"
pre type_expr t
"it would escape the scope of its equation"
)
| Errortrace.Self ->
Some (dprintf "%t@,Self type cannot escape its class" pre)
| Errortrace.Constraint ->
None
let explain_object (type variety) : variety Errortrace.obj -> _ = function
| Errortrace.Missing_field (pos,f) -> Some(
dprintf "@,@[The %a object type has no method %s@]"
Errortrace.print_pos pos f
)
| Errortrace.Abstract_row pos -> Some(
dprintf
"@,@[The %a object type has an abstract row, it cannot be closed@]"
Errortrace.print_pos pos
)
| Errortrace.Self_cannot_be_closed ->
Some (dprintf "@,Self type cannot be unified with a closed object type")
let explanation (type variety) intro prev env
: ('a, variety) Errortrace.elt -> _ = function
| Errortrace.Diff { Errortrace.got = _,s; expected = _,t } ->
explanation_diff env s t
| Errortrace.Escape {kind;context} ->
let pre =
match context, kind, prev with
| Some ctx, _, _ ->
dprintf "@[%t@;<1 2>%a@]" intro type_expr ctx
| None, Univ _, Some(Errortrace.Incompatible_fields {name; diff}) ->
dprintf "@,@[The method %s has type@ %a,@ \
but the expected method type was@ %a@]"
name type_expr diff.got type_expr diff.expected
| _ -> ignore
in
explain_escape pre kind
| Errortrace.Incompatible_fields { name; _ } ->
Some(dprintf "@,Types for method %s are incompatible" name)
| Errortrace.Variant v ->
explain_variant v
| Errortrace.Obj o ->
explain_object o
| Errortrace.Rec_occur(x,y) ->
reset_and_mark_loops y;
begin match x.desc with
| Tvar _ | Tunivar _ ->
Some(dprintf "@,@[<hov>The type variable %a occurs inside@ %a@]"
type_expr x type_expr y)
| _ ->
(* We had a delayed unification of the type variable with
a non-variable after the occur check. *)
Some ignore
(* There is no need to search further for an explanation, but
we don't want to print a message of the form:
{[ The type int occurs inside int list -> 'a |}
*)
end
let mismatch intro env trace =
Errortrace.explain trace (fun ~prev h -> explanation intro prev env h)
let explain mis ppf =
match mis with
| None -> ()
| Some explain -> explain ppf
let warn_on_missing_def env ppf t =
match t.desc with
| Tconstr (p,_,_) ->
begin
try
ignore(Env.find_type p env : Types.type_declaration)
with Not_found ->
fprintf ppf
"@,@[%a is abstract because no corresponding cmi file was found \
in path.@]" path p
end
| _ -> ()
let prepare_expansion_head empty_tr = function
| Errortrace.Diff d ->
Some (Errortrace.map_diff (may_prepare_expansion empty_tr) d)
| _ -> None
let head_error_printer txt_got txt_but = function
| None -> ignore
| Some d ->
let d = Errortrace.map_diff trees_of_type_expansion d in
dprintf "%t@;<1 2>%a@ %t@;<1 2>%a"
txt_got type_expansion d.Errortrace.got
txt_but type_expansion d.Errortrace.expected
let warn_on_missing_defs env ppf = function
| None -> ()
| Some {Errortrace.got=te1,_; expected=te2,_ } ->
warn_on_missing_def env ppf te1;
warn_on_missing_def env ppf te2
let error trace_format env tr txt1 ppf txt2 ty_expect_explanation =
reset ();
let tr = prepare_trace (fun t t' -> t, hide_variant_name t') tr in
let mis = mismatch txt1 env tr in
match tr with
| [] -> assert false
| elt :: tr ->
try
print_labels := not !Clflags.classic;
let tr = filter_trace trace_format (mis = None) tr in
let head = prepare_expansion_head (tr=[]) elt in
let tr = List.map (Errortrace.map_diff prepare_expansion) tr in
let head_error = head_error_printer txt1 txt2 head in
let tr = trees_of_trace tr in
fprintf ppf
"@[<v>\
@[%t%t@]%a%t\
@]"
head_error
ty_expect_explanation
(trace false (incompatibility_phrase trace_format)) tr
(explain mis);
if env <> Env.empty
then warn_on_missing_defs env ppf head;
Conflicts.print_explanations ppf;
print_labels := true
with exn ->
print_labels := true;
raise exn
let report_error trace_format ppf env tr
?(type_expected_explanation = fun _ -> ())
txt1 txt2 =
wrap_printing_env env (fun () -> error trace_format env tr txt1 ppf txt2
type_expected_explanation)
~error:true
let report_unification_error =
report_error Unification
let report_equality_error =
report_error Equality ?type_expected_explanation:None
let report_moregen_error =
report_error Moregen ?type_expected_explanation:None
module Subtype = struct
(* There's a frustrating amount of code duplication between this module and
the outside code, particularly in [prepare_trace] and [filter_trace].
Unfortunately, [Subtype] is *just* similar enough to have code duplication,
while being *just* different enough (it's only [Diff]) for the abstraction
to be nonobvious. Someday, perhaps... *)
let printing_status = function
| Errortrace.Subtype.Diff d -> diff_printing_status d
let prepare_unification_trace = prepare_trace
let prepare_trace f tr =
prepare_any_trace printing_status (Errortrace.Subtype.flatten f tr)
let trace filter_trace get_diff fst keep_last txt ppf tr =
print_labels := not !Clflags.classic;
try match tr with
| elt :: tr' ->
let diffed_elt = get_diff elt in
let tr =
trees_of_trace
@@ List.map (Errortrace.map_diff prepare_expansion)
@@ filter_trace keep_last tr' in
let tr =
match fst, diffed_elt with
| true, Some elt -> elt :: tr
| _, _ -> tr
in
trace fst txt ppf tr;
print_labels := true
| _ -> ()
with exn ->
print_labels := true;
raise exn
let filter_unification_trace = filter_trace Unification
let rec filter_subtype_trace keep_last = function
| [] -> []
| [Errortrace.Subtype.Diff d as elt]
when printing_status elt = Optional_refinement ->
if keep_last then [d] else []
| Errortrace.Subtype.Diff d :: rem ->
d :: filter_subtype_trace keep_last rem
let unification_get_diff = function
| Errortrace.Diff diff ->
Some (Errortrace.map_diff trees_of_type_expansion diff)
| _ -> None
let subtype_get_diff = function
| Errortrace.Subtype.Diff diff ->
Some (Errortrace.map_diff trees_of_type_expansion diff)
let report_error ppf env tr1 txt1 tr2 =
wrap_printing_env ~error:true env (fun () ->
reset ();
let tr1 =
prepare_trace (fun t t' -> prepare_expansion (t, t')) tr1
in
let tr2 =
prepare_unification_trace (fun t t' -> prepare_expansion (t, t')) tr2
in
let keep_first = match tr2 with
| [Obj _ | Variant _ | Escape _ ] | [] -> true
| _ -> false in
fprintf ppf "@[<v>%a"
(trace filter_subtype_trace subtype_get_diff true keep_first txt1) tr1;
if tr2 = [] then fprintf ppf "@]" else
let mis = mismatch (dprintf "Within this type") env tr2 in
fprintf ppf "%a%t%t@]"
(trace filter_unification_trace unification_get_diff false
(mis = None) "is not compatible with type") tr2
(explain mis)
Conflicts.print_explanations
)
end
let report_ambiguous_type_error ppf env tp0 tpl txt1 txt2 txt3 =
wrap_printing_env ~error:true env (fun () ->
reset ();
let tp0 = trees_of_type_path_expansion tp0 in
match tpl with
[] -> assert false
| [tp] ->
fprintf ppf
"@[%t@;<1 2>%a@ \
%t@;<1 2>%a\
@]"
txt1 type_path_expansion (trees_of_type_path_expansion tp)
txt3 type_path_expansion tp0
| _ ->
fprintf ppf
"@[%t@;<1 2>@[<hv>%a@]\
@ %t@;<1 2>%a\
@]"
txt2 type_path_list (List.map trees_of_type_path_expansion tpl)
txt3 type_path_expansion tp0)
(* Adapt functions to exposed interface *)
let tree_of_path = tree_of_path Other
let tree_of_modtype = tree_of_modtype ~ellipsis:false
let type_expansion ty ppf ty' =
type_expansion ppf (trees_of_type_expansion (ty,ty'))
let tree_of_type_declaration ident td rs =
with_hidden_items [{hide=true; ident}]
(fun () -> tree_of_type_declaration ident td rs)
| (**************************************************************************)
(* *)
(* OCaml *)
(* *)
(* Xavier Leroy and Jerome Vouillon, 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. *)
(* *)
(**************************************************************************)
|
version-404.h |
#define OCAML_VERSION_MAJOR 4
#define OCAML_VERSION_MINOR 4
#define OCAML_VERSION_PATCHLEVEL 2
#undef OCAML_VERSION_ADDITIONAL
#define OCAML_VERSION 40402
#define OCAML_VERSION_STRING "4.04.2"
| |
mempool.ml | open Protocol
open Alpha_context
type error_classification =
[ `Branch_delayed of tztrace
| `Branch_refused of tztrace
| `Refused of tztrace
| `Outdated of tztrace ]
type nanotez = Q.t
let nanotez_enc : nanotez Data_encoding.t =
let open Data_encoding in
def
"nanotez"
~title:"A thousandth of a mutez"
~description:"One thousand nanotez make a mutez (1 tez = 1e9 nanotez)"
(conv
(fun q -> (q.Q.num, q.Q.den))
(fun (num, den) -> {Q.num; den})
(tup2 z z))
let manager_op_replacement_factor_enc : Q.t Data_encoding.t =
let open Data_encoding in
def
"manager operation replacement factor"
~title:"A manager operation's replacement factor"
~description:"The fee and fee/gas ratio of an operation to replace another"
(conv
(fun q -> (q.Q.num, q.Q.den))
(fun (num, den) -> {Q.num; den})
(tup2 z z))
type config = {
minimal_fees : Tez.t;
minimal_nanotez_per_gas_unit : nanotez;
minimal_nanotez_per_byte : nanotez;
allow_script_failure : bool;
(** If [true], this makes [post_filter_manager] unconditionally return
[`Passed_postfilter filter_state], no matter the operation's
success. *)
clock_drift : Period.t option;
replace_by_fee_factor : Q.t;
(** This field determines the amount of additional fees (given as a
factor of the declared fees) a manager should add to an operation
in order to (eventually) replace an existing (prechecked) one
in the mempool. Note that other criteria, such as the gas ratio,
are also taken into account to decide whether to accept the
replacement or not. *)
max_prechecked_manager_operations : int;
(** Maximal number of prechecked operations to keep. The mempool only
keeps the [max_prechecked_manager_operations] operations with the
highest fee/gas and fee/size ratios. *)
}
let default_minimal_fees =
match Tez.of_mutez 100L with None -> assert false | Some t -> t
let default_minimal_nanotez_per_gas_unit = Q.of_int 100
let default_minimal_nanotez_per_byte = Q.of_int 1000
let managers_quota =
Stdlib.List.nth Main.validation_passes Operation_repr.manager_pass
(* If the drift is not specified, it will be the duration of round zero.
It allows only to spam with one future round.
/!\ Warning /!\ : current plugin implementation implies that this drift
cumulates with the accepted drift regarding the current head's timestamp.
*)
let default_config =
{
minimal_fees = default_minimal_fees;
minimal_nanotez_per_gas_unit = default_minimal_nanotez_per_gas_unit;
minimal_nanotez_per_byte = default_minimal_nanotez_per_byte;
allow_script_failure = true;
clock_drift = None;
replace_by_fee_factor =
Q.make (Z.of_int 105) (Z.of_int 100)
(* Default value of [replace_by_fee_factor] is set to 5% *);
max_prechecked_manager_operations = 5_000;
}
let config_encoding : config Data_encoding.t =
let open Data_encoding in
conv
(fun {
minimal_fees;
minimal_nanotez_per_gas_unit;
minimal_nanotez_per_byte;
allow_script_failure;
clock_drift;
replace_by_fee_factor;
max_prechecked_manager_operations;
} ->
( minimal_fees,
minimal_nanotez_per_gas_unit,
minimal_nanotez_per_byte,
allow_script_failure,
clock_drift,
replace_by_fee_factor,
max_prechecked_manager_operations ))
(fun ( minimal_fees,
minimal_nanotez_per_gas_unit,
minimal_nanotez_per_byte,
allow_script_failure,
clock_drift,
replace_by_fee_factor,
max_prechecked_manager_operations ) ->
{
minimal_fees;
minimal_nanotez_per_gas_unit;
minimal_nanotez_per_byte;
allow_script_failure;
clock_drift;
replace_by_fee_factor;
max_prechecked_manager_operations;
})
(obj7
(dft "minimal_fees" Tez.encoding default_config.minimal_fees)
(dft
"minimal_nanotez_per_gas_unit"
nanotez_enc
default_config.minimal_nanotez_per_gas_unit)
(dft
"minimal_nanotez_per_byte"
nanotez_enc
default_config.minimal_nanotez_per_byte)
(dft "allow_script_failure" bool default_config.allow_script_failure)
(opt "clock_drift" Period.encoding)
(dft
"replace_by_fee_factor"
manager_op_replacement_factor_enc
default_config.replace_by_fee_factor)
(dft
"max_prechecked_manager_operations"
int31
default_config.max_prechecked_manager_operations))
(** An Alpha_context manager operation, packed so that the type is not
parametrized by ['kind]. *)
type manager_op = Manager_op : 'kind Kind.manager operation -> manager_op
(** Information stored for each prechecked manager operation.
Note that this record does not include the operation hash because
it is instead used as key in the map that stores this information
in the [state] below. *)
type manager_op_info = {
manager_op : manager_op;
(** Used when we want to remove the operation with
{!Validate.remove_manager_operation}. *)
fee : Tez.t;
gas_limit : Fixed_point_repr.integral_tag Gas.Arith.t;
(** Both [fee] and [gas_limit] are used to determine whether a new
operation from the same manager should replace this one. *)
weight : Q.t;
(** Used to update [ops_prechecked] and [min_prechecked_op_weight]
in [state] when appropriate. *)
}
type manager_op_weight = {operation_hash : Operation_hash.t; weight : Q.t}
(** Build a {!manager_op_weight} from operation hash and {!manager_op_info}. *)
let mk_op_weight oph (info : manager_op_info) =
{operation_hash = oph; weight = info.weight}
let compare_manager_op_weight op1 op2 =
let c = Q.compare op1.weight op2.weight in
if c <> 0 then c
else Operation_hash.compare op1.operation_hash op2.operation_hash
module ManagerOpWeightSet = Set.Make (struct
type t = manager_op_weight
(* Sort by weight *)
let compare = compare_manager_op_weight
end)
(** Static information to store in the filter state. *)
type state_info = {
head : Block_header.shell_header;
round_durations : Round.round_durations;
hard_gas_limit_per_block : Gas.Arith.integral;
head_round : Round.t;
round_zero_duration : Period.t;
grandparent_level_start : Timestamp.t;
}
(** State that tracks validated manager operations. *)
type ops_state = {
prechecked_manager_op_count : int;
(** Number of prechecked manager operations.
Invariants:
- [prechecked_manager_op_count
= Operation_hash.Map.cardinal prechecked_manager_ops
= ManagerOpWeightSet.cardinal prechecked_op_weights]
- [prechecked_manager_op_count <= max_prechecked_manager_operations] *)
prechecked_manager_ops : manager_op_info Operation_hash.Map.t;
(** All prechecked manager operations. See {!manager_op_info}. *)
prechecked_op_weights : ManagerOpWeightSet.t;
(** The {!manager_op_weight} of all prechecked manager operations. *)
min_prechecked_op_weight : manager_op_weight option;
(** The prechecked operation in [op_prechecked_managers], if any, with
the minimal weight.
Invariant:
- [min_prechecked_op_weight = min { x | x \in prechecked_op_weights }] *)
}
type state = {state_info : state_info; ops_state : ops_state}
let empty_ops_state =
{
prechecked_manager_op_count = 0;
prechecked_manager_ops = Operation_hash.Map.empty;
prechecked_op_weights = ManagerOpWeightSet.empty;
min_prechecked_op_weight = None;
}
let init_state_prototzresult ~head round_durations hard_gas_limit_per_block =
let open Lwt_result_syntax in
let*? head_round =
Alpha_context.Fitness.round_from_raw head.Tezos_base.Block_header.fitness
in
let round_zero_duration = Round.round_duration round_durations Round.zero in
let*? grandparent_round =
Alpha_context.Fitness.predecessor_round_from_raw head.fitness
in
let*? proposal_level_offset =
Round.level_offset_of_round
round_durations
~round:Round.(succ grandparent_round)
in
let*? proposal_round_offset =
Round.level_offset_of_round round_durations ~round:head_round
in
let*? proposal_offset =
Period.(add proposal_level_offset proposal_round_offset)
in
let grandparent_level_start = Timestamp.(head.timestamp - proposal_offset) in
let state_info =
{
head;
round_durations;
hard_gas_limit_per_block;
head_round;
round_zero_duration;
grandparent_level_start;
}
in
return {state_info; ops_state = empty_ops_state}
let init_state ~head round_durations hard_gas_limit_per_block =
Lwt.map
Environment.wrap_tzresult
(init_state_prototzresult ~head round_durations hard_gas_limit_per_block)
let init context ~(head : Tezos_base.Block_header.shell_header) =
let open Lwt_result_syntax in
let* ( ctxt,
(_ : Receipt.balance_updates),
(_ : Migration.origination_result list) ) =
prepare
context
~level:(Int32.succ head.level)
~predecessor_timestamp:head.timestamp
~timestamp:head.timestamp
|> Lwt.map Environment.wrap_tzresult
in
let round_durations = Constants.round_durations ctxt in
let hard_gas_limit_per_block = Constants.hard_gas_limit_per_block ctxt in
init_state ~head round_durations hard_gas_limit_per_block
let flush old_state ~head =
(* To avoid the need to prepare a context as in [init], we retrieve
the [round_durations] from the previous state. Indeed, they are
only determined by the [minimal_block_delay] and
[delay_increment_per_round] constants (see
{!Raw_context.prepare}), and all the constants remain unchanged
during the lifetime of a protocol. As to
[hard_gas_limit_per_block], it is directly a protocol
constant. *)
init_state
~head
old_state.state_info.round_durations
old_state.state_info.hard_gas_limit_per_block
let manager_prio p = `Low p
let consensus_prio = `High
let other_prio = `Medium
let get_manager_operation_gas_and_fee contents =
let open Operation in
let l = to_list (Contents_list contents) in
List.fold_left
(fun acc -> function
| Contents (Manager_operation {fee; gas_limit; _}) -> (
match acc with
| Error _ as e -> e
| Ok (total_fee, total_gas) -> (
match Tez.(total_fee +? fee) with
| Ok total_fee -> Ok (total_fee, Gas.Arith.add total_gas gas_limit)
| Error _ as e -> e))
| _ -> acc)
(Ok (Tez.zero, Gas.Arith.zero))
l
type Environment.Error_monad.error += Fees_too_low
let () =
Environment.Error_monad.register_error_kind
`Permanent
~id:"prefilter.fees_too_low"
~title:"Operation fees are too low"
~description:"Operation fees are too low"
~pp:(fun ppf () -> Format.fprintf ppf "Operation fees are too low")
Data_encoding.unit
(function Fees_too_low -> Some () | _ -> None)
(fun () -> Fees_too_low)
type Environment.Error_monad.error +=
| Manager_restriction of {oph : Operation_hash.t; fee : Tez.t}
let () =
Environment.Error_monad.register_error_kind
`Temporary
~id:"prefilter.manager_restriction"
~title:"Only one manager operation per manager per block allowed"
~description:"Only one manager operation per manager per block allowed"
~pp:(fun ppf (oph, fee) ->
Format.fprintf
ppf
"Only one manager operation per manager per block allowed (found %a \
with %atez fee. You may want to use --replace to provide adequate fee \
and replace it)."
Operation_hash.pp
oph
Tez.pp
fee)
Data_encoding.(
obj2
(req "operation_hash" Operation_hash.encoding)
(req "operation_fee" Tez.encoding))
(function Manager_restriction {oph; fee} -> Some (oph, fee) | _ -> None)
(fun (oph, fee) -> Manager_restriction {oph; fee})
type Environment.Error_monad.error +=
| Manager_operation_replaced of {
old_hash : Operation_hash.t;
new_hash : Operation_hash.t;
}
let () =
Environment.Error_monad.register_error_kind
`Permanent
~id:"plugin.manager_operation_replaced"
~title:"Manager operation replaced"
~description:"The manager operation has been replaced"
~pp:(fun ppf (old_hash, new_hash) ->
Format.fprintf
ppf
"The manager operation %a has been replaced with %a"
Operation_hash.pp
old_hash
Operation_hash.pp
new_hash)
(Data_encoding.obj2
(Data_encoding.req "old_hash" Operation_hash.encoding)
(Data_encoding.req "new_hash" Operation_hash.encoding))
(function
| Manager_operation_replaced {old_hash; new_hash} ->
Some (old_hash, new_hash)
| _ -> None)
(fun (old_hash, new_hash) ->
Manager_operation_replaced {old_hash; new_hash})
type Environment.Error_monad.error += Fees_too_low_for_mempool of Tez.t
let () =
Environment.Error_monad.register_error_kind
`Temporary
~id:"prefilter.fees_too_low_for_mempool"
~title:"Operation fees are too low to be considered in full mempool"
~description:"Operation fees are too low to be considered in full mempool"
~pp:(fun ppf required_fees ->
Format.fprintf
ppf
"The mempool is full, the number of prechecked manager operations has \
reached the limit max_prechecked_manager_operations set by the \
filter. Increase operation fees to at least %atz for the operation to \
be considered and propagated by THIS node. Note that the operations \
with the minimum fees in the mempool risk being removed if better \
ones are received."
Tez.pp
required_fees)
Data_encoding.(obj1 (req "required_fees" Tez.encoding))
(function
| Fees_too_low_for_mempool required_fees -> Some required_fees | _ -> None)
(fun required_fees -> Fees_too_low_for_mempool required_fees)
type Environment.Error_monad.error += Removed_fees_too_low_for_mempool
let () =
Environment.Error_monad.register_error_kind
`Temporary
~id:"plugin.removed_fees_too_low_for_mempool"
~title:"Operation removed because fees are too low for full mempool"
~description:"Operation removed because fees are too low for full mempool"
~pp:(fun ppf () ->
Format.fprintf
ppf
"The mempool is full, the number of prechecked manager operations has \
reached the limit max_prechecked_manager_operations set by the \
filter. Operation was removed because another operation with a better \
fees/gas-size ratio was received and accepted by the mempool.")
Data_encoding.unit
(function Removed_fees_too_low_for_mempool -> Some () | _ -> None)
(fun () -> Removed_fees_too_low_for_mempool)
(* TODO: https://gitlab.com/tezos/tezos/-/issues/2238
Write unit tests for the feature 'replace-by-fee' and for other changes
introduced by other MRs in the plugin. *)
(* In order to decide if the new operation can replace an old one from the
same manager, we check if its fees (resp. fees/gas ratio) are greater than
(or equal to) the old operations's fees (resp. fees/gas ratio), bumped by
the factor [config.replace_by_fee_factor].
*)
let better_fees_and_ratio =
let bump config q = Q.mul q config.replace_by_fee_factor in
fun config old_gas old_fee new_gas new_fee ->
let old_fee = Tez.to_mutez old_fee |> Z.of_int64 |> Q.of_bigint in
let old_gas = Gas.Arith.integral_to_z old_gas |> Q.of_bigint in
let new_fee = Tez.to_mutez new_fee |> Z.of_int64 |> Q.of_bigint in
let new_gas = Gas.Arith.integral_to_z new_gas |> Q.of_bigint in
let old_ratio = Q.div old_fee old_gas in
let new_ratio = Q.div new_fee new_gas in
Q.compare new_ratio (bump config old_ratio) >= 0
&& Q.compare new_fee (bump config old_fee) >= 0
let size_of_operation op =
(WithExceptions.Option.get ~loc:__LOC__
@@ Data_encoding.Binary.fixed_length
Tezos_base.Operation.shell_header_encoding)
+ Data_encoding.Binary.length Operation.protocol_data_encoding op
(** Returns the weight and resources consumption of an operation. The weight
corresponds to the one implemented by the baker, to decide which operations
to put in a block first (the code is largely duplicated).
See {!Tezos_baking_alpha.Operation_selection.weight_manager} *)
let weight_and_resources_manager_operation ~hard_gas_limit_per_block ?size ~fee
~gas op =
let max_size = managers_quota.max_size in
let size = match size with None -> size_of_operation op | Some s -> s in
let size_f = Q.of_int size in
let gas_f = Q.of_bigint (Gas.Arith.integral_to_z gas) in
let fee_f = Q.of_int64 (Tez.to_mutez fee) in
let size_ratio = Q.(size_f / Q.of_int max_size) in
let gas_ratio =
Q.(gas_f / Q.of_bigint (Gas.Arith.integral_to_z hard_gas_limit_per_block))
in
let resources = Q.max size_ratio gas_ratio in
(Q.(fee_f / resources), resources)
(** Return fee for an operation that consumes [op_resources] for its weight to
be strictly greater than [min_weight]. *)
let required_fee_manager_operation_weight ~op_resources ~min_weight =
let req_mutez_q = Q.((min_weight * op_resources) + Q.one) in
Tez.of_mutez_exn @@ Q.to_int64 req_mutez_q
(** Check if an operation as a weight (fees w.r.t gas and size) large enough to
be prechecked and return said weight. In the case where the prechecked
mempool is full, return an error if the weight is too small, or return the
operation to be replaced otherwise. *)
let check_minimal_weight config state ~fee ~gas_limit op =
let weight, op_resources =
weight_and_resources_manager_operation
~hard_gas_limit_per_block:state.state_info.hard_gas_limit_per_block
~fee
~gas:gas_limit
op
in
if
state.ops_state.prechecked_manager_op_count
< config.max_prechecked_manager_operations
then
(* The precheck mempool is not full yet *)
`Weight_ok (`No_replace, [weight])
else
match state.ops_state.min_prechecked_op_weight with
| None ->
(* The precheck mempool is empty *)
`Weight_ok (`No_replace, [weight])
| Some {weight = min_weight; operation_hash = min_oph} ->
if Q.(weight > min_weight) then
(* The operation has a weight greater than the minimal
prechecked operation, replace the latest with the new one *)
`Weight_ok (`Replace min_oph, [weight])
else
(* Otherwise fail and give indication as to what to fee should
be for the operation to be prechecked *)
let required_fee =
required_fee_manager_operation_weight ~op_resources ~min_weight
in
`Fail
(`Branch_delayed
[Environment.wrap_tzerror (Fees_too_low_for_mempool required_fee)])
let pre_filter_manager :
type t.
config ->
state ->
Operation.packed_protocol_data ->
t Kind.manager contents_list ->
[ `Passed_prefilter of Q.t list
| `Branch_refused of tztrace
| `Branch_delayed of tztrace
| `Refused of tztrace
| `Outdated of tztrace ] =
fun config filter_state packed_op op ->
let size = size_of_operation packed_op in
let check_gas_and_fee fee gas_limit =
let fees_in_nanotez =
Q.mul (Q.of_int64 (Tez.to_mutez fee)) (Q.of_int 1000)
in
let minimal_fees_in_nanotez =
Q.mul (Q.of_int64 (Tez.to_mutez config.minimal_fees)) (Q.of_int 1000)
in
let minimal_fees_for_gas_in_nanotez =
Q.mul
config.minimal_nanotez_per_gas_unit
(Q.of_bigint @@ Gas.Arith.integral_to_z gas_limit)
in
let minimal_fees_for_size_in_nanotez =
Q.mul config.minimal_nanotez_per_byte (Q.of_int size)
in
if
Q.compare
fees_in_nanotez
(Q.add
minimal_fees_in_nanotez
(Q.add
minimal_fees_for_gas_in_nanotez
minimal_fees_for_size_in_nanotez))
>= 0
then `Fees_ok
else `Refused [Environment.wrap_tzerror Fees_too_low]
in
match get_manager_operation_gas_and_fee op with
| Error err -> `Refused (Environment.wrap_tztrace err)
| Ok (fee, gas_limit) -> (
match check_gas_and_fee fee gas_limit with
| `Refused _ as err -> err
| `Fees_ok -> (
match
check_minimal_weight config filter_state ~fee ~gas_limit packed_op
with
| `Fail errs -> errs
| `Weight_ok (_, weight) -> `Passed_prefilter weight))
type Environment.Error_monad.error += Wrong_operation
let () =
Environment.Error_monad.register_error_kind
`Temporary
~id:"prefilter.wrong_operation"
~title:"Wrong operation"
~description:"Failing_noop operations are not accepted in the mempool."
~pp:(fun ppf () ->
Format.fprintf
ppf
"Failing_noop operations are not accepted in the mempool")
Data_encoding.unit
(function Wrong_operation -> Some () | _ -> None)
(fun () -> Wrong_operation)
type Environment.Error_monad.error += Consensus_operation_in_far_future
let () =
Environment.Error_monad.register_error_kind
`Branch
~id:"prefilter.Consensus_operation_in_far_future"
~title:"Consensus operation in far future"
~description:"Consensus operation too far in the future are not accepted."
~pp:(fun ppf () ->
Format.fprintf
ppf
"Consensus operation too far in the future are not accepted.")
Data_encoding.unit
(function Consensus_operation_in_far_future -> Some () | _ -> None)
(fun () -> Consensus_operation_in_far_future)
(** {2 consensus operation filtering}
In Tenderbake, we increased a lot the number of consensus
operations, therefore it seems necessary to be able to filter consensus
operations that could be produced by a Byzantine baker mis-using
its right to produce operations in future rounds or levels.
We consider the situation where the head is at level [h_l],
round [h_r], and with timestamp [h_ts], with the predecessor of the head
being at round [hp_r].
We receive at a time [now] a consensus operation for level [op_l] and
round [op_r].
A consensus operation is considered too far in the future, and therefore filtered,
if the earliest possible starting time of its round is greater than the
current time plus a safety margin of [config.clock_drift].
To consider potential level 2 reorgs, we first compute the expected
timestamp of round zero at previous level [hp0_ts],
All ops at level p_l and round r' such that time(r') is greater than (now + drift) are
deemed too far in the future:
h_r op_ts now+drift (h_l,r')
hp0_ts h_0 h_l | | |
+----+-----+---------+-------------------+--+-----+--------------+-----------
| | | | | | |
| h_ts h_r end time | now | earliest expected
| | | | time of round r'
|<----op_r rounds duration -------->| |
|
|<--------------- operations kept ---->|<-rejected----------...
|
|<-----------operations considered by the filter -----------...
For an operation on a proposal at the next level, we consider the minimum
starting time of the operation's round, obtained by assuming that the proposal
at the next level was built on top of a proposal at round 0 for the current
level, itself based on a proposal at round 0 of previous level.
Operations on proposal with higher levels are treated similarly.
All ops at the next level and round r' such that timestamp(r') > now+drift
are deemed too far in the future.
r=0 r=1 h_r now now+drift (h_l+1,r')
hp0_ts h_0 h_l h_l | | |
+----+---- |-------+----+---------+----------+----------+----------
| | | | |
| t0 | h_ts earliest expected
| | | | time of round r'
|<--- | earliest| |
| next level| |
| |<---------------------------------->|
round_offset(r')
*)
(** At a given level a consensus operation is acceptable if its earliest
expected timestamp, [op_earliest_ts] is below the current clock with an
accepted drift for the clock given by a configuration. *)
let acceptable ~drift ~op_earliest_ts ~now_timestamp =
Timestamp.(
now_timestamp +? drift >|? fun now_drifted -> op_earliest_ts <= now_drifted)
(** Check that an operation with the given [op_round], at level [op_level]
is likely to be correct, meaning it could have been produced before
now (+ the safety margin from configuration).
Given an operation at level greater or equal than/to the current level, we
compute the expected timestamp of the operation's round. If the operation
is at a greater level, we assume that it is based on the proposal at round
zero of the current level.
All operations whose (level, round) is lower than or equal to the current
head are deemed valid.
Note that in case where their is a high drift in the computer clock, they
might not have been considered valid by comparing their expected timestamp
to the clock.
This is a stricter than necessary filter as it will reject operations that
could be valid in the current timeframe if the proposal they endorse is
built over a predecessor of the current proposal that would be of lower
round than the current one.
What can we do that would be smarter: get current head's predecessor round
and timestamp to compute the timestamp t0 of a predecessor that would have
been proposed at round 0.
Timestamp of round at current level for an alternative head that would be
based on such proposal would be computed based on t0.
For level higher than current head, compute the round's earliest timestamp
if all proposal passed at round 0 starting from t0.
*)
let acceptable_op ~config ~round_durations ~round_zero_duration ~proposal_level
~proposal_round ~proposal_timestamp
~(proposal_predecessor_level_start : Timestamp.t) ~op_level ~op_round
~now_timestamp =
if
Raw_level.(succ op_level < proposal_level)
|| (op_level = proposal_level && op_round <= proposal_round)
then
(* Past and current round operations are not in the future *)
(* This case could be handled directly in `pre_filter_far_future_consensus_ops`
for a (slightly) better performance. *)
Ok true
else
(* If, by some tolerance on local clock drift, the timestamp of the
current head is itself in the future, we use this time instead of
now_timestamp *)
let now_timestamp = Timestamp.(max now_timestamp proposal_timestamp) in
(* Computing when the current level started. *)
let drift = Option.value ~default:round_zero_duration config.clock_drift in
(* We compute the earliest timestamp possible [op_earliest_ts] for the
operation's (level,round), as if all proposals were accepted at round 0
since the previous level. *)
(* Invariant: [op_level + 1 >= proposal_level] *)
let level_offset = Raw_level.(diff (succ op_level) proposal_level) in
Period.mult level_offset round_zero_duration >>? fun time_shift ->
Timestamp.(proposal_predecessor_level_start +? time_shift)
>>? fun earliest_op_level_start ->
(* computing the operations's round start from it's earliest
possible level start *)
Round.timestamp_of_another_round_same_level
round_durations
~current_round:Round.zero
~current_timestamp:earliest_op_level_start
~considered_round:op_round
>>? fun op_earliest_ts ->
(* We finally check that the expected time of the operation is
acceptable *)
acceptable ~drift ~op_earliest_ts ~now_timestamp
let pre_filter_far_future_consensus_ops config ~filter_state
({level = op_level; round = op_round; _} : consensus_content) : bool Lwt.t =
let res =
let open Result_syntax in
let now_timestamp = Time.System.now () |> Time.System.to_protocol in
let* proposal_level =
Raw_level.of_int32 filter_state.state_info.head.level
in
acceptable_op
~config
~round_durations:filter_state.state_info.round_durations
~round_zero_duration:filter_state.state_info.round_zero_duration
~proposal_level
~proposal_round:filter_state.state_info.head_round
~proposal_timestamp:filter_state.state_info.head.timestamp
~proposal_predecessor_level_start:
filter_state.state_info.grandparent_level_start
~op_level
~op_round
~now_timestamp
in
match res with Ok b -> Lwt.return b | Error _ -> Lwt.return_false
(** A quasi infinite amount of "valid" (pre)endorsements could be
sent by a committee member, one for each possible round number.
This filter rejects (pre)endorsements that refer to a round
that could not have been reached within the time span between
the last head's timestamp and the current local clock.
We add [config.clock_drift] time as a safety margin.
*)
let pre_filter config ~filter_state
({shell = _; protocol_data = Operation_data {contents; _} as op} :
Main.operation) =
let prefilter_manager_op manager_op =
Lwt.return
@@
match pre_filter_manager config filter_state op manager_op with
| `Passed_prefilter prio -> `Passed_prefilter (manager_prio prio)
| (`Branch_refused _ | `Branch_delayed _ | `Refused _ | `Outdated _) as err
->
err
in
match contents with
| Single (Failing_noop _) ->
Lwt.return (`Refused [Environment.wrap_tzerror Wrong_operation])
| Single (Preendorsement consensus_content)
| Single (Endorsement consensus_content) ->
pre_filter_far_future_consensus_ops ~filter_state config consensus_content
>>= fun keep ->
if keep then Lwt.return @@ `Passed_prefilter consensus_prio
else
Lwt.return
(`Branch_refused
[Environment.wrap_tzerror Consensus_operation_in_far_future])
| Single (Dal_slot_availability _)
| Single (Seed_nonce_revelation _)
| Single (Double_preendorsement_evidence _)
| Single (Double_endorsement_evidence _)
| Single (Double_baking_evidence _)
| Single (Activate_account _)
| Single (Proposals _)
| Single (Vdf_revelation _)
| Single (Drain_delegate _)
| Single (Ballot _) ->
Lwt.return @@ `Passed_prefilter other_prio
| Single (Manager_operation _) as op -> prefilter_manager_op op
| Cons (Manager_operation _, _) as op -> prefilter_manager_op op
(** Remove a manager operation hash from the ops_state.
Do nothing if the operation was not in the state. *)
let remove_operation ops_state oph =
match Operation_hash.Map.find oph ops_state.prechecked_manager_ops with
| None ->
(* Not present in the ops_state: nothing to do. *)
ops_state
| Some info ->
let prechecked_manager_ops =
Operation_hash.Map.remove oph ops_state.prechecked_manager_ops
in
let prechecked_manager_op_count =
ops_state.prechecked_manager_op_count - 1
in
let prechecked_op_weights =
ManagerOpWeightSet.remove
(mk_op_weight oph info)
ops_state.prechecked_op_weights
in
let min_prechecked_op_weight =
match ops_state.min_prechecked_op_weight with
| None -> None
| Some min_op_weight ->
if Operation_hash.equal min_op_weight.operation_hash oph then
ManagerOpWeightSet.min_elt prechecked_op_weights
else Some min_op_weight
in
{
prechecked_manager_op_count;
prechecked_manager_ops;
prechecked_op_weights;
min_prechecked_op_weight;
}
(** Remove a manager operation hash from the ops_state.
Do nothing if the operation was not in the state. *)
let remove ~filter_state oph =
{filter_state with ops_state = remove_operation filter_state.ops_state oph}
(** Add a manager operation hash and information to the filter state.
Do nothing if the operation is already present in the state. *)
let add_manager_op ops_state oph info replacement =
let ops_state =
match replacement with
| `No_replace -> ops_state
| `Replace (oph, _classification) -> remove_operation ops_state oph
in
if Operation_hash.Map.mem oph ops_state.prechecked_manager_ops then
(* Already present in the ops_state: nothing to do. *)
ops_state
else
let prechecked_manager_op_count =
ops_state.prechecked_manager_op_count + 1
in
let prechecked_manager_ops =
Operation_hash.Map.add oph info ops_state.prechecked_manager_ops
in
let op_weight = mk_op_weight oph info in
let prechecked_op_weights =
ManagerOpWeightSet.add op_weight ops_state.prechecked_op_weights
in
let min_prechecked_op_weight =
match ops_state.min_prechecked_op_weight with
| Some old_min when compare_manager_op_weight old_min op_weight <= 0 ->
Some old_min
| _ -> Some op_weight
in
{
prechecked_manager_op_count;
prechecked_manager_ops;
prechecked_op_weights;
min_prechecked_op_weight;
}
let add_manager_op_and_enforce_mempool_bound config filter_state oph
(op : 'manager_kind Kind.manager operation) =
let open Lwt_result_syntax in
let*? fee, gas_limit =
Result.map_error
(fun err -> `Refused (Environment.wrap_tztrace err))
(get_manager_operation_gas_and_fee op.protocol_data.contents)
in
let* replacement, weight =
match
check_minimal_weight
config
filter_state
~fee
~gas_limit
(Operation_data op.protocol_data)
with
| `Weight_ok (`No_replace, weight) ->
(* The mempool is not full: no need to replace any operation. *)
return (`No_replace, weight)
| `Weight_ok (`Replace min_weight_oph, weight) ->
(* The mempool is full yet the new operation has enough weight
to be included: the old operation with the lowest weight is
reclassified as [Branch_delayed]. *)
(* TODO: https://gitlab.com/tezos/tezos/-/issues/2347 The
branch_delayed ring is bounded to 1000, so we may loose
operations. We can probably do better. *)
let replace_err =
Environment.wrap_tzerror Removed_fees_too_low_for_mempool
in
let replacement =
`Replace (min_weight_oph, `Branch_delayed [replace_err])
in
return (replacement, weight)
| `Fail err ->
(* The mempool is full and the weight of the new operation is
too low: raise the error returned by {!check_minimal_weight}. *)
fail err
in
let weight = match weight with [x] -> x | _ -> assert false in
let info = {manager_op = Manager_op op; gas_limit; fee; weight} in
let ops_state = add_manager_op filter_state.ops_state oph info replacement in
return ({filter_state with ops_state}, replacement)
(** If the provided operation is a manager operation, add it to the
filter_state. If the mempool is full, either return an error if the
operation does not have enough weight to be included, or return the
operation with minimal weight that gets removed to make room.
Do nothing on non-manager operations.
If [replace] is provided, then it is removed from [filter_state]
before processing [op]. (If [replace] is a non-manager operation,
this does nothing since it was never in [filter_state] to begin with.)
Note that when this happens, the mempool can no longer be full after
the operation has been removed, so this function always returns
[`No_replace].
This function is designed to be called by the shell each time a
new operation has been validated by the protocol. It will be
removed in the future once the shell is able to bound the number of
operations in the mempool by itself. *)
let add_operation_and_enforce_mempool_bound ?replace config filter_state
(oph, op) =
let filter_state =
match replace with
| Some replace_oph ->
(* If the operation to replace is not a manager operation, then
it cannot be present in the [filter_state]. But then,
[remove] does nothing anyway. *)
remove ~filter_state replace_oph
| None -> filter_state
in
let {protocol_data = Operation_data protocol_data; _} = op in
let call_manager protocol_data =
add_manager_op_and_enforce_mempool_bound
config
filter_state
oph
{shell = op.shell; protocol_data}
in
match protocol_data.contents with
| Single (Manager_operation _) -> call_manager protocol_data
| Cons (Manager_operation _, _) -> call_manager protocol_data
| Single _ -> return (filter_state, `No_replace)
let is_manager_operation op =
match Operation.acceptable_pass op with
| Some pass -> Compare.Int.equal pass Operation_repr.manager_pass
| None -> false
(** [conflict_handler config] returns a conflict handler for
{!Mempool.add_operation} (see {!Mempool.conflict_handler}).
- For non-manager operations, we select the greater operation
according to {!Operation.compare}.
- A manager operation is replaced only when the new operation's
fee and fee/gas ratio both exceed the old operation's by at least a
factor of [config.replace_by_fee_factor] (see {!better_fees_and_ratio}).
Precondition: both operations must be individually valid (because
of the call to {!Operation.compare}). *)
let conflict_handler config : Mempool.conflict_handler =
fun ~existing_operation ~new_operation ->
let (_ : Operation_hash.t), old_op = existing_operation in
let (_ : Operation_hash.t), new_op = new_operation in
if is_manager_operation old_op && is_manager_operation new_op then
let new_op_is_better =
let open Result_syntax in
let {protocol_data = Operation_data old_protocol_data; _} = old_op in
let {protocol_data = Operation_data new_protocol_data; _} = new_op in
let* old_fee, old_gas_limit =
get_manager_operation_gas_and_fee old_protocol_data.contents
in
let* new_fee, new_gas_limit =
get_manager_operation_gas_and_fee new_protocol_data.contents
in
return
(better_fees_and_ratio
config
old_gas_limit
old_fee
new_gas_limit
new_fee)
in
match new_op_is_better with
| Ok b when b -> `Replace
| Ok _ | Error _ -> `Keep
else if Operation.compare existing_operation new_operation < 0 then `Replace
else `Keep
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Nomadic Development. <contact@tezcore.com> *)
(* Copyright (c) 2021-2022 Nomadic Labs, <contact@nomadic-labs.com> *)
(* Copyright (c) 2022 TriliTech <contact@trili.tech> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
sub_dirs.mli |
open Import
module Status : sig
type t =
| Data_only
| Normal
| Vendored
val to_dyn : t -> Dyn.t
module Or_ignored : sig
type nonrec t =
| Ignored
| Status of t
end
module Map : sig
type status
type 'a t =
{ data_only : 'a
; vendored : 'a
; normal : 'a
}
val merge : 'a t -> 'b t -> f:('a -> 'b -> 'c) -> 'c t
val find : 'a t -> status -> 'a
val to_dyn : ('a -> Dyn.t) -> 'a t -> Dyn.t
end
with type status := t
module Set : sig
type t = bool Map.t
val all : t
val normal_only : t
end
end
type subdir_stanzas
val or_default : subdir_stanzas -> Predicate_lang.Glob.t Status.Map.t
val default : Predicate_lang.Glob.t Status.Map.t
type status_map
val eval : Predicate_lang.Glob.t Status.Map.t -> dirs:string list -> status_map
val status : status_map -> dir:string -> Status.Or_ignored.t
module Dir_map : sig
type t
type per_dir =
{ sexps : Dune_lang.Ast.t list
; subdir_status : subdir_stanzas
}
val descend : t -> string -> t option
val sub_dirs : t -> string list
val merge : t -> t -> t
val root : t -> per_dir
end
type decoder =
{ decode : 'a. Dune_lang.Ast.t list -> 'a Dune_lang.Decoder.t -> 'a }
val decode :
file:Path.Source.t -> decoder -> Dune_lang.Ast.t list -> Dir_map.t Memo.t
| |
voting_period_repr.mli | (** A voting period can be of 4 kinds and is uniquely identified as a counter
since the root. *)
type t
type voting_period = t
val encoding: voting_period Data_encoding.t
val rpc_arg: voting_period RPC_arg.arg
val pp: Format.formatter -> voting_period -> unit
include Compare.S with type t := voting_period
val to_int32: voting_period -> int32
val of_int32_exn: int32 -> voting_period
val root: voting_period
val succ: voting_period -> voting_period
type kind =
| Proposal (** protocols can be proposed *)
| Testing_vote (** a proposal can be voted *)
| Testing (** winning proposal is forked on a testnet *)
| Promotion_vote (** activation can be voted *)
val kind_encoding: kind 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. *)
(* *)
(*****************************************************************************)
|
synth.mli |
open Mm_audio
(** Operations on synthesizers. *)
(** A synthesizer. *)
class type t =
object
(** Set the global volume of the synth. *)
method set_volume : float -> unit
(** Play a note. *)
method note_on : int -> float -> unit
(** Stop playing a note. *)
method note_off : int -> float -> unit
(** Fill a buffer with synthesized data adding to the original data of the buffer. *)
method fill_add : Audio.buffer -> int -> int -> unit
(** Synthesize into an audio buffer. Notice that the delta times in the track
should be in samples (so they do depend on the samplerate). *)
method play : MIDI.buffer -> int -> Audio.buffer -> int -> int -> unit
(** Same as [play] but keeps data originally present in the buffer. *)
method play_add : MIDI.buffer -> int -> Audio.buffer -> int -> int -> unit
(** Reset the synthesizer (sets all notes off in particular). *)
method reset : unit
end
(** A synthesizer. *)
type synth = t
(** Create a synthesizer from a function which creates a generator at given
frequency and volume. *)
class create : (float -> float -> Audio.Generator.t) -> t
(** Same as [create] with a mono generator. *)
class create_mono : (float -> float -> Audio.Mono.Generator.t) -> t
(** Sine synthesizer. *)
class sine : ?adsr:Audio.Mono.Effect.ADSR.t -> int -> t
(** Square synthesizer. *)
class square : ?adsr:Audio.Mono.Effect.ADSR.t -> int -> t
(** Saw synthesizer. *)
class saw : ?adsr:Audio.Mono.Effect.ADSR.t -> int -> t
(** Synths with only one note at a time. *)
class monophonic : Audio.Generator.t -> t
(** Multichannel synthesizers. *)
module Multitrack : sig
(** A multichannel synthesizer. *)
class type t =
object
(** Synthesize into an audio buffer. *)
method play :
MIDI.Multitrack.buffer -> int -> Audio.buffer -> int -> int -> unit
(** Same as [play] but keeps data originally present in the buffer. *)
method play_add :
MIDI.Multitrack.buffer -> int -> Audio.buffer -> int -> int -> unit
end
(** Create a multichannel synthesizer with given number of channels and a
function returning the synthesizer on each channel. *)
class create : int -> (int -> synth) -> t
end
| (*
* Copyright 2011 The Savonet Team
*
* This file is part of ocaml-mm.
*
* ocaml-mm 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 2 of the License, or
* (at your option) any later version.
*
* ocaml-mm 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 Lesser General Public License
* along with ocaml-mm; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* As a special exception to the GNU Library General Public License, you may
* link, statically or dynamically, a "work that uses the Library" with a publicly
* distributed version of the Library to produce an executable file containing
* portions of the Library, and distribute that executable file under terms of
* your choice, without any of the additional requirements listed in clause 6
* of the GNU Library General Public License.
* By "a publicly distributed version of the Library", we mean either the unmodified
* Library as distributed by The Savonet Team, or a modified version of the Library that is
* distributed under the conditions defined in clause 3 of the GNU Library General
* Public License. This exception does not however invalidate any other reasons why
* the executable file might be covered by the GNU Library General Public License.
*
*) |
PPrintMini.ml | (* -------------------------------------------------------------------------- *)
(* A type of integers with infinity. *)
type requirement =
int (* with infinity *)
(* Infinity is encoded as [max_int]. *)
let infinity : requirement =
max_int
(* Addition of integers with infinity. *)
let (++) (x : requirement) (y : requirement) : requirement =
if x = infinity || y = infinity then
infinity
else
x + y
(* Comparison of requirements is just ordinary comparison. *)
(* -------------------------------------------------------------------------- *)
(* The type of documents. See [PPrintEngine] for documentation. *)
type document =
| Empty
| FancyString of string * int * int * int
| Blank of int
| IfFlat of document * document
| HardLine
| Cat of requirement * document * document
| Nest of requirement * int * document
| Group of requirement * document
(* -------------------------------------------------------------------------- *)
(* Retrieving or computing the space requirement of a document. *)
let rec requirement = function
| Empty ->
0
| FancyString (_, _, _, len)
| Blank len ->
len
| IfFlat (doc1, _) ->
requirement doc1
| HardLine ->
infinity
| Cat (req, _, _)
| Nest (req, _, _)
| Group (req, _) ->
req
(* -------------------------------------------------------------------------- *)
(* Document constructors. *)
let empty =
Empty
let fancysubstring s ofs len apparent_length =
if len = 0 then
empty
else
FancyString (s, ofs, len, apparent_length)
let fancystring s apparent_length =
fancysubstring s 0 (String.length s) apparent_length
let utf8_length s =
let rec length_aux s c i =
if i >= String.length s then c else
let n = Char.code (String.unsafe_get s i) in
let k =
if n < 0x80 then 1 else
if n < 0xe0 then 2 else
if n < 0xf0 then 3 else 4
in
length_aux s (c + 1) (i + k)
in
length_aux s 0 0
let utf8string s =
fancystring s (utf8_length s)
let char c =
assert (c <> '\n');
fancystring (String.make 1 c) 1
let space =
char ' '
let hardline =
HardLine
let blank n =
match n with
| 0 ->
empty
| 1 ->
space
| _ ->
Blank n
let ifflat doc1 doc2 =
match doc1 with
| IfFlat (doc1, _)
| doc1 ->
IfFlat (doc1, doc2)
let internal_break i =
ifflat (blank i) hardline
let break0 =
internal_break 0
let break1 =
internal_break 1
let break i =
match i with
| 0 ->
break0
| 1 ->
break1
| _ ->
internal_break i
let (^^) x y =
match x, y with
| Empty, _ ->
y
| _, Empty ->
x
| _, _ ->
Cat (requirement x ++ requirement y, x, y)
let nest i x =
assert (i >= 0);
Nest (requirement x, i, x)
let group x =
let req = requirement x in
if req = infinity then
x
else
Group (req, x)
(* -------------------------------------------------------------------------- *)
(* Printing blank space (indentation characters). *)
let blank_length =
80
let blank_buffer =
String.make blank_length ' '
let rec blanks output n =
if n <= 0 then
()
else if n <= blank_length then
Buffer.add_substring output blank_buffer 0 n
else begin
Buffer.add_substring output blank_buffer 0 blank_length;
blanks output (n - blank_length)
end
(* -------------------------------------------------------------------------- *)
(* The rendering engine maintains the following internal state. *)
(* For simplicity, the ribbon width is considered equal to the line
width; in other words, there is no ribbon width constraint. *)
(* For simplicity, the output channel is required to be an OCaml buffer.
It is stored within the [state] record. *)
type state =
{
(* The line width. *)
width: int;
(* The current column. *)
mutable column: int;
(* The output buffer. *)
output: Buffer.t;
}
(* -------------------------------------------------------------------------- *)
(* For simplicity, the rendering engine is *not* in tail-recursive style. *)
let rec pretty state (indent : int) (flatten : bool) doc =
match doc with
| Empty ->
()
| FancyString (s, ofs, len, apparent_length) ->
Buffer.add_substring state.output s ofs len;
state.column <- state.column + apparent_length
| Blank n ->
blanks state.output n;
state.column <- state.column + n
| HardLine ->
assert (not flatten);
Buffer.add_char state.output '\n';
blanks state.output indent;
state.column <- indent
| IfFlat (doc1, doc2) ->
pretty state indent flatten (if flatten then doc1 else doc2)
| Cat (_, doc1, doc2) ->
pretty state indent flatten doc1;
pretty state indent flatten doc2
| Nest (_, j, doc) ->
pretty state (indent + j) flatten doc
| Group (req, doc) ->
let flatten = flatten || state.column ++ req <= state.width in
pretty state indent flatten doc
(* -------------------------------------------------------------------------- *)
(* The engine's entry point. *)
let pretty width doc =
let output = Buffer.create 512 in
let state = { width; column = 0; output } in
pretty state 0 false doc;
Buffer.contents output
| (******************************************************************************)
(* *)
(* PPrint *)
(* *)
(* François Pottier, Inria Paris *)
(* Nicolas Pouillard *)
(* *)
(* Copyright 2007-2022 Inria. All rights reserved. This file is *)
(* distributed under the terms of the GNU Library General Public *)
(* License, with an exception, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
|
alpha_services.ml | open Alpha_context
let custom_root = RPC_path.open_root
module Seed = struct
module S = struct
open Data_encoding
let seed =
RPC_service.post_service
~description:"Seed of the cycle to which the block belongs."
~query:RPC_query.empty
~input:empty
~output:Seed.seed_encoding
RPC_path.(custom_root / "context" / "seed")
end
let () =
let open Services_registration in
register0 S.seed (fun ctxt () () ->
let l = Level.current ctxt in
Seed.for_cycle ctxt l.cycle)
let get ctxt block = RPC_context.make_call0 S.seed ctxt block () ()
end
module Nonce = struct
type info = Revealed of Nonce.t | Missing of Nonce_hash.t | Forgotten
let info_encoding =
let open Data_encoding in
union
[ case
(Tag 0)
~title:"Revealed"
(obj1 (req "nonce" Nonce.encoding))
(function Revealed nonce -> Some nonce | _ -> None)
(fun nonce -> Revealed nonce);
case
(Tag 1)
~title:"Missing"
(obj1 (req "hash" Nonce_hash.encoding))
(function Missing nonce -> Some nonce | _ -> None)
(fun nonce -> Missing nonce);
case
(Tag 2)
~title:"Forgotten"
empty
(function Forgotten -> Some () | _ -> None)
(fun () -> Forgotten) ]
module S = struct
let get =
RPC_service.get_service
~description:"Info about the nonce of a previous block."
~query:RPC_query.empty
~output:info_encoding
RPC_path.(custom_root / "context" / "nonces" /: Raw_level.rpc_arg)
end
let register () =
let open Services_registration in
register1 S.get (fun ctxt raw_level () () ->
let level = Level.from_raw ctxt raw_level in
Nonce.get ctxt level
>|= function
| Ok (Revealed nonce) ->
ok (Revealed nonce)
| Ok (Unrevealed {nonce_hash; _}) ->
ok (Missing nonce_hash)
| Error _ ->
ok Forgotten)
let get ctxt block level =
RPC_context.make_call1 S.get ctxt block level () ()
end
module Contract = Contract_services
module Constants = Constants_services
module Delegate = Delegate_services
module Voting = Voting_services
module Sapling = Sapling_services
module Liquidity_baking = struct
module S = struct
let get_cpmm_address =
RPC_service.get_service
~description:"Liquidity baking CPMM address"
~query:RPC_query.empty
~output:Alpha_context.Contract.encoding
RPC_path.(
custom_root / "context" / "liquidity_baking" / "cpmm_address")
end
let register () =
let open Services_registration in
register0 S.get_cpmm_address (fun ctxt () () ->
Alpha_context.Liquidity_baking.get_cpmm_address ctxt)
let get_cpmm_address ctxt block =
RPC_context.make_call0 S.get_cpmm_address ctxt block () ()
end
let register () =
Contract.register () ;
Constants.register () ;
Delegate.register () ;
Nonce.register () ;
Voting.register () ;
Sapling.register () ;
Liquidity_baking.register ()
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)
(* Copyright (c) 2019-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. *)
(* *)
(*****************************************************************************)
|
GHParserException.h |
#import <Foundation/Foundation.h>
@class GHLocation;
@class GHToken;
@interface GHParserException : NSException
@property (nonatomic, readonly) GHLocation * location;
@end
@interface GHAstBuilderException : GHParserException
- (id)initWithMessage:(NSString *)theMessage;
- (id)initWithMessage:(NSString *)theMessage location:(GHLocation *)theLocation;
@end
@interface GHNoSuchLanguageException : GHParserException
- (id)initWithLanguage:(NSString *)theLanguage location:(GHLocation *)theLocation;
@end
@interface GHTokenParserException : GHParserException
- (id)initWithMessage:(NSString *)theMessage token:(GHToken *)theToken;
@end
@interface GHUnexpectedTokenException : GHTokenParserException
@property (nonatomic, readonly) NSString * stateComment;
@property (nonatomic, readonly) GHToken * receivedToken;
@property (nonatomic, readonly) NSArray<NSString *> * expectedTokenTypes;
- (id)initWithToken:(GHToken *)theReceivedToken expectedTokenTypes:(NSArray<NSString *> *)theExpectedTokenTypes stateComment:(NSString *)theStateComment;
@end
@interface GHUnexpectedEOFException : GHTokenParserException
@property (nonatomic, readonly) NSString * stateComment;
@property (nonatomic, readonly) NSArray<NSString *> * expectedTokenTypes;
- (id)initWithToken:(GHToken *)theReceivedToken expectedTokenTypes:(NSArray<NSString *> *)theExpectedTokenTypes stateComment:(NSString *)theStateComment;
@end
@interface GHCompositeParserException : GHParserException
@property (nonatomic, readonly) NSArray<GHParserException *> * errors;
- (id)initWithErrors:(NSArray<GHParserException *> *)theErrors;
@end | |
mmap.mli | (** Memory map of a running process *)
exception Error of string
type t =
{ vma_offset_text : int64
; vma_offset_semaphores : int64
}
(** [read pid filename] reads memory map of a running process from /proc/pid/maps and
extracts information relavant to the object file [filename]. Requires permissions to
read maps, such as calling this function from pid itself or a process attached to pid
using ptrace, and pid should be stopped (or memory map might be modified by the OS
during reading). *)
val read : pid:int -> Elf.t -> t
(** Control debug printing. *)
val verbose : bool ref
| (** Memory map of a running process *)
exception Error of string |
test808ext.ml |
let unused _ _ = failwith "*** Using the unused ***"
module E = struct
type ('a,'b,'c) expr = ..
[@@deriving gt ~options:{show; eval}]
(* TODO: support whildcards here *)
(* class virtual ['ia,'a,'sa,'ib,'b,'sb,'ic,'c,'sc,'inh,'self,'syn] expr_t =
* object end
* let gcata_expr tr inh subj = assert false *)
end
module Lam = struct
type ('name_abs, 'name, 'lam) E.expr += App of 'lam * 'lam | Var of 'name
[@@deriving gt ~options:{show; eval}]
class ['me, 'me2] de_bruijn fuse_var fterm = object
inherit [string, unit, string, int, 'me, 'me2, string list, 'me2] eval_expr_t
unused (fun _ (_: string) -> ()) fuse_var fterm
end
end
module Abs = struct
type ('name_a, 'name, 'lam) E.expr += Abs of 'name_a * 'lam
[@@deriving gt ~options:{show; eval}]
class ['me, 'me2] de_bruijn fuse_var ft = object
inherit [ 'inh, 'name_a, 'name_a2
, 'inh, 'name, 'name2
, 'inh, 'lam, 'lam2
, 'inh, 'self, ('name_a2, 'name2, 'lam2) E.expr
] expr_t
inherit ['me, 'me2] Lam.de_bruijn fuse_var ft
constraint 'name2 = int
method c_Abs env name term = Abs ((), ft (name :: env) term)
end
end
module Let = struct
type ('name_a, 'name, 'lam) E.expr += Let of 'name_a * 'lam * 'lam
[@@deriving gt ~options:{show; eval}]
class ['me, 'me'] de_bruijn fuse_var ft = object
inherit [ string list, string, unit
, string list, string, int
, string list, 'me, 'me'
, string list, 'me, 'me'] expr_t
inherit ['me, 'me'] Abs.de_bruijn fuse_var ft
method c_Let env (name: string) bnd term =
Let ((), ft env bnd, ft (name :: env) term)
end
end
module LetRec = struct
type ('name_a, 'name, 'lam) E.expr += LetRec of 'name_a * 'lam * 'lam
[@@deriving gt ~options:{show; eval}]
class ['me, 'me'] de_bruijn fuse_var ft = object
inherit [ string list, string, unit
, string list, string, int
, string list, 'me, 'me'
, string list, 'me, 'me'] expr_t
inherit ['me, 'me'] Let.de_bruijn fuse_var ft
method c_LetRec env name bnd term =
let env2 = name::env in
LetRec ((), ft env2 bnd, ft env2 term)
end
end
(* *)
let fix f inh t =
let knot = ref (fun _ -> assert false) in
let recurse inh t = f !knot inh t in
knot := recurse;
recurse inh t
let ith m n = fix (fun me i -> function
| [] -> raise Not_found
| x :: tl when x = n -> i
| _ :: tl -> me (i+1) tl
) 0 m
type ('var_abs, 'n, 'b) t = ('var_abs, 'n, ('var_abs, 'n, 'b) t) E.expr
let show_t fname fterm lam =
let rec helper lam =
Let.gcata_expr (new Let.show_expr_t helper fname fname helper) () lam
in
helper lam
type named = (string, string, string) t
type nameless = (unit, int, unit) t
let show_string = Printf.sprintf "%S"
let show_int = Printf.sprintf "%d"
let show_unit _ = Printf.sprintf "()"
let show_named (t: named) =
GT.fix0 (fun fself ->
LetRec.gcata_expr (new LetRec.show_expr_t fself show_string show_string fself) ()
) t
let show_nameless (t: nameless) =
GT.fix0 (fun fself ->
LetRec.gcata_expr (new LetRec.show_expr_t fself show_unit show_int fself) ()
) t
(* to de Bruijn *)
let convert (lam: named) : nameless =
let rec helper env lam =
LetRec.gcata_expr (new LetRec.de_bruijn ith helper) env lam
in
helper [] lam
let () =
let l : named =
let open Lam in let open Abs in
App (Abs ("x", Var "x"), Abs ("y", Var "y"))
in
let l2 : named =
let open Lam in let open Abs in let open Let in
Let ("z", Abs ("x", Var "x"), Abs ("x", Abs ("y", App (Var "x", Var "z"))))
in
let l3 =
let open Lam in let open Abs in let open Let in let open LetRec in
LetRec ("z", App (Abs ("x", Var "x"), Var "z"), Abs ("x", Abs ("y", App (Var "x", Var "z"))))
in
(* Original: App (Abs ("x", Var ("x")), Abs ("y", Var ("y"))) *)
Printf.printf "Original: %s\n" (show_named l);
(* Converted: App (Abs ((), Var (0)), Abs ((), Var (0))) *)
Printf.printf "Converted: %s\n" (show_nameless @@ convert l);
(* Converted: Let ((), Abs ((), Var (0)), Abs ((), Abs ((), App (Var (1), Var (2))))) *)
Printf.printf "Converted: %s\n" (show_nameless @@ convert l2);
(* Converted: Let ((), App (Abs ((), Var (0)), Var (0)), Abs ((), Abs ((), App (Var (1), Var (2))))) *)
Printf.printf "Converted: %s\n" (show_nameless @@ convert l3);
()
| |
b0_main.ml |
open Cmdliner
let doc = "Software construction and deployment kit"
let sdocs = Manpage.s_common_options
let exits = B0_driver.Exit.infos
let man = [
`S Manpage.s_synopsis;
`P "$(mname) $(i,COMMAND) …"; `Noblank;
`P "$(mname) \
[$(b,-a) $(i,UNIT)]
[$(b,-u) $(i,UNIT)]… [$(b,-p) $(i,PACK)]… [$(i,OPTION)]… \
$(b,--) [$(i,ARG)]…";
`S Manpage.s_description;
`P "B0 describes software construction and deployments using modular and \
customizable definitions written in OCaml.";
`Pre "Use $(mname) $(b,unit) to see what can be built."; `Noblank;
`Pre "Use $(mname) $(b,--what) to see what gets built."; `Noblank;
`Pre "Use $(mname) to build."; `Noblank;
`Pre "Use $(mname) $(b,-a) $(i,UNIT) to build $(i,UNIT) and execute its \
outcome action.";
`Pre "Use $(mname) [$(i,COMMAND)]… $(b,--help) for help about any \
command.";
`P "More information is available in the manuals, see $(b,odig doc b0).";
B0_b0.Cli.man_see_manual;
`S Manpage.s_bugs;
`P "Report them, see $(i,https://erratique.ch/software/b0) for contact information."; ]
let cmds =
[ B0_cmd_build.cmd;
B0_cmd_cmdlet.cmd;
B0_cmd_cmd.cmd;
B0_cmd_delete.cmd;
B0_cmd_file.cmd;
B0_cmd_log.cmd;
B0_cmd_pack.cmd;
B0_cmd_root.cmd;
B0_cmd_scope.cmd;
B0_cmd_unit.cmd ]
let b0 =
let info = Cmd.info "b0" ~version:"v0.0.4" ~doc ~sdocs ~exits ~man in
Cmd.group info ~default:B0_cmd_build.term cmds
let main () = Cmd.eval_value b0
let () = B0_driver.set ~driver:B0_b0.driver ~main
(*---------------------------------------------------------------------------
Copyright (c) 2020 The b0 programmers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
| (*---------------------------------------------------------------------------
Copyright (c) 2020 The b0 programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*) |
bonsai_web_ui_partial_render_table_bench.mli |
open! Core
open! Bonsai
open! Bonsai_web
open! Incr_map_collate
open! Bonsai_web_ui_partial_render_table
open! Bonsai_bench
(** An [Action.t] represents the possible actions that can be performed on a partial render
table. *)
module Action : sig
type 'a t =
| Unfocus
| Focus_up
| Focus_down
| Page_up
| Page_down
| Focus of 'a
[@@deriving sexp, equal]
end
(** An [Input.t] packages up all of the inputs to the partial render table and provides
facilities for modifying individual components. *)
module Input : sig
type ('key, 'data, 'cmp) t
(** [create] produces a [t], with defaults for most components of the input. *)
val create
: ?filter:(* default: None *) (key:'key -> data:'data -> bool) option
-> ?order:
(* default: Compare.Unchanged *)
('key, 'data, 'cmp) Incr_map_collate.Compare.t
-> ?rank_range:(* default: Which_range.To 100 *) int Collate.Which_range.t
-> ?key_range:(* default: Which_range.All_rows *) 'key Collate.Which_range.t
-> ?on_change:((* default: Fn.const Effect.Ignore *) 'key option -> unit Effect.t)
-> ('key, 'data, 'cmp) Map.t
-> ('key, 'data, 'cmp) t
(** [apply_filter] produces an interaction to change the current filter. *)
val apply_filter
: ('key, 'data, 'cmp) t
-> (key:'key -> data:'data -> bool)
-> 'action Bonsai_bench.Interaction.t
(** [clear_filter] produces an interaction to remove the current filter. *)
val clear_filter : _ t -> 'action Bonsai_bench.Interaction.t
(** [set_map] produces an interaction to change the map whose data is being rendered in
the table. *)
val set_map
: ('key, 'data, 'cmp) t
-> ('key, 'data, 'cmp) Map.t
-> 'action Bonsai_bench.Interaction.t
(** [set_order] produces an interaction to change the current ordering. *)
val set_order
: ('key, 'data, 'cmp) t
-> ('key, 'data, 'cmp) Incr_map_collate.Compare.t
-> 'action Bonsai_bench.Interaction.t
(** [set_rank_range] produces an interaction to change the currently visible rank range. *)
val set_rank_range
: _ t
-> int Collate.Which_range.t
-> 'action Bonsai_bench.Interaction.t
(** [set_on_change] produces an interaction to change the current [on_change] function. *)
val set_on_change
: ('key, _, _) t
-> ('key option -> unit Effect.t)
-> 'action Bonsai_bench.Interaction.t
(** [scroll] generates an interaction with abs(start-stop) [change_input]s, which set the
[rank_range]'s low end to the values between [start] (inclusive) and [stop]
(exclusive), keeping [window_size] elements in the range. *)
val scroll
: _ t
-> start:int
-> stop:int
-> window_size:int
-> 'action Bonsai_bench.Interaction.t
end
(** [create_test] produces a [Bonsai_bench.Test.t] which will benchmark the partial render
table, with the initial input set to [initial_vars], by running the interaction
produced by calling [interaction] on [initial_vars]. *)
val create_test
: ?preload_rows:int
-> ('key, 'cmp) Bonsai.comparator
-> initial_vars:('key, 'data, 'cmp) Input.t
-> columns:('key, 'data) Expert.Columns.t
-> interaction:(('key, 'data, 'cmp) Input.t -> 'key Action.t Bonsai_bench.Interaction.t)
-> test_name:string
-> Bonsai_bench.Test.t
| |
fprint_pretty.c |
#include <stdlib.h>
#include <string.h>
#include "fmpq_mpoly.h"
int
fmpq_mpoly_fprint_pretty(FILE * file, const fmpq_mpoly_t A,
const char ** x_in, const fmpq_mpoly_ctx_t qctx)
{
int r = 0;
fmpq_t c;
slong i, j, N;
fmpz * exponents;
const fmpz_mpoly_struct * poly = A->zpoly;
const mpoly_ctx_struct * mctx = qctx->zctx->minfo;
char ** x = (char **) x_in;
TMP_INIT;
TMP_START;
fmpq_init(c);
N = mpoly_words_per_exp(poly->bits, mctx);
exponents = (fmpz *) TMP_ALLOC(mctx->nvars*sizeof(fmpz));
for (i = 0; i < mctx->nvars; i++)
fmpz_init(exponents + i);
r = 0;
if (poly->length == 0)
{
r = fputc('0', file);
goto cleanup;
}
if (x == NULL)
{
x = (char **) TMP_ALLOC(mctx->nvars*sizeof(char *));
for (i = 0; i < mctx->nvars; i++)
{
x[i] = (char *) TMP_ALLOC(22*sizeof(char));
flint_sprintf(x[i], "x%wd", i + 1);
}
}
for (i = 0; i < poly->length; i++)
{
int first = 1;
fmpq_mul_fmpz(c, A->content, poly->coeffs + i);
r = flint_fprintf(file, (fmpq_sgn(c) >= 0) ? (i > 0 ? " + " : "")
: (i > 0 ? " - " : "-") );
fmpq_abs(c, c);
if (!fmpq_is_one(c))
{
first = 0;
fmpq_fprint(file, c);
}
mpoly_get_monomial_ffmpz(exponents, poly->exps + N*i, poly->bits, mctx);
for (j = 0; j < mctx->nvars; j++)
{
int cmp = fmpz_cmp_ui(exponents + j, UWORD(1));
if (cmp < 0)
continue;
if (!first)
{
r = fputc('*', file);
}
r = flint_fprintf(file, "%s", x[j]);
if (cmp > 0)
{
r = fputc('^', file);
r = fmpz_fprint(file, exponents + j);
}
first = 0;
}
if (first)
{
r = flint_fprintf(file, "1");
}
}
cleanup:
for (i = 0; i < mctx->nvars; i++)
fmpz_clear(exponents + i);
fmpq_clear(c);
TMP_END;
return r;
}
| /*
Copyright (C) 2018 Daniel Schultz
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/ |
dune |
(rule
(targets g.ml)
(deps stubgen/mmdb_ml_types_stubgen.exe)
(action
(with-stdout-to
%{targets}
(run %{deps}))))
(library
(name mmdb_types)
(public_name mmdb.types)
(synopsis
"Ctypes bindings that describe the libmaxminddb constants and types")
(flags :standard -w -9-27 -cclib -lmaxminddb)
(libraries mmdb_types_bindings))
| |
t-bell_number_vec.c |
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
#include "flint.h"
#include "arith.h"
#include "fmpz_vec.h"
#include "ulong_extras.h"
int main(void)
{
fmpz * b1;
fmpz * b2;
slong n;
const slong maxn = 1000;
FLINT_TEST_INIT(state);
flint_printf("bell_number_vec....");
fflush(stdout);
b1 = _fmpz_vec_init(maxn);
b2 = _fmpz_vec_init(maxn);
for (n = 0; n < maxn; n += (n < 50) ? + 1 : n/4)
{
arith_bell_number_vec_recursive(b1, n);
arith_bell_number_vec_multi_mod(b2, n);
if (!_fmpz_vec_equal(b1, b2, n))
{
flint_printf("FAIL:\n");
flint_printf("n = %wd\n", n);
fflush(stdout);
flint_abort();
}
}
_fmpz_vec_clear(b1, maxn);
_fmpz_vec_clear(b2, maxn);
FLINT_TEST_CLEANUP(state);
flint_printf("PASS\n");
return 0;
}
| /*
Copyright (C) 2011 Fredrik Johansson
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/ |
frx_misc.mli | val autodef : (unit -> 'a) -> (unit -> 'a)
(* [autodef make] is a pleasant wrapper around 'a option ref *)
val create_photo : Camltk.options list -> Camltk.imagePhoto
(* [create_photo options] allows Data in options (by saving to tmp file) *)
| (***********************************************************************)
(* *)
(* MLTk, Tcl/Tk interface of OCaml *)
(* *)
(* Francois Rouaix, Francois Pessaux, Jun Furuse and Pierre Weis *)
(* projet Cristal, INRIA Rocquencourt *)
(* Jacques Garrigue, Kyoto University RIMS *)
(* *)
(* Copyright 2002 Institut National de Recherche en Informatique et *)
(* en Automatique and Kyoto University. All rights reserved. *)
(* This file is distributed under the terms of the GNU Library *)
(* General Public License, with the special exception on linking *)
(* described in file LICENSE found in the OCaml source tree. *)
(* *)
(***********************************************************************)
open Camltk |
generative.ml |
module Generative () = struct end
module M = Generative ()
module M = String_id (M) ()
| |
sapling_validator.ml | (* Check that each nullifier is not already present in the state and add it.
Important to avoid spending the same input twice in a transaction. *)
let rec check_and_update_nullifiers ctxt state inputs =
match inputs with
| [] -> return (ctxt, Some state)
| input :: inputs -> (
Sapling_storage.nullifiers_mem ctxt state Sapling.UTXO.(input.nf)
>>=? function
| (ctxt, true) -> return (ctxt, None)
| (ctxt, false) ->
let state =
Sapling_storage.nullifiers_add state Sapling.UTXO.(input.nf)
in
check_and_update_nullifiers ctxt state inputs)
let verify_update :
Raw_context.t ->
Sapling_storage.state ->
Sapling_repr.transaction ->
string ->
(Raw_context.t * (Int64.t * Sapling_storage.state) option) tzresult Lwt.t =
fun ctxt state transaction key ->
(* Check the transaction *)
(* To avoid overflowing the balance, the number of inputs and outputs must be
bounded.
Ciphertexts' memo_size must match the state's memo_size.
These constraints are already enforced at the encoding level. *)
assert (Compare.Int.(List.compare_length_with transaction.inputs 5208 <= 0)) ;
assert (Compare.Int.(List.compare_length_with transaction.outputs 2019 <= 0)) ;
let pass =
List.for_all
(fun output ->
Compare.Int.(
Sapling.Ciphertext.get_memo_size Sapling.UTXO.(output.ciphertext)
= state.memo_size))
transaction.outputs
in
if not pass then return (ctxt, None)
else
(* Check the root is a recent state *)
Sapling_storage.root_mem ctxt state transaction.root >>=? fun pass ->
if not pass then return (ctxt, None)
else
check_and_update_nullifiers ctxt state transaction.inputs >|=? function
| (ctxt, None) -> (ctxt, None)
| (ctxt, Some state) ->
Sapling.Verification.with_verification_ctx (fun vctx ->
let pass =
(* Check all the output ZK proofs *)
List.for_all
(fun output -> Sapling.Verification.check_output vctx output)
transaction.outputs
in
if not pass then (ctxt, None)
else
let pass =
(* Check all the input Zk proofs and signatures *)
List.for_all
(fun input ->
Sapling.Verification.check_spend
vctx
input
transaction.root
key)
transaction.inputs
in
if not pass then (ctxt, None)
else
let pass =
(* Check the signature and balance of the whole transaction *)
Sapling.Verification.final_check vctx transaction key
in
if not pass then (ctxt, None)
else
(* update tree *)
let list_to_add =
List.map
(fun output ->
Sapling.UTXO.(output.cm, output.ciphertext))
transaction.outputs
in
let state = Sapling_storage.add state list_to_add in
(ctxt, Some (transaction.balance, state)))
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2019-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. *)
(* *)
(*****************************************************************************)
|
tyxml_ppx_register.ml |
open Ppxlib
let str_item_expansion name lang =
Extension.declare_with_path_arg
name
Extension.Context.structure_item
Ast_pattern.(pstr ((pstr_value __ __) ^:: nil))
(Tyxml_ppx.expand_str_item ~lang)
let expr_expansion name lang =
Extension.declare_with_path_arg
name
Extension.Context.expression
Ast_pattern.(pstr ((pstr_eval __ __) ^:: nil))
(Tyxml_ppx.expand_expr ~lang)
let () =
let extensions = [
expr_expansion "tyxml.html" Html;
expr_expansion "tyxml.svg" Svg;
str_item_expansion "tyxml.html" Html;
str_item_expansion "tyxml.svg" Svg;
]
in
Ppxlib.Driver.register_transformation ~extensions "tyxml"
| |
pretty.ml | #load "pa_macro.cmo";
open Versdep;
exception GiveUp;
value line_length = ref 78;
value horiz_ctx = ref False;
value utf8_string_length s =
loop 0 0 where rec loop i len =
if i = String.length s then len
else
let c = Char.code s.[i] in
if c < 0b1000_0000 || c >= 0b1100_0000 then loop (i + 1) (len + 1)
else loop (i + 1) len
;
value after_print s =
if horiz_ctx.val then
if string_contains s '\n' || utf8_string_length s > line_length.val then
raise GiveUp
else s
else s
;
value sprintf fmt = Versdep.printf_ksprintf after_print fmt;
value horiz_vertic horiz vertic =
try Ploc.call_with horiz_ctx True horiz () with
[ GiveUp -> if horiz_ctx.val then raise GiveUp else vertic () ]
;
value vertic v =
horiz_vertic (fun () -> raise GiveUp) v
;
value horizontally () = horiz_ctx.val;
| (* camlp5r *)
(* pretty.ml,v *)
(* Copyright (c) INRIA 2007-2017 *)
|
test_ticket_balance.ml | (** Testing
-------
Component: Protocol (Ticket_balance_key)
Invocation: dune exec \
src/proto_alpha/lib_protocol/test/integration/michelson/main.exe \
-- test "^ticket balance"
Subject: Ticket balance key hashing
*)
open Protocol
open Alpha_context
open Lwt_result_syntax
let wrap m = m >|= Environment.wrap_tzresult
type init_env = {
block : Block.t;
baker : Tezos_crypto.Signature.V0.public_key_hash;
contract : Contract.t;
}
let init_env () =
let* block, baker, contract, _src2 = Contract_helpers.init () in
return {block; baker; contract}
let transaction block ~baker ~sender ~entrypoint ~recipient ~parameters =
let parameters = Script.lazy_expr @@ Expr.from_string parameters in
let* operation =
Op.transaction
(B block)
~gas_limit:Max
~entrypoint
~parameters
~fee:Tez.one
sender
recipient
(Tez.of_mutez_exn 0L)
in
let* incr =
Incremental.begin_construction ~policy:Block.(By_account baker) block
in
let* incr = Incremental.add_operation incr operation in
Incremental.finalize_block incr
let originate = Contract_helpers.originate_contract_from_string
let get_balance ctxt ~token ~owner =
let* key_hash, ctxt =
wrap @@ Ticket_balance_key.of_ex_token ctxt ~owner token
in
wrap (Ticket_balance.get_balance ctxt key_hash)
let get_used_ticket_storage block =
let* incr = Incremental.begin_construction block in
wrap
@@ Ticket_balance.Internal_for_tests.used_storage_space
(Incremental.alpha_ctxt incr)
let get_paid_ticket_storage block =
let* incr = Incremental.begin_construction block in
wrap
@@ Ticket_balance.Internal_for_tests.paid_storage_space
(Incremental.alpha_ctxt incr)
let get_used_contract_storage block contract =
let* incr = Incremental.begin_construction block in
let alpha_ctxt = Incremental.alpha_ctxt incr in
wrap @@ Alpha_context.Contract.used_storage_space alpha_ctxt contract
let get_paid_contract_storage block contract =
let* incr = Incremental.begin_construction block in
let alpha_ctxt = Incremental.alpha_ctxt incr in
wrap
@@ Alpha_context.Contract.Internal_for_tests.paid_storage_space
alpha_ctxt
contract
let assert_paid_contract_storage ~loc block contract expected =
let* storage = get_paid_contract_storage block contract in
Assert.equal
~loc
Z.equal
"Paid contract storage "
Z.pp_print
(Z.of_int expected)
storage
let assert_used_contract_storage ~loc block contract expected =
let* storage = get_used_contract_storage block contract in
Assert.equal
~loc
Z.equal
"Used contract storage "
Z.pp_print
(Z.of_int expected)
storage
let assert_paid_ticket_storage ~loc block expected =
let* storage = get_paid_ticket_storage block in
Assert.equal
~loc
Z.equal
"Paid ticket storage "
Z.pp_print
(Z.of_int expected)
storage
let assert_used_ticket_storage ~loc block expected =
let* storage = get_used_ticket_storage block in
Assert.equal
~loc
Z.equal
"Used ticket storage "
Z.pp_print
(Z.of_int expected)
storage
let assert_token_balance ~loc block token owner expected =
let* incr = Incremental.begin_construction block in
let ctxt = Incremental.alpha_ctxt incr in
let* balance, _ =
get_balance ctxt ~token ~owner:(Destination.Contract owner)
in
match (balance, expected) with
| Some b, Some e -> Assert.equal_int ~loc (Z.to_int b) e
| Some b, None ->
failwith "%s: Expected no balance but got some %d" loc (Z.to_int b)
| None, Some b -> failwith "%s: Expected balance %d but got none" loc b
| None, None -> return ()
let string_token ~ticketer content =
let contents =
WithExceptions.Result.get_ok ~loc:__LOC__ @@ Script_string.of_string content
in
Ticket_token.Ex_token
{ticketer; contents_type = Script_typed_ir.string_t; contents}
let unit_ticket ~ticketer =
Ticket_token.Ex_token
{ticketer; contents_type = Script_typed_ir.unit_t; contents = ()}
let new_contracts ~before ~after =
let all_contracts current_block =
let* ctxt =
Incremental.begin_construction current_block >|=? Incremental.alpha_ctxt
in
Lwt.map Result.ok (Contract.list ctxt)
in
let* cs1 = all_contracts before in
let* cs2 = all_contracts after in
let not_in_cs1 =
let module S = Set.Make (String) in
let set = S.of_list @@ List.map Contract.to_b58check cs1 in
fun c -> not @@ S.mem (Contract.to_b58check c) set
in
return (List.filter not_in_cs1 cs2)
let get_new_contract before f =
let* after = f before in
let* contracts = new_contracts ~before ~after in
match contracts with
| c :: _ -> return (c, after)
| _ -> failwith "Expected one new contracts"
(** Test adding a ticket to a strict storage. *)
let test_add_strict () =
let* {block; baker; contract = source_contract} = init_env () in
(* Originate *)
let* contract, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter unit;
storage (list (ticket string));
code
{ CDR;
PUSH nat 1;
PUSH string "Red";
TICKET;
ASSERT_SOME;
CONS;
NIL operation ;
PAIR } }
|}
~storage:"{}"
block
in
let token_red = string_token ~ticketer:contract "Red" in
(* Before calling the contract the balance should be empty. *)
let* () = assert_token_balance ~loc:__LOC__ block token_red contract None in
(* Run the script *)
let* block =
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:contract
~parameters:"Unit"
in
(* After calling the contract, one ticket is added and balance is one. *)
let* () =
assert_token_balance ~loc:__LOC__ block token_red contract (Some 1)
in
(* Calling the contract again should increase the balance once more. *)
let* block =
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:contract
~parameters:"Unit"
in
assert_token_balance ~loc:__LOC__ block token_red contract (Some 2)
(** Test adding and removing tickets from a list in the storage. *)
let test_add_remove () =
let* {block; baker; contract = source_contract} = init_env () in
(* Originate *)
let* contract, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter (or (unit %add) (unit %remove));
storage (list (ticket string)) ;
code { UNPAIR ;
IF_LEFT
{ DROP ;
PUSH nat 1 ;
PUSH string "Red" ;
TICKET ;
ASSERT_SOME ;
CONS ;
NIL operation ;
PAIR }
{ DROP 2 ; NIL (ticket string) ; NIL operation ; PAIR } } }
|}
~storage:"{}"
block
in
let add_one block =
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:contract
~parameters:"Left Unit"
in
let clear block =
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:contract
~parameters:"Right Unit"
in
let token_red = string_token ~ticketer:contract "Red" in
(* Before calling the contract the balance should be empty *)
let* () = assert_token_balance ~loc:__LOC__ block token_red contract None in
(* Call the contract twice *)
let* block = add_one block in
let* block = add_one block in
let* () =
assert_token_balance ~loc:__LOC__ block token_red contract (Some 2)
in
(* Remove tickets from the contract *)
let* block = clear block in
assert_token_balance ~loc:__LOC__ block token_red contract None
(** Test adding multiple tickets to a big-map. *)
let test_add_to_big_map () =
let* {block; baker; contract = source_contract} = init_env () in
let* contract, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter int ;
storage (big_map int (ticket string)) ;
code { LEFT (big_map int (ticket string)) ;
LOOP_LEFT
{ UNPAIR ;
PUSH int 0 ;
SWAP ;
DUP ;
DUG 2 ;
COMPARE ;
LE ;
IF { DROP ; RIGHT (pair int (big_map int (ticket string))) }
{ SWAP ;
PUSH nat 1 ;
PUSH string "Red" ;
TICKET ;
ASSERT_SOME ;
SOME ;
DUP 3 ;
GET_AND_UPDATE ;
DROP ;
PUSH int 1 ;
DIG 2 ;
SUB ;
PAIR ;
LEFT (big_map int (ticket string)) } } ;
NIL operation ;
PAIR } }
|}
~storage:"{}"
block
in
let* block =
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:contract
~parameters:"100"
in
let token_red = string_token ~ticketer:contract "Red" in
assert_token_balance ~loc:__LOC__ block token_red contract (Some 100)
(** Test adding, swapping and clearing big-maps from storage.
The script contains in its storage two big-maps:
pair
(big_map %map1 int (ticket string))
(big_map %map2 int (ticket string)))
And takes three actions:
1) Add one ticket to map1
2) Swap map1 and map2
3) Clear map1
*)
let test_swap_big_map () =
let* {block; baker; contract = source_contract} = init_env () in
let* contract, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter (or (or (int %add) (unit %clear)) (unit %swap)) ;
storage (pair (big_map %map1 int (ticket string)) (big_map %map2 int (ticket string))) ;
code { UNPAIR ;
NIL operation ;
SWAP ;
IF_LEFT
{ IF_LEFT
{ DIG 2 ;
UNPAIR ;
PUSH nat 1 ;
PUSH string "Red" ;
TICKET ;
ASSERT_SOME ;
SOME ;
DIG 3 ;
GET_AND_UPDATE ;
DROP ;
PAIR ;
SWAP ;
PAIR }
{ DROP ; SWAP ; CDR ; EMPTY_BIG_MAP int (ticket string) ;
PAIR ; SWAP ; PAIR } }
{ DROP ; SWAP ; UNPAIR ; SWAP ; PAIR ; SWAP ; PAIR } } }
|}
~storage:"Pair {} {}"
block
in
let add_to_index block ix =
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:contract
~parameters:(Printf.sprintf "Left (Left %d)" ix)
in
let swap_big_maps block =
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:contract
~parameters:"Right Unit"
in
let clear_left_big_map block =
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:contract
~parameters:"Left (Right Unit)"
in
(* Add three tickets to [map1] *)
let* block = add_to_index block 1 in
let* block = add_to_index block 2 in
let* block = add_to_index block 3 in
let token_red = string_token ~ticketer:contract "Red" in
let* () =
assert_token_balance ~loc:__LOC__ block token_red contract (Some 3)
in
(* Swap [map1] and [map2]. This should not impact the ticket balance. *)
let* block = swap_big_maps block in
let* () =
assert_token_balance ~loc:__LOC__ block token_red contract (Some 3)
in
(* Remove all tickets from [map1] (which is empty). *)
let* block = clear_left_big_map block in
let* () =
assert_token_balance ~loc:__LOC__ block token_red contract (Some 3)
in
(* Swap [map1] and [map2]. Now, [map1] contains three tickets. *)
let* block = swap_big_maps block in
(* Clear all tickets from [map1]. *)
let* block = clear_left_big_map block in
assert_token_balance ~loc:__LOC__ block token_red contract None
(* Test sending a ticket to an address *)
let test_send_tickets () =
let* {block; baker; contract = source_contract} = init_env () in
(* A contract that can receive a ticket and store it in a list. *)
let* ticket_receiver, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter (ticket string) ;
storage (list (ticket string)) ;
code { UNPAIR ; CONS ; NIL operation ; PAIR } }
|}
~storage:"{}"
block
in
(* A contract that, given an address to a contract that receives tickets,
mints a ticket and sends it over. *)
let* ticket_sender, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter address ;
storage unit ;
code { CAR ;
CONTRACT (ticket string) ;
IF_NONE
{ PUSH string "Contract of type `ticket(string)' not found" ;
FAILWITH }
{ PUSH mutez 0 ;
PUSH nat 1 ;
PUSH string "Red" ;
TICKET ;
ASSERT_SOME ;
TRANSFER_TOKENS ;
PUSH unit Unit ;
NIL operation ;
DIG 2 ;
CONS ;
PAIR } } }
|}
~storage:"Unit"
block
in
let mint_and_send block =
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:ticket_sender
~parameters:
(Printf.sprintf {|"%s"|} @@ Contract.to_b58check ticket_receiver)
in
(* Call ticket-sender twice in order to transfer tickets to ticket-receiver *)
let* block = mint_and_send block in
let* block = mint_and_send block in
let token_red = string_token ~ticketer:ticket_sender "Red" in
assert_token_balance ~loc:__LOC__ block token_red ticket_receiver (Some 2)
(** Test sending and storing tickets with amount zero. *)
let test_send_and_store_zero_amount_tickets () =
let* {block; baker; contract = source_contract} = init_env () in
(* A contract that, given an address to a contract that receives tickets,
mints a ticket and sends it over. *)
let* ticket_minter, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter (pair address nat) ;
storage unit ;
code { CAR ;
UNPAIR ;
CONTRACT (ticket string) ;
IF_NONE
{ DROP ;
PUSH string "Contract of type `ticket(string)` not found" ;
FAILWITH }
{ PUSH mutez 0 ;
DIG 2 ;
PUSH string "Red" ;
TICKET ;
ASSERT_SOME ;
TRANSFER_TOKENS ;
PUSH unit Unit ;
NIL operation ;
DIG 2 ;
CONS ;
PAIR } } }
|}
~storage:"Unit"
block
in
(* A contract with two entrypoints:
- Store (ticket): stores the received ticket.
- Send (address) sends the last received tickets to the given address.
*)
let ticket_storer_script =
{|
{ parameter (or (address %send) (ticket %store string)) ;
storage (list (ticket string)) ;
code { UNPAIR ;
IF_LEFT
{ CONTRACT (ticket string) ;
IF_NONE
{ DROP ;
PUSH string "Contract of type `ticket(string)` not found" ;
FAILWITH }
{ SWAP ;
IF_CONS
{ DIG 2 ;
PUSH mutez 0 ;
DIG 2 ;
TRANSFER_TOKENS ;
SWAP ;
NIL operation ;
DIG 2 ;
CONS ;
PAIR }
{ DROP ; PUSH string "Empty storage" ; FAILWITH } } }
{ CONS ; NIL operation ; PAIR } } }
|}
in
let* ticket_store_1, _script, block =
originate
~baker
~source_contract
~script:ticket_storer_script
~storage:"{}"
block
in
let* ticket_store_2, _script, block =
originate
~baker
~source_contract
~script:ticket_storer_script
~storage:"{}"
block
in
let mint_and_send_to_storer_1 block amount =
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:ticket_minter
~parameters:
(Printf.sprintf
{|Pair "%s%s" %d|}
(Contract.to_b58check ticket_store_1)
"%store"
amount)
in
let send_from_store_1_to_store_2 block =
transaction
~entrypoint:(Entrypoint.of_string_strict_exn "send")
~baker
~sender:source_contract
block
~recipient:ticket_store_1
~parameters:
(Printf.sprintf
{|"%s%s"|}
(Contract.to_b58check ticket_store_2)
"%store")
in
let token_red = string_token ~ticketer:ticket_minter "Red" in
(* Mint and send a ticket with amount 0 to [ticket_store_1], which fails.
After the transaction:
[ticket_store_1]:
[ ]
*)
let*! result = mint_and_send_to_storer_1 block 0 in
assert (Result.is_error result) ;
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_store_1 None
in
(* Mint and send a ticket with amount 10 to [ticket_store_1]. After
the transaction:
[ticket_store_1]:
[
(TM, "Red", 10)
]
*)
let* block = mint_and_send_to_storer_1 block 10 in
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_store_1 (Some 10)
in
(* Send the top of [ticket_storer_1]'s list to [ticket_store_2]. That is the
ticket (TM, "Red", 10). After the transaction:
ticket_store_1:
[ ]
ticket_store_2:
[
(TM, "Red", 10)
]
*)
let* block = send_from_store_1_to_store_2 block in
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_store_1 None
in
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_store_2 (Some 10)
in
(* Send the top of [ticket_store_1]'s stack to [ticket_store_2].
However, this fails because [ticket_store_1]'s stack is empty.
Now, [ticket_store_2] holds both tickets.
ticket_store_1:
[ ]
[ticket_store_2]:
[
(TM, "Red", 10)
]
*)
let*! result = send_from_store_1_to_store_2 block in
assert (Result.is_error result) ;
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_store_1 None
in
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_store_2 (Some 10)
in
(* Mint and send a ticket with amount 5 to [ticket_store_1]. After the
transaction:
[ticket_store_1]:
[
(TM, "Red", 5)
]
[ticket_store_2]:
[
(TM, "Red", 10)
]
*)
let* block = mint_and_send_to_storer_1 block 5 in
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_store_1 (Some 5)
in
(* Send the top of [ticket_store_1]'s stack to [ticket_store_2]. That is the
ticket (TM, "Red", 5). After the transaction, [ticket_store_2] holds three
tickets:
ticket_store_1:
[ ]
[ticket_store_2]:
[
(TM, "Red", 5)
(TM, "Red", 10)
]
*)
let* block = send_from_store_1_to_store_2 block in
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_store_1 None
in
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_store_2 (Some 15)
in
return_unit
(** Test sending tickets in a big-map. *)
let test_send_tickets_in_big_map () =
let* {block; baker; contract = source_contract} = init_env () in
(* A contract that can receive a big-map with tickets. *)
let* ticket_receiver, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter (big_map int (ticket string)) ;
storage (big_map int (ticket string)) ;
code { CAR ; NIL operation ; PAIR } }
|}
~storage:"{}"
block
in
(* A contract with two actions:
- [mint_and_save(key, content)] for creating and saving a new ticket in
a big-map.
- [send (address)] for transferring the big-map to the given address.
*)
let* ticket_manager, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter (or (pair %mint_and_save int string) (address %send)) ;
storage (big_map int (ticket string)) ;
code { UNPAIR ;
IF_LEFT
{ UNPAIR ;
DIG 2 ;
PUSH nat 1 ;
DIG 3 ;
TICKET ;
ASSERT_SOME ;
SOME ;
DIG 2 ;
GET_AND_UPDATE ;
DROP ;
NIL operation ;
PAIR }
{ CONTRACT (big_map int (ticket string)) ;
IF_NONE
{ PUSH string "Contract of type `ticket(string)` not found" ;
FAILWITH }
{ PUSH mutez 0 ;
DIG 2 ;
TRANSFER_TOKENS ;
EMPTY_BIG_MAP int (ticket string) ;
NIL operation ;
DIG 2 ;
CONS ;
PAIR } } } }
|}
~storage:"{}"
block
in
let mint_and_save key content block =
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:ticket_manager
~parameters:(Printf.sprintf {|Left (Pair %d "%s")|} key content)
in
let send block =
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:ticket_manager
~parameters:
(Printf.sprintf {|Right "%s"|} @@ Contract.to_b58check ticket_receiver)
in
let token_red = string_token ~ticketer:ticket_manager "Red" in
let token_blue = string_token ~ticketer:ticket_manager "Blue" in
let token_yellow = string_token ~ticketer:ticket_manager "Yellow" in
(* Call ticket manager to mint and save three tickets in a big-map. *)
let* block = mint_and_save 1 "Red" block in
let* block = mint_and_save 2 "Blue" block in
let* block = mint_and_save 3 "Yellow" block in
(* Verify that all three tickets are accounted for and belong to
ticket-manager. *)
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_manager (Some 1)
in
let* () =
assert_token_balance ~loc:__LOC__ block token_blue ticket_manager (Some 1)
in
let* () =
assert_token_balance ~loc:__LOC__ block token_yellow ticket_manager (Some 1)
in
(* Send over the big-map with tickets to ticket-receiver. *)
let* block = send block in
(* Verify that all three tickets now belong to the ticket-receiver contract. *)
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_receiver (Some 1)
in
let* () =
assert_token_balance ~loc:__LOC__ block token_blue ticket_receiver (Some 1)
in
let* () =
assert_token_balance
~loc:__LOC__
block
token_yellow
ticket_receiver
(Some 1)
in
(* Finally test that the ticket-manager no longer holds any of the tickets *)
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_manager None
in
let* () =
assert_token_balance ~loc:__LOC__ block token_blue ticket_manager None
in
assert_token_balance ~loc:__LOC__ block token_yellow ticket_manager None
(* Test sending tickets in a big-map. *)
let test_modify_big_map () =
let* {block; baker; contract = source_contract} = init_env () in
(* A contract with two actions:
- [Add ((int, string))] for adding a ticket to the big-map.
- [Remove(int)] for removing an index from the big-map.
*)
let* ticket_manager, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter (or (pair %add int string) (int %remove)) ;
storage (big_map int (ticket string)) ;
code { UNPAIR ;
IF_LEFT
{ UNPAIR ;
DIG 2 ;
PUSH nat 1 ;
DIG 3 ;
TICKET ;
ASSERT_SOME ;
SOME ;
DIG 2 ;
GET_AND_UPDATE ;
DROP ;
NIL operation ;
PAIR }
{ SWAP ;
NONE (ticket string) ;
DIG 2 ;
GET_AND_UPDATE ;
DROP ;
NIL operation ;
PAIR } } }
|}
~storage:"{}"
block
in
let add key content block =
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:ticket_manager
~parameters:(Printf.sprintf {|Left (Pair %d "%s")|} key content)
in
let remove key block =
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:ticket_manager
~parameters:(Printf.sprintf {|Right %d|} key)
in
let token_red = string_token ~ticketer:ticket_manager "Red" in
let token_blue = string_token ~ticketer:ticket_manager "Blue" in
let token_yellow = string_token ~ticketer:ticket_manager "Yellow" in
let token_green = string_token ~ticketer:ticket_manager "Green" in
(* Add a red, blue and a yellow ticket *)
let* block = add 1 "Red" block in
let* block = add 2 "Blue" block in
let* block = add 3 "Yellow" block in
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_manager (Some 1)
in
let* () =
assert_token_balance ~loc:__LOC__ block token_blue ticket_manager (Some 1)
in
let* () =
assert_token_balance ~loc:__LOC__ block token_yellow ticket_manager (Some 1)
in
(* Replace the red ticket at index 1 with a green one. *)
let* block = add 1 "Green" block in
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_manager None
in
let* () =
assert_token_balance ~loc:__LOC__ block token_green ticket_manager (Some 1)
in
(* Remove the blue ticket at index 2. *)
let* block = remove 2 block in
let* () =
assert_token_balance ~loc:__LOC__ block token_blue ticket_manager None
in
(* Add one more green ticket at index 4 and verify that the total count is 2. *)
let* block = add 4 "Green" block in
assert_token_balance ~loc:__LOC__ block token_green ticket_manager (Some 2)
(* Test sending tickets in a big-map to a receiver that drops it. *)
let test_send_tickets_in_big_map_and_drop () =
let* {block; baker; contract = source_contract} = init_env () in
(* A contract that can receive a big-map with tickets but drops it. *)
let* ticket_receiver, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter (big_map int (ticket string)) ;
storage unit;
code { DROP; PUSH unit Unit; NIL operation ; PAIR } }
|}
~storage:"Unit"
block
in
(* A contract that, given an address, creates a ticket and sends it to the
corresponding contract in a big-map. *)
let* ticket_sender, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter address ;
storage unit ;
code { CAR ;
EMPTY_BIG_MAP int (ticket string) ;
PUSH nat 1 ;
PUSH string "Red" ;
TICKET ;
ASSERT_SOME ;
SOME ;
PUSH int 1 ;
GET_AND_UPDATE ;
DROP ;
SWAP ;
CONTRACT (big_map int (ticket string)) ;
IF_NONE
{ DROP ;
PUSH string "Contract of type `ticket(string)` not found" ;
FAILWITH }
{ PUSH mutez 0 ;
DIG 2 ;
TRANSFER_TOKENS ;
PUSH unit Unit ;
NIL operation ;
DIG 2 ;
CONS ;
PAIR } } }
|}
~storage:"Unit"
block
in
let token_red = string_token ~ticketer:ticket_sender "Red" in
(* Call ticket-sender to send a ticket to ticket-receiver. *)
let* block =
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:ticket_sender
~parameters:
(Printf.sprintf {|"%s"|} @@ Contract.to_b58check ticket_receiver)
in
(* Verify that neither ticket-sender nor ticket-receiver holds any balance
for the ticket. *)
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_sender None
in
assert_token_balance ~loc:__LOC__ block token_red ticket_receiver None
(* Test create contract with tickets *)
let test_create_contract_with_ticket () =
let* {block; baker; contract = source_contract} = init_env () in
let* ticket_creator, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter (pair (pair string nat) key_hash) ;
storage unit ;
code { UNPAIR ;
UNPAIR ;
UNPAIR ;
TICKET ;
ASSERT_SOME ;
PUSH mutez 0 ;
DIG 2 ;
SOME ;
CREATE_CONTRACT
{ parameter (ticket string) ;
storage (ticket string) ;
code { CAR ; NIL operation ; PAIR } } ;
SWAP ;
DROP ;
SWAP ;
NIL operation ;
DIG 2 ;
CONS ;
PAIR } }
|}
~storage:"Unit"
block
in
let token_red = string_token ~ticketer:ticket_creator "Red" in
(* Call ticket-creator to originate a new contract with one ticket *)
let* new_contract, block =
get_new_contract block (fun block ->
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:ticket_creator
~parameters:
(Printf.sprintf
{|Pair (Pair "Red" 1) "%s"|}
(Contract.to_b58check source_contract)))
in
let* () =
assert_token_balance ~loc:__LOC__ block token_red new_contract (Some 1)
in
assert_token_balance ~loc:__LOC__ block token_red ticket_creator None
let test_join_tickets () =
let* {block; baker; contract = source_contract} = init_env () in
let* ticket_joiner, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter unit ;
storage (option (ticket string)) ;
code { CDR ;
IF_NONE
{ PUSH nat 1 ; PUSH string "Red" ;
TICKET ; ASSERT_SOME ; SOME ; NIL operation ; PAIR }
{ PUSH nat 1 ;
PUSH string "Red" ;
TICKET ;
ASSERT_SOME ;
PAIR ;
JOIN_TICKETS ;
NIL operation ;
PAIR } } }
|}
~storage:"None"
block
in
let token_red = string_token ~ticketer:ticket_joiner "Red" in
(* Call ticket joiner to create and join an additional ticket. *)
let add block =
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:ticket_joiner
~parameters:"Unit"
in
(* Add three tickets *)
let* block = add block in
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_joiner (Some 1)
in
let* block = add block in
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_joiner (Some 2)
in
let* block = add block in
assert_token_balance ~loc:__LOC__ block token_red ticket_joiner (Some 3)
(* A simple fungible token contract implemented using tickets of type
[ticket unit].
parameter:
- burn: ticket unit
- mint: (contract %destination (ticket unit)) x (nat %amount)
*)
let ticket_builder =
{|
parameter
(or (ticket %burn unit)
(pair %mint (contract %destination (ticket unit)) (nat %amount)));
storage address;
code
{
AMOUNT; PUSH mutez 0; ASSERT_CMPEQ;
UNPAIR;
IF_LEFT
{
# Burn entrypoint
# Check that the ticket is ticketed by ourselves
READ_TICKET; CAR; SELF_ADDRESS; ASSERT_CMPEQ;
# Drop the ticket
DROP;
# Finish
NIL operation
}
{
# Mint entrypoint
# Authenticate SENDER
DUP @manager 2; SENDER; ASSERT_CMPEQ;
UNPAIR;
SWAP; UNIT; TICKET; ASSERT_SOME;
PUSH mutez 0; SWAP; TRANSFER_TOKENS;
NIL operation; SWAP; CONS
};
PAIR
}
|}
(* A simple wallet for fungible tokens implemented using tickets of
type [ticket unit].
parameter:
- receive: ticket unit
- send:
* destination: (contract (ticket unit))
* amount: nat
* ticketer: address
*)
let ticket_wallet =
{|
parameter
(or
(ticket %receive unit)
(pair %send (contract %destination (ticket unit)) (nat %amount) (address %ticketer)));
storage (pair (address %manager) (big_map %tickets address (ticket unit)));
code
{
AMOUNT; PUSH mutez 0; ASSERT_CMPEQ;
UNPAIR 3;
IF_LEFT
{
# Receive entrypoint
# Get the ticketer
READ_TICKET; CAR @ticketer; DUP;
# Extract the associated ticket, if any, from the stored big map
DIG 4;
NONE (ticket unit);
DIG 2;
GET_AND_UPDATE;
# Join it with the parameter
IF_SOME
{
DIG 3;
PAIR;
JOIN_TICKETS;
ASSERT_SOME
}
{ DIG 2 };
SOME;
DIG 2;
GET_AND_UPDATE;
ASSERT_NONE;
SWAP;
PAIR;
NIL operation
}
{
# Send entrypoints
# Authenticate SENDER
DUP @manager 2; SENDER; ASSERT_CMPEQ;
UNPAIR 3;
# Get the ticket associated to the requested ticketer
DIG 4;
NONE (ticket unit);
DUP @ticketer 5;
GET_AND_UPDATE;
ASSERT_SOME;
# Substract the requested amount
READ_TICKET;
GET @total_amount 4;
DUP @amount 5;
SWAP; SUB;
DUP; EQ;
IF
{
# Drop @remaining_amount because it is zero
DROP;
# Drop @amount because this is now irrelevant
DIG 3; DROP;
# Drop @ticketer because we are not storing any ticket in this wallet
DIG 3; DROP;
# Bring the big map to the stack top since the ticket entry is already striked out
DUG 3
}
{
ISNAT; ASSERT_SOME @remaining_amount;
# Split the ticket
DIG 4; PAIR; SWAP; SPLIT_TICKET;
ASSERT_SOME; UNPAIR @to_send @to_keep;
# Store the ticket to keep
DUG 5;
SOME;
DIG 3;
GET_AND_UPDATE;
ASSERT_NONE;
};
DIG 2; PAIR;
# Send the ticket
SWAP;
PUSH mutez 0;
DIG 3;
TRANSFER_TOKENS;
NIL operation;
SWAP;
CONS;
};
PAIR
}
|}
(** Test ticket wallet implementation including sending tickets to self. *)
let test_ticket_wallet () =
let* {block; baker; contract = source_contract} = init_env () in
let* ticket_builder, _script, block =
originate
~baker
~source_contract
~script:ticket_builder
~storage:(Printf.sprintf "%S" @@ Contract.to_b58check source_contract)
block
in
let* ticket_wallet, _script, block =
originate
~baker
~source_contract
~script:ticket_wallet
~storage:
(Printf.sprintf "Pair %S {}" @@ Contract.to_b58check source_contract)
block
in
(* Call ticket-builder to mint one ticket and send to ticket-wallet. *)
let ticket_builder_token = unit_ticket ~ticketer:ticket_builder in
let send_one block =
transaction
~entrypoint:(Entrypoint.of_string_strict_exn "mint")
~baker
~sender:source_contract
block
~recipient:ticket_builder
~parameters:
(Printf.sprintf
{|Pair "%s%sreceive" 1|}
(Contract.to_b58check ticket_wallet)
"%")
in
(* Call ticket wallet to send a ticket to ticket-builder's burn address
entrypoint. *)
let send_to_burn block =
transaction
~entrypoint:(Entrypoint.of_string_strict_exn "send")
~baker
~sender:source_contract
block
~recipient:ticket_wallet
~parameters:
(Printf.sprintf
{|Pair "%s%sburn" 1 %S|}
(Contract.to_b58check ticket_builder)
"%"
(Contract.to_b58check ticket_builder))
in
let send_to_self block =
transaction
~entrypoint:(Entrypoint.of_string_strict_exn "send")
~baker
~sender:source_contract
block
~recipient:ticket_wallet
~parameters:
(Printf.sprintf
{|Pair "%s%sreceive" 1 %S|}
(Contract.to_b58check ticket_wallet)
"%"
(Contract.to_b58check ticket_builder))
in
let assert_balance block balance =
assert_token_balance
~loc:__LOC__
block
ticket_builder_token
ticket_wallet
balance
in
(* Mint and send tickets to wallet. *)
let* block = send_one block in
let* () = assert_balance block (Some 1) in
let* block = send_one block in
let* () = assert_balance block (Some 2) in
(* Send to self should not affect the balance. *)
let* block = send_to_self block in
let* () = assert_balance block (Some 2) in
(* Burn tickets by sending to burn address. *)
let* block = send_to_burn block in
let* () = assert_balance block (Some 1) in
let* block = send_to_burn block in
assert_balance block None
(* Test used ticket storage and paid storage. *)
let test_ticket_storage () =
let* {block; baker; contract = source_contract} = init_env () in
(* A contract that can receive a ticket and store it. Each new ticket it
receives is added to a list. *)
let* ticket_keeper, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter (ticket string) ;
storage (list (ticket string)) ;
code { UNPAIR ; CONS ; NIL operation ; PAIR } }
|}
~storage:"{}"
block
in
(* A contract that receives a pair of ticket and address and forwards the
ticket to the given address. The contract does not store any tickets. *)
let* ticket_forwarder, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter (pair (ticket string) address) ;
storage unit ;
code { CAR ;
UNPAIR ;
SWAP ;
CONTRACT (ticket string) ;
IF_NONE
{ DROP ;
PUSH string "Contract of type `ticket(string)` not found" ;
FAILWITH }
{ PUSH mutez 0 ;
DIG 2 ;
TRANSFER_TOKENS ;
PUSH unit Unit ;
NIL operation ;
DIG 2 ;
CONS ;
PAIR } } }
|}
~storage:"Unit"
block
in
(* A contract that takes two addresses: one to a ticket-forward contract and
one to a ticket-receiver contract, mints and sends the ticket to a
ticket-forward address along with the address of the ticket-receiver.
Altogether we have:
[ticket_minter] ----> [ticket_forwarder] ----> [ticket_receiver]
*)
let* ticket_minter, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter (pair address address) ; storage unit ;
code { CAR ;
UNPAIR ;
CONTRACT (pair (ticket string) address) ;
IF_NONE
{ DROP ;
PUSH string "Contract of type `ticket(string)` not found" ;
FAILWITH }
{ PUSH mutez 0 ;
DIG 2 ;
PUSH nat 1 ;
PUSH string "Red" ;
TICKET ;
ASSERT_SOME ;
PAIR ;
TRANSFER_TOKENS ;
PUSH unit Unit ;
NIL operation ;
DIG 2 ;
CONS ;
PAIR } } } |}
~storage:"Unit"
block
in
let mint_and_send block =
transaction
~entrypoint:Entrypoint.default
~baker
~sender:source_contract
block
~recipient:ticket_minter
~parameters:
(Printf.sprintf
{|Pair %S %S|}
(Contract.to_b58check ticket_forwarder)
(Contract.to_b58check ticket_keeper))
in
let* block = mint_and_send block in
let token_red = string_token ~ticketer:ticket_minter "Red" in
(* Verify that the ticket is accredited to the ticket keeper and no one else.
The ticket table now looks like:
*)
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_minter None
in
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_forwarder None
in
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_keeper (Some 1)
in
(* Both ticket paid and used storage should now be 65 bytes for the key and
one for the value. Ticket table looks like:
| Owner x Ticket-token | Amount |
|--------------------------|--------|
| ticket_keeper x Red | 1 |
Used storage: 65 + 1 = 66
Paid storage: 66
*)
let* () = assert_used_ticket_storage ~loc:__LOC__ block 66 in
let* () = assert_paid_ticket_storage ~loc:__LOC__ block 66 in
(* Send another ticket that uses the same slot. That does not increase used
storage. The first call from [ticket_minter] to ticket-forwarder results in
a table:
| Owner x Ticket-token | Amount |
|--------------------------|--------|
| ticket_forwarder x Red | 1 |
| ticket_keeper x Red | 1 |
Used storage: 132
The call from ticket-forwarder to [ticket_keeper] results in:
| Owner x Ticket-token | Amount |
|--------------------------|--------|
| ticket_keeper x Red | 2 |
Used storage: 66
Noted that the paid-storage "water-marker" was pushed up to 132.
*)
let* block = mint_and_send block in
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_keeper (Some 2)
in
let* () = assert_used_ticket_storage ~loc:__LOC__ block 66 in
let* () = assert_paid_ticket_storage ~loc:__LOC__ block 132 in
(* Send yet another ticket that uses the same slot. That does not increase used
storage and it's using already paid storage. The first call from
[ticket_minter] to ticket-forwarder results in a table:
| Owner x Ticket-token | Amount |
|--------------------------|--------|
| ticket_forwarder x Red | 1 |
| ticket_keeper x Red | 2 |
Used storage: 132
The call from ticket-forwarder to [ticket_keeper] results in:
| Owner x Ticket-token | Amount |
|--------------------------|--------|
| ticket_keeper x Red | 3 |
Used storage: 66
Here, the paid_storage "water-mark" is not pushed up.
*)
let* block = mint_and_send block in
let* () =
assert_token_balance ~loc:__LOC__ block token_red ticket_keeper (Some 3)
in
let* () = assert_used_ticket_storage ~loc:__LOC__ block 66 in
let* () = assert_paid_ticket_storage ~loc:__LOC__ block 132 in
return ()
(* Test used ticket storage and paid storage. *)
let test_storage_for_create_and_remove_tickets () =
let* {block; baker; contract = source_contract} = init_env () in
(* A contract with two endpoints:
- Create n tickets and add to its storage
- Remove all tickets
*)
let* ticket_manager, _script, block =
originate
~baker
~source_contract
~script:
{|
{ parameter (or (pair %add nat string) (unit %clear)) ;
storage (list (ticket string)) ;
code { UNPAIR ;
IF_LEFT
{ UNPAIR ; DIG 2 ; SWAP ; DIG 2 ; TICKET ; ASSERT_SOME ; CONS ; NIL operation ; PAIR }
{ DROP 2 ; NIL (ticket string) ; NIL operation ; PAIR } } }
|}
~storage:"{}"
block
in
let add block n content =
transaction
~entrypoint:(Entrypoint.of_string_strict_exn "add")
~baker
~sender:source_contract
block
~recipient:ticket_manager
~parameters:(Printf.sprintf "Pair %d %S" n content)
in
let clear block =
transaction
~entrypoint:(Entrypoint.of_string_strict_exn "clear")
~baker
~sender:source_contract
block
~recipient:ticket_manager
~parameters:"Unit"
in
(* Initially the used and paid contract storage size is 141. *)
let* () =
assert_used_contract_storage ~loc:__LOC__ block ticket_manager 141
in
let* () =
assert_paid_contract_storage ~loc:__LOC__ block ticket_manager 141
in
(* Add 1000 units of "A" tickets. *)
let* block = add block 1000 "A" in
(* After adding one block the new used and paid storage grows to accommodate
for the new ticket. The size is 141 + 40 (size of ticket) = 181. *)
let* () =
assert_used_contract_storage ~loc:__LOC__ block ticket_manager 181
in
let* () =
assert_paid_contract_storage ~loc:__LOC__ block ticket_manager 181
in
(* The size of used and paid-for ticket storage is 67 bytes. (65 for hash
and 2 for amount). *)
let* () = assert_used_ticket_storage ~loc:__LOC__ block 67 in
let* () = assert_paid_ticket_storage ~loc:__LOC__ block 67 in
(* Add 1000 units of "B" tickets. *)
let* block = add block 1000 "B" in
(* The new used and paid for contract storage grow to 155 + 40 = 195. *)
let* () =
assert_used_contract_storage ~loc:__LOC__ block ticket_manager 221
in
let* () =
assert_paid_contract_storage ~loc:__LOC__ block ticket_manager 221
in
(* The new used and paid for ticket storage doubles (2 * 67 = 134). *)
let* () = assert_used_ticket_storage ~loc:__LOC__ block 134 in
let* () = assert_paid_ticket_storage ~loc:__LOC__ block 134 in
(* Clear all tickets. *)
let* block = clear block in
(* We're back to 115 base-line for the used contract storage and keep 195 for
paid. *)
let* () =
assert_used_contract_storage ~loc:__LOC__ block ticket_manager 141
in
let* () =
assert_paid_contract_storage ~loc:__LOC__ block ticket_manager 221
in
(* Since the ticket-table is empty it does not take up any space. However,
we've already paid for 134 bytes. *)
let* () = assert_used_ticket_storage ~loc:__LOC__ block 0 in
let* () = assert_paid_ticket_storage ~loc:__LOC__ block 134 in
(* Add one unit of "C" tickets. *)
let* block = add block 1 "C" in
(* The new used storage is 141 + 39 (size of ticket) = 180. The size is 39
rather than 40 because it carries a smaller amount payload. *)
let* () =
assert_used_contract_storage ~loc:__LOC__ block ticket_manager 180
in
(* We still have paid for 221 contract storage. *)
let* () =
assert_paid_contract_storage ~loc:__LOC__ block ticket_manager 221
in
(* There is one row in the ticket table with size 65 (for the hash) + 1
(for the amount) = 65 bytes. *)
let* () = assert_used_ticket_storage ~loc:__LOC__ block 66 in
(* We've still paid for 134 bytes however. *)
let* () = assert_paid_ticket_storage ~loc:__LOC__ block 134 in
(* Add yet another "C" ticket. *)
let* block = add block 1 "C" in
(* The new used storage is 180 + 39 (size of ticket) = 219. *)
let* () =
assert_used_contract_storage ~loc:__LOC__ block ticket_manager 219
in
(* We still have paid for 221 contract storage. *)
let* () =
assert_paid_contract_storage ~loc:__LOC__ block ticket_manager 221
in
(* There is still only one row in the ticket table with size 66. *)
let* () = assert_used_ticket_storage ~loc:__LOC__ block 66 in
(* And we've still paid for 134 bytes. *)
let* () = assert_paid_ticket_storage ~loc:__LOC__ block 134 in
(* Add a "D" ticket. *)
let* block = add block 1 "D" in
(* The new used storage is 219 + 39 (size of ticket) = 258. *)
let* () =
assert_used_contract_storage ~loc:__LOC__ block ticket_manager 258
in
(* The paid storage also increases to 258. *)
let* () =
assert_paid_contract_storage ~loc:__LOC__ block ticket_manager 258
in
(* There are now two rows in the ticket table: 2 x 66 = 132 *)
let* () = assert_used_ticket_storage ~loc:__LOC__ block 132 in
(* And we've still paid for 134 bytes. *)
let* () = assert_paid_ticket_storage ~loc:__LOC__ block 134 in
let* block = add block 1 "E" in
(* The new used storage is 258 + 39 (size of ticket) = 297. *)
let* () =
assert_used_contract_storage ~loc:__LOC__ block ticket_manager 297
in
(* The paid storage also increases to 297. *)
let* () =
assert_paid_contract_storage ~loc:__LOC__ block ticket_manager 297
in
(* There are now three rows in the ticket table: 3 x 66 = 198. *)
let* () = assert_used_ticket_storage ~loc:__LOC__ block 198 in
(* And the paid storage has increased. *)
assert_paid_ticket_storage ~loc:__LOC__ block 198
let tests =
[
Tztest.tztest "Test add strict" `Quick test_add_strict;
Tztest.tztest "Test add and remove" `Quick test_add_remove;
Tztest.tztest "Test add to big-map" `Quick test_add_to_big_map;
Tztest.tztest "Test swap big-map" `Quick test_swap_big_map;
Tztest.tztest "Test send ticket" `Quick test_send_tickets;
Tztest.tztest
"Test send and store tickets with amount 0"
`Quick
test_send_and_store_zero_amount_tickets;
Tztest.tztest
"Test send tickets in big-map"
`Quick
test_send_tickets_in_big_map;
Tztest.tztest "Test modify big-map" `Quick test_modify_big_map;
Tztest.tztest "Test send drop" `Quick test_send_tickets_in_big_map_and_drop;
Tztest.tztest "Test send drop" `Quick test_create_contract_with_ticket;
Tztest.tztest "Test join" `Quick test_join_tickets;
Tztest.tztest "Test wallet" `Quick test_ticket_wallet;
Tztest.tztest "Test ticket storage" `Quick test_ticket_storage;
Tztest.tztest
"Test storage for create and remove tickets"
`Quick
test_storage_for_create_and_remove_tickets;
]
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2022 Trili Tech, <contact@trili.tech> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
demo.ml | open Format
open Graph
let v_ = ref 30
let prob_ = ref 0.5
let seed_ = ref None
let interactive_ = ref false
type algo = TransitiveClosure | TransitiveReduction | Prim | Kruskal |
Dijkstra | Bfs | Dfs
let algo = ref None
let arg_spec =
["-v", Arg.Int (fun i -> v_ := i),
" <int> number of vertices";
"--prob", Arg.Float (fun f -> prob_ := f),
" <float> probability to discrad an edge";
"--seed", Arg.Int (fun n -> seed_ := Some n),
" <int> random seed";
"--transitive-closure", Arg.Unit (fun () -> algo := Some TransitiveClosure),
" display transitive closure in blue";
"--transitive-reduction", Arg.Unit (fun () ->
algo := Some TransitiveReduction),
" display useless edges in blue";
"--prim", Arg.Unit (fun () -> algo := Some Prim),
" Prim's algorithm";
"--kruskal", Arg.Unit (fun () -> algo := Some Kruskal),
" Kruskal's algorithm";
"--dijkstra", Arg.Unit (fun () -> algo := Some Dijkstra),
" Dijkstra's algorithm";
"--dfs", Arg.Unit (fun () -> algo := Some Dfs),
" Depth-First Search's algorithm";
"--bfs", Arg.Unit (fun () -> algo := Some Bfs),
" Breadth-First Search's algorithm";
"-i", Arg.Set interactive_, " run algorithms interactively";
]
let () = Arg.parse arg_spec (fun _ -> ()) "usage: color <options>"
let v = !v_
let prob = !prob_
let interactive = !interactive_
let seed = match !seed_ with
| None -> Random.self_init (); Random.int (1 lsl 29)
| Some s -> s
let () = printf "seed = %d@." seed; Random.init seed
let () = if interactive then
printf "interactive mode (press any key to step in algorithm, q to quit)@."
module G = struct
module IntInt = struct
type t = int * int
let compare = Stdlib.compare
let equal = (=)
let hash = Hashtbl.hash
end
module Int = struct
type t = int
let compare = Stdlib.compare
let hash = Hashtbl.hash
let equal = (=)
let default = 0
end
include Imperative.Digraph.ConcreteLabeled(IntInt)(Int)
end
(* a random graph with n vertices *)
module R = Rand.Planar.I(G)
let g = R.graph ~xrange:(20,780) ~yrange:(20,580)~prob v
module Draw = struct
open Graphics
let () = open_graph " 800x600"
let vertex_radius = 5
let round f = truncate (f +. 0.5)
let pi = 4.0 *. atan 1.0
let draw_arrow ?(color=black) ?(width=1) (xu,yu) (xv,yv) =
set_color color;
set_line_width width;
let dx = float (xv - xu) in
let dy = float (yv - yu) in
let alpha = atan2 dy dx in
let r = sqrt (dx *. dx +. dy *. dy) in
let ra = float vertex_radius *. 1.5 in
let d = float vertex_radius +. 3. in
let xs, ys = float xu +. d *. dx /. r, float yu +. d *. dy /. r in
let xd, yd = float xv -. d *. dx /. r, float yv -. d *. dy /. r in
let coords theta =
round (xd +. ra *. cos (pi +. alpha +. theta)),
round (yd +. ra *. sin (pi +. alpha +. theta))
in
moveto (round xs) (round ys);
lineto (round xd) (round yd);
let x1,y1 = coords (pi /. 6.) in
moveto (round xd) (round yd); lineto x1 y1;
let x2,y2 = coords (-. pi /. 6.) in
moveto (round xd) (round yd); lineto x2 y2
let draw_edge ?color ?width v1 v2 =
draw_arrow ?color ?width (G.V.label v1) (G.V.label v2)
let draw_vertex ?(color=red) ?(width=1) v =
let (x,y) = G.V.label v in
set_line_width width;
set_color color;
draw_circle x y vertex_radius
let color_vertex v color =
let x,y = G.V.label v in
set_color color;
fill_circle x y vertex_radius
let draw_graph ?color ?width g =
clear_graph ();
G.iter_vertex draw_vertex g;
G.iter_edges (draw_edge ?color ?width) g
let draw_edges ?(color=blue) ?(width=2) el =
List.iter
(fun e ->
draw_edge ~color ~width (G.E.src e) (G.E.dst e);
draw_vertex ~color ~width (G.E.src e);
draw_vertex ~color ~width (G.E.dst e)
) el
let pause () =
let st = wait_next_event [Key_pressed] in
if st.key = 'q' then begin close_graph (); exit 0 end
let draw_iteration ?(interactive=false) f g =
f (fun v -> color_vertex v Graphics.red; if interactive then pause ()) g
end
module W = struct
type edge = G.E.t
type t = int
let weight = G.E.label
let zero = 0
let add = (+)
let sub = (-)
let compare = compare
end
module PathWeight = struct
type edge = G.E.t
type t = int
let weight x = G.E.label x
let zero = 0
let add = (+)
let sub = (-)
let compare = compare
end
module Selection = struct
type selection =
| No
| One of G.V.t
| Two of G.V.t * G.V.t
let selection = ref No
let draw_selection () = match !selection with
| No -> ()
| One v1 -> Draw.color_vertex v1 Graphics.blue
| Two (v1, v2) -> Draw.color_vertex v1 Graphics.blue;
Draw.color_vertex v2 Graphics.green
let distance (x1,y1) (x2,y2) =
let dx = float (x1 - x2) in
let dy = float (y1 - y2) in
Draw.round (sqrt (dx *. dx +. dy *. dy))
let select g =
let select_vertex v = match !selection with
| No -> selection := One v
| One v1 -> selection := Two (v1, v)
| Two (_, v2) -> selection := Two (v2, v)
in
let p = Graphics.mouse_pos () in
try
G.iter_vertex
(fun v ->
if distance p (G.V.label v) <= Draw.vertex_radius then begin
select_vertex v; Draw.draw_graph g; draw_selection (); raise Exit
end)
g
with Exit -> ()
let select2 g =
printf "please select two vertices...@.";
printf "press r to run...@.";
printf "press q to quit...@.";
let continue = ref true in
while !continue do
let st = Graphics.wait_next_event [ Graphics.Key_pressed;
Graphics.Button_down ] in
if st.Graphics.keypressed then match st.Graphics.key with
| 'r' ->
begin match !selection with
| Two (_,_) -> continue := false
| _ -> printf "please select two vertices...@."
end
| 'q' -> raise Exit
| _ -> ()
else if st.Graphics.button then
select g
done;
match !selection with
| Two (v1,v2) -> (v1,v2)
| _ -> assert false
end
let () = Draw.draw_graph g
let () = match !algo with
| Some Dijkstra -> ()
| _ -> ignore (Graphics.wait_next_event [Graphics.Key_pressed ])
let () = match !algo with
| Some TransitiveClosure ->
let module O = Oper.I(G) in
let tg = O.transitive_closure g in
G.iter_edges
(fun v1 v2 ->
if not (G.mem_edge g v1 v2) then
Draw.draw_edge ~color:Graphics.blue v1 v2) tg
| Some TransitiveReduction ->
Draw.draw_graph ~color:Graphics.blue g;
let module O = Oper.I(G) in
let tr = O.transitive_reduction g in
G.iter_edges Draw.draw_edge tr;
ignore (Graphics.wait_next_event [Graphics.Key_pressed ]);
Draw.draw_graph tr
| Some Prim ->
let module P = Prim.Make(G)(W) in
let el = P.spanningtree g in
Draw.draw_edges el
| Some Kruskal ->
let module P = Kruskal.Make(G)(W) in
let el = P.spanningtree g in
Draw.draw_edges el
| Some Dijkstra ->
let module Dij = Path.Dijkstra(G)(PathWeight) in
let rec recherche () =
let (v1, v2) = Selection.select2 g in
begin
try
let (p, _) = Dij.shortest_path g v1 v2 in
Draw.draw_edges ~color:Graphics.red p
with Not_found ->
printf "no path found...@.";
recherche ()
end
in
recherche ()
| Some Dfs ->
let module Dfs = Traverse.Dfs(G) in
Draw.draw_iteration ~interactive Dfs.prefix g
| Some Bfs ->
let module Bfs = Traverse.Bfs(G) in
Draw.draw_iteration ~interactive Bfs.iter g
| None -> ()
let () =
ignore (Graphics.wait_next_event [Graphics.Key_pressed ]);
Graphics.close_graph ()
| (**************************************************************************)
(* *)
(* Ocamlgraph: a generic graph library for OCaml *)
(* Copyright (C) 2004-2007 *)
(* Sylvain Conchon, Jean-Christophe Filliatre and Julien Signoles *)
(* *)
(* This software is free software; you can redistribute it and/or *)
(* modify it under the terms of the GNU Library General Public *)
(* License version 2, with the special exception on linking *)
(* described in file LICENSE. *)
(* *)
(* This software is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *)
(* *)
(**************************************************************************)
|
bzlamsg.c |
#include "bzlamsg.h"
#include <stdio.h>
#include "assert.h"
#include "bzlacore.h"
BzlaMsg *
bzla_msg_new(Bzla *bzla)
{
assert(bzla);
BzlaMsg *res;
BZLA_CNEW(bzla->mm, res);
res->bzla = bzla;
return res;
}
void
bzla_msg_delete(BzlaMsg *msg)
{
assert(msg);
bzla_mem_freestr(msg->bzla->mm, msg->prefix);
BZLA_DELETE(msg->bzla->mm, msg);
}
void
bzla_msg(BzlaMsg *msg, bool log, const char *filename, const char *fmt, ...)
{
va_list ap;
char *path, *fname, *c, *p;
uint32_t len;
len = strlen(filename) + 1;
BZLA_NEWN(msg->bzla->mm, path, len);
strcpy(path, filename);
/* cut-off file extension */
if ((c = strrchr(path, '.'))) *c = 0;
fname = strrchr(path, '/');
if (!fname)
fname = path;
else
fname += 1;
fputs("[", stdout);
if (log) fputs("log:", stdout);
if (msg->prefix) fprintf(stdout, "%s>", msg->prefix);
p = path;
while ((c = strchr(p, '/')))
{
*c = 0;
/* print at most 4 chars per directory */
if (c - p > 4)
{
p[4] = 0;
fprintf(stdout, "%s>", p);
}
p = c;
}
/* cut-off bzla prefix from file name */
fputs(fname + 4, stdout);
fputs("] ", stdout);
BZLA_DELETEN(msg->bzla->mm, path, len);
va_start(ap, fmt);
vfprintf(stdout, fmt, ap);
va_end(ap);
fputc('\n', stdout);
fflush(stdout);
}
| /***
* 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.
*/ |
process.c |
#include "uv.h"
#include "internal.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>
#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#if defined(__APPLE__)
# include <spawn.h>
# include <paths.h>
# include <sys/kauth.h>
# include <sys/types.h>
# include <sys/sysctl.h>
# include <dlfcn.h>
# include <crt_externs.h>
# include <xlocale.h>
# define environ (*_NSGetEnviron())
/* macOS 10.14 back does not define this constant */
# ifndef POSIX_SPAWN_SETSID
# define POSIX_SPAWN_SETSID 1024
# endif
#else
extern char **environ;
#endif
#if defined(__linux__) || defined(__GLIBC__)
# include <grp.h>
#endif
#if defined(__MVS__)
# include "zos-base.h"
#endif
#if defined(__APPLE__) || \
defined(__DragonFly__) || \
defined(__FreeBSD__) || \
defined(__NetBSD__) || \
defined(__OpenBSD__)
#include <sys/event.h>
#else
#define UV_USE_SIGCHLD
#endif
#ifdef UV_USE_SIGCHLD
static void uv__chld(uv_signal_t* handle, int signum) {
assert(signum == SIGCHLD);
uv__wait_children(handle->loop);
}
#endif
void uv__wait_children(uv_loop_t* loop) {
uv_process_t* process;
int exit_status;
int term_signal;
int status;
int options;
pid_t pid;
QUEUE pending;
QUEUE* q;
QUEUE* h;
QUEUE_INIT(&pending);
h = &loop->process_handles;
q = QUEUE_HEAD(h);
while (q != h) {
process = QUEUE_DATA(q, uv_process_t, queue);
q = QUEUE_NEXT(q);
#ifndef UV_USE_SIGCHLD
if ((process->flags & UV_HANDLE_REAP) == 0)
continue;
options = 0;
process->flags &= ~UV_HANDLE_REAP;
#else
options = WNOHANG;
#endif
do
pid = waitpid(process->pid, &status, options);
while (pid == -1 && errno == EINTR);
#ifdef UV_USE_SIGCHLD
if (pid == 0) /* Not yet exited */
continue;
#endif
if (pid == -1) {
if (errno != ECHILD)
abort();
/* The child died, and we missed it. This probably means someone else
* stole the waitpid from us. Handle this by not handling it at all. */
continue;
}
assert(pid == process->pid);
process->status = status;
QUEUE_REMOVE(&process->queue);
QUEUE_INSERT_TAIL(&pending, &process->queue);
}
h = &pending;
q = QUEUE_HEAD(h);
while (q != h) {
process = QUEUE_DATA(q, uv_process_t, queue);
q = QUEUE_NEXT(q);
QUEUE_REMOVE(&process->queue);
QUEUE_INIT(&process->queue);
uv__handle_stop(process);
if (process->exit_cb == NULL)
continue;
exit_status = 0;
if (WIFEXITED(process->status))
exit_status = WEXITSTATUS(process->status);
term_signal = 0;
if (WIFSIGNALED(process->status))
term_signal = WTERMSIG(process->status);
process->exit_cb(process, exit_status, term_signal);
}
assert(QUEUE_EMPTY(&pending));
}
/*
* Used for initializing stdio streams like options.stdin_stream. Returns
* zero on success. See also the cleanup section in uv_spawn().
*/
static int uv__process_init_stdio(uv_stdio_container_t* container, int fds[2]) {
int mask;
int fd;
mask = UV_IGNORE | UV_CREATE_PIPE | UV_INHERIT_FD | UV_INHERIT_STREAM;
switch (container->flags & mask) {
case UV_IGNORE:
return 0;
case UV_CREATE_PIPE:
assert(container->data.stream != NULL);
if (container->data.stream->type != UV_NAMED_PIPE)
return UV_EINVAL;
else
return uv_socketpair(SOCK_STREAM, 0, fds, 0, 0);
case UV_INHERIT_FD:
case UV_INHERIT_STREAM:
if (container->flags & UV_INHERIT_FD)
fd = container->data.fd;
else
fd = uv__stream_fd(container->data.stream);
if (fd == -1)
return UV_EINVAL;
fds[1] = fd;
return 0;
default:
assert(0 && "Unexpected flags");
return UV_EINVAL;
}
}
static int uv__process_open_stream(uv_stdio_container_t* container,
int pipefds[2]) {
int flags;
int err;
if (!(container->flags & UV_CREATE_PIPE) || pipefds[0] < 0)
return 0;
err = uv__close(pipefds[1]);
if (err != 0)
abort();
pipefds[1] = -1;
uv__nonblock(pipefds[0], 1);
flags = 0;
if (container->flags & UV_WRITABLE_PIPE)
flags |= UV_HANDLE_READABLE;
if (container->flags & UV_READABLE_PIPE)
flags |= UV_HANDLE_WRITABLE;
return uv__stream_open(container->data.stream, pipefds[0], flags);
}
static void uv__process_close_stream(uv_stdio_container_t* container) {
if (!(container->flags & UV_CREATE_PIPE)) return;
uv__stream_close(container->data.stream);
}
static void uv__write_int(int fd, int val) {
ssize_t n;
do
n = write(fd, &val, sizeof(val));
while (n == -1 && errno == EINTR);
/* The write might have failed (e.g. if the parent process has died),
* but we have nothing left but to _exit ourself now too. */
_exit(127);
}
static void uv__write_errno(int error_fd) {
uv__write_int(error_fd, UV__ERR(errno));
}
#if !(defined(__APPLE__) && (TARGET_OS_TV || TARGET_OS_WATCH))
/* execvp is marked __WATCHOS_PROHIBITED __TVOS_PROHIBITED, so must be
* avoided. Since this isn't called on those targets, the function
* doesn't even need to be defined for them.
*/
static void uv__process_child_init(const uv_process_options_t* options,
int stdio_count,
int (*pipes)[2],
int error_fd) {
sigset_t signewset;
int close_fd;
int use_fd;
int fd;
int n;
/* Reset signal disposition first. Use a hard-coded limit because NSIG is not
* fixed on Linux: it's either 32, 34 or 64, depending on whether RT signals
* are enabled. We are not allowed to touch RT signal handlers, glibc uses
* them internally.
*/
for (n = 1; n < 32; n += 1) {
if (n == SIGKILL || n == SIGSTOP)
continue; /* Can't be changed. */
#if defined(__HAIKU__)
if (n == SIGKILLTHR)
continue; /* Can't be changed. */
#endif
if (SIG_ERR != signal(n, SIG_DFL))
continue;
uv__write_errno(error_fd);
}
if (options->flags & UV_PROCESS_DETACHED)
setsid();
/* First duplicate low numbered fds, since it's not safe to duplicate them,
* they could get replaced. Example: swapping stdout and stderr; without
* this fd 2 (stderr) would be duplicated into fd 1, thus making both
* stdout and stderr go to the same fd, which was not the intention. */
for (fd = 0; fd < stdio_count; fd++) {
use_fd = pipes[fd][1];
if (use_fd < 0 || use_fd >= fd)
continue;
#ifdef F_DUPFD_CLOEXEC /* POSIX 2008 */
pipes[fd][1] = fcntl(use_fd, F_DUPFD_CLOEXEC, stdio_count);
#else
pipes[fd][1] = fcntl(use_fd, F_DUPFD, stdio_count);
#endif
if (pipes[fd][1] == -1)
uv__write_errno(error_fd);
#ifndef F_DUPFD_CLOEXEC /* POSIX 2008 */
n = uv__cloexec(pipes[fd][1], 1);
if (n)
uv__write_int(error_fd, n);
#endif
}
for (fd = 0; fd < stdio_count; fd++) {
close_fd = -1;
use_fd = pipes[fd][1];
if (use_fd < 0) {
if (fd >= 3)
continue;
else {
/* Redirect stdin, stdout and stderr to /dev/null even if UV_IGNORE is
* set. */
uv__close_nocheckstdio(fd); /* Free up fd, if it happens to be open. */
use_fd = open("/dev/null", fd == 0 ? O_RDONLY : O_RDWR);
close_fd = use_fd;
if (use_fd < 0)
uv__write_errno(error_fd);
}
}
if (fd == use_fd) {
if (close_fd == -1) {
n = uv__cloexec(use_fd, 0);
if (n)
uv__write_int(error_fd, n);
}
}
else {
fd = dup2(use_fd, fd);
}
if (fd == -1)
uv__write_errno(error_fd);
if (fd <= 2 && close_fd == -1)
uv__nonblock_fcntl(fd, 0);
if (close_fd >= stdio_count)
uv__close(close_fd);
}
if (options->cwd != NULL && chdir(options->cwd))
uv__write_errno(error_fd);
if (options->flags & (UV_PROCESS_SETUID | UV_PROCESS_SETGID)) {
/* When dropping privileges from root, the `setgroups` call will
* remove any extraneous groups. If we don't call this, then
* even though our uid has dropped, we may still have groups
* that enable us to do super-user things. This will fail if we
* aren't root, so don't bother checking the return value, this
* is just done as an optimistic privilege dropping function.
*/
SAVE_ERRNO(setgroups(0, NULL));
}
if ((options->flags & UV_PROCESS_SETGID) && setgid(options->gid))
uv__write_errno(error_fd);
if ((options->flags & UV_PROCESS_SETUID) && setuid(options->uid))
uv__write_errno(error_fd);
if (options->env != NULL)
environ = options->env;
/* Reset signal mask just before exec. */
sigemptyset(&signewset);
if (sigprocmask(SIG_SETMASK, &signewset, NULL) != 0)
abort();
#ifdef __MVS__
execvpe(options->file, options->args, environ);
#else
execvp(options->file, options->args);
#endif
uv__write_errno(error_fd);
}
#endif
#if defined(__APPLE__)
typedef struct uv__posix_spawn_fncs_tag {
struct {
int (*addchdir_np)(const posix_spawn_file_actions_t *, const char *);
} file_actions;
} uv__posix_spawn_fncs_t;
static uv_once_t posix_spawn_init_once = UV_ONCE_INIT;
static uv__posix_spawn_fncs_t posix_spawn_fncs;
static int posix_spawn_can_use_setsid;
static void uv__spawn_init_posix_spawn_fncs(void) {
/* Try to locate all non-portable functions at runtime */
posix_spawn_fncs.file_actions.addchdir_np =
dlsym(RTLD_DEFAULT, "posix_spawn_file_actions_addchdir_np");
}
static void uv__spawn_init_can_use_setsid(void) {
int which[] = {CTL_KERN, KERN_OSRELEASE};
unsigned major;
unsigned minor;
unsigned patch;
char buf[256];
size_t len;
len = sizeof(buf);
if (sysctl(which, ARRAY_SIZE(which), buf, &len, NULL, 0))
return;
/* NULL specifies to use LC_C_LOCALE */
if (3 != sscanf_l(buf, NULL, "%u.%u.%u", &major, &minor, &patch))
return;
posix_spawn_can_use_setsid = (major >= 19); /* macOS Catalina */
}
static void uv__spawn_init_posix_spawn(void) {
/* Init handles to all potentially non-defined functions */
uv__spawn_init_posix_spawn_fncs();
/* Init feature detection for POSIX_SPAWN_SETSID flag */
uv__spawn_init_can_use_setsid();
}
static int uv__spawn_set_posix_spawn_attrs(
posix_spawnattr_t* attrs,
const uv__posix_spawn_fncs_t* posix_spawn_fncs,
const uv_process_options_t* options) {
int err;
unsigned int flags;
sigset_t signal_set;
err = posix_spawnattr_init(attrs);
if (err != 0) {
/* If initialization fails, no need to de-init, just return */
return err;
}
if (options->flags & (UV_PROCESS_SETUID | UV_PROCESS_SETGID)) {
/* kauth_cred_issuser currently requires exactly uid == 0 for these
* posixspawn_attrs (set_groups_np, setuid_np, setgid_np), which deviates
* from the normal specification of setuid (which also uses euid), and they
* are also undocumented syscalls, so we do not use them. */
err = ENOSYS;
goto error;
}
/* Set flags for spawn behavior
* 1) POSIX_SPAWN_CLOEXEC_DEFAULT: (Apple Extension) All descriptors in the
* parent will be treated as if they had been created with O_CLOEXEC. The
* only fds that will be passed on to the child are those manipulated by
* the file actions
* 2) POSIX_SPAWN_SETSIGDEF: Signals mentioned in spawn-sigdefault in the
* spawn attributes will be reset to behave as their default
* 3) POSIX_SPAWN_SETSIGMASK: Signal mask will be set to the value of
* spawn-sigmask in attributes
* 4) POSIX_SPAWN_SETSID: Make the process a new session leader if a detached
* session was requested. */
flags = POSIX_SPAWN_CLOEXEC_DEFAULT |
POSIX_SPAWN_SETSIGDEF |
POSIX_SPAWN_SETSIGMASK;
if (options->flags & UV_PROCESS_DETACHED) {
/* If running on a version of macOS where this flag is not supported,
* revert back to the fork/exec flow. Otherwise posix_spawn will
* silently ignore the flag. */
if (!posix_spawn_can_use_setsid) {
err = ENOSYS;
goto error;
}
flags |= POSIX_SPAWN_SETSID;
}
err = posix_spawnattr_setflags(attrs, flags);
if (err != 0)
goto error;
/* Reset all signal the child to their default behavior */
sigfillset(&signal_set);
err = posix_spawnattr_setsigdefault(attrs, &signal_set);
if (err != 0)
goto error;
/* Reset the signal mask for all signals */
sigemptyset(&signal_set);
err = posix_spawnattr_setsigmask(attrs, &signal_set);
if (err != 0)
goto error;
return err;
error:
(void) posix_spawnattr_destroy(attrs);
return err;
}
static int uv__spawn_set_posix_spawn_file_actions(
posix_spawn_file_actions_t* actions,
const uv__posix_spawn_fncs_t* posix_spawn_fncs,
const uv_process_options_t* options,
int stdio_count,
int (*pipes)[2]) {
int fd;
int fd2;
int use_fd;
int err;
err = posix_spawn_file_actions_init(actions);
if (err != 0) {
/* If initialization fails, no need to de-init, just return */
return err;
}
/* Set the current working directory if requested */
if (options->cwd != NULL) {
if (posix_spawn_fncs->file_actions.addchdir_np == NULL) {
err = ENOSYS;
goto error;
}
err = posix_spawn_fncs->file_actions.addchdir_np(actions, options->cwd);
if (err != 0)
goto error;
}
/* Do not return ENOSYS after this point, as we may mutate pipes. */
/* First duplicate low numbered fds, since it's not safe to duplicate them,
* they could get replaced. Example: swapping stdout and stderr; without
* this fd 2 (stderr) would be duplicated into fd 1, thus making both
* stdout and stderr go to the same fd, which was not the intention. */
for (fd = 0; fd < stdio_count; fd++) {
use_fd = pipes[fd][1];
if (use_fd < 0 || use_fd >= fd)
continue;
use_fd = stdio_count;
for (fd2 = 0; fd2 < stdio_count; fd2++) {
/* If we were not setting POSIX_SPAWN_CLOEXEC_DEFAULT, we would need to
* also consider whether fcntl(fd, F_GETFD) returned without the
* FD_CLOEXEC flag set. */
if (pipes[fd2][1] == use_fd) {
use_fd++;
fd2 = 0;
}
}
err = posix_spawn_file_actions_adddup2(
actions,
pipes[fd][1],
use_fd);
assert(err != ENOSYS);
if (err != 0)
goto error;
pipes[fd][1] = use_fd;
}
/* Second, move the descriptors into their respective places */
for (fd = 0; fd < stdio_count; fd++) {
use_fd = pipes[fd][1];
if (use_fd < 0) {
if (fd >= 3)
continue;
else {
/* If ignored, redirect to (or from) /dev/null, */
err = posix_spawn_file_actions_addopen(
actions,
fd,
"/dev/null",
fd == 0 ? O_RDONLY : O_RDWR,
0);
assert(err != ENOSYS);
if (err != 0)
goto error;
continue;
}
}
if (fd == use_fd)
err = posix_spawn_file_actions_addinherit_np(actions, fd);
else
err = posix_spawn_file_actions_adddup2(actions, use_fd, fd);
assert(err != ENOSYS);
if (err != 0)
goto error;
/* Make sure the fd is marked as non-blocking (state shared between child
* and parent). */
uv__nonblock_fcntl(use_fd, 0);
}
/* Finally, close all the superfluous descriptors */
for (fd = 0; fd < stdio_count; fd++) {
use_fd = pipes[fd][1];
if (use_fd < stdio_count)
continue;
/* Check if we already closed this. */
for (fd2 = 0; fd2 < fd; fd2++) {
if (pipes[fd2][1] == use_fd)
break;
}
if (fd2 < fd)
continue;
err = posix_spawn_file_actions_addclose(actions, use_fd);
assert(err != ENOSYS);
if (err != 0)
goto error;
}
return 0;
error:
(void) posix_spawn_file_actions_destroy(actions);
return err;
}
char* uv__spawn_find_path_in_env(char** env) {
char** env_iterator;
const char path_var[] = "PATH=";
/* Look for an environment variable called PATH in the
* provided env array, and return its value if found */
for (env_iterator = env; *env_iterator != NULL; env_iterator++) {
if (strncmp(*env_iterator, path_var, sizeof(path_var) - 1) == 0) {
/* Found "PATH=" at the beginning of the string */
return *env_iterator + sizeof(path_var) - 1;
}
}
return NULL;
}
static int uv__spawn_resolve_and_spawn(const uv_process_options_t* options,
posix_spawnattr_t* attrs,
posix_spawn_file_actions_t* actions,
pid_t* pid) {
const char *p;
const char *z;
const char *path;
size_t l;
size_t k;
int err;
int seen_eacces;
path = NULL;
err = -1;
seen_eacces = 0;
/* Short circuit for erroneous case */
if (options->file == NULL)
return ENOENT;
/* The environment for the child process is that of the parent unless overriden
* by options->env */
char** env = environ;
if (options->env != NULL)
env = options->env;
/* If options->file contains a slash, posix_spawn/posix_spawnp should behave
* the same, and do not involve PATH resolution at all. The libc
* `posix_spawnp` provided by Apple is buggy (since 10.15), so we now emulate it
* here, per https://github.com/libuv/libuv/pull/3583. */
if (strchr(options->file, '/') != NULL) {
do
err = posix_spawn(pid, options->file, actions, attrs, options->args, env);
while (err == EINTR);
return err;
}
/* Look for the definition of PATH in the provided env */
path = uv__spawn_find_path_in_env(env);
/* The following resolution logic (execvpe emulation) is copied from
* https://git.musl-libc.org/cgit/musl/tree/src/process/execvp.c
* and adapted to work for our specific usage */
/* If no path was provided in env, use the default value
* to look for the executable */
if (path == NULL)
path = _PATH_DEFPATH;
k = strnlen(options->file, NAME_MAX + 1);
if (k > NAME_MAX)
return ENAMETOOLONG;
l = strnlen(path, PATH_MAX - 1) + 1;
for (p = path;; p = z) {
/* Compose the new process file from the entry in the PATH
* environment variable and the actual file name */
char b[PATH_MAX + NAME_MAX];
z = strchr(p, ':');
if (!z)
z = p + strlen(p);
if ((size_t)(z - p) >= l) {
if (!*z++)
break;
continue;
}
memcpy(b, p, z - p);
b[z - p] = '/';
memcpy(b + (z - p) + (z > p), options->file, k + 1);
/* Try to spawn the new process file. If it fails with ENOENT, the
* new process file is not in this PATH entry, continue with the next
* PATH entry. */
do
err = posix_spawn(pid, b, actions, attrs, options->args, env);
while (err == EINTR);
switch (err) {
case EACCES:
seen_eacces = 1;
break; /* continue search */
case ENOENT:
case ENOTDIR:
break; /* continue search */
default:
return err;
}
if (!*z++)
break;
}
if (seen_eacces)
return EACCES;
return err;
}
static int uv__spawn_and_init_child_posix_spawn(
const uv_process_options_t* options,
int stdio_count,
int (*pipes)[2],
pid_t* pid,
const uv__posix_spawn_fncs_t* posix_spawn_fncs) {
int err;
posix_spawnattr_t attrs;
posix_spawn_file_actions_t actions;
err = uv__spawn_set_posix_spawn_attrs(&attrs, posix_spawn_fncs, options);
if (err != 0)
goto error;
/* This may mutate pipes. */
err = uv__spawn_set_posix_spawn_file_actions(&actions,
posix_spawn_fncs,
options,
stdio_count,
pipes);
if (err != 0) {
(void) posix_spawnattr_destroy(&attrs);
goto error;
}
/* Try to spawn options->file resolving in the provided environment
* if any */
err = uv__spawn_resolve_and_spawn(options, &attrs, &actions, pid);
assert(err != ENOSYS);
/* Destroy the actions/attributes */
(void) posix_spawn_file_actions_destroy(&actions);
(void) posix_spawnattr_destroy(&attrs);
error:
/* In an error situation, the attributes and file actions are
* already destroyed, only the happy path requires cleanup */
return UV__ERR(err);
}
#endif
static int uv__spawn_and_init_child_fork(const uv_process_options_t* options,
int stdio_count,
int (*pipes)[2],
int error_fd,
pid_t* pid) {
sigset_t signewset;
sigset_t sigoldset;
/* Start the child with most signals blocked, to avoid any issues before we
* can reset them, but allow program failures to exit (and not hang). */
sigfillset(&signewset);
sigdelset(&signewset, SIGKILL);
sigdelset(&signewset, SIGSTOP);
sigdelset(&signewset, SIGTRAP);
sigdelset(&signewset, SIGSEGV);
sigdelset(&signewset, SIGBUS);
sigdelset(&signewset, SIGILL);
sigdelset(&signewset, SIGSYS);
sigdelset(&signewset, SIGABRT);
if (pthread_sigmask(SIG_BLOCK, &signewset, &sigoldset) != 0)
abort();
*pid = fork();
if (*pid == 0) {
/* Fork succeeded, in the child process */
uv__process_child_init(options, stdio_count, pipes, error_fd);
abort();
}
if (pthread_sigmask(SIG_SETMASK, &sigoldset, NULL) != 0)
abort();
if (*pid == -1)
/* Failed to fork */
return UV__ERR(errno);
/* Fork succeeded, in the parent process */
return 0;
}
static int uv__spawn_and_init_child(
uv_loop_t* loop,
const uv_process_options_t* options,
int stdio_count,
int (*pipes)[2],
pid_t* pid) {
int signal_pipe[2] = { -1, -1 };
int status;
int err;
int exec_errorno;
ssize_t r;
#if defined(__APPLE__)
uv_once(&posix_spawn_init_once, uv__spawn_init_posix_spawn);
/* Special child process spawn case for macOS Big Sur (11.0) onwards
*
* Big Sur introduced a significant performance degradation on a call to
* fork/exec when the process has many pages mmaped in with MAP_JIT, like, say
* a javascript interpreter. Electron-based applications, for example,
* are impacted; though the magnitude of the impact depends on how much the
* app relies on subprocesses.
*
* On macOS, though, posix_spawn is implemented in a way that does not
* exhibit the problem. This block implements the forking and preparation
* logic with posix_spawn and its related primitives. It also takes advantage of
* the macOS extension POSIX_SPAWN_CLOEXEC_DEFAULT that makes impossible to
* leak descriptors to the child process. */
err = uv__spawn_and_init_child_posix_spawn(options,
stdio_count,
pipes,
pid,
&posix_spawn_fncs);
/* The posix_spawn flow will return UV_ENOSYS if any of the posix_spawn_x_np
* non-standard functions is both _needed_ and _undefined_. In those cases,
* default back to the fork/execve strategy. For all other errors, just fail. */
if (err != UV_ENOSYS)
return err;
#endif
/* This pipe is used by the parent to wait until
* the child has called `execve()`. We need this
* to avoid the following race condition:
*
* if ((pid = fork()) > 0) {
* kill(pid, SIGTERM);
* }
* else if (pid == 0) {
* execve("/bin/cat", argp, envp);
* }
*
* The parent sends a signal immediately after forking.
* Since the child may not have called `execve()` yet,
* there is no telling what process receives the signal,
* our fork or /bin/cat.
*
* To avoid ambiguity, we create a pipe with both ends
* marked close-on-exec. Then, after the call to `fork()`,
* the parent polls the read end until it EOFs or errors with EPIPE.
*/
err = uv__make_pipe(signal_pipe, 0);
if (err)
return err;
/* Acquire write lock to prevent opening new fds in worker threads */
uv_rwlock_wrlock(&loop->cloexec_lock);
err = uv__spawn_and_init_child_fork(options, stdio_count, pipes, signal_pipe[1], pid);
/* Release lock in parent process */
uv_rwlock_wrunlock(&loop->cloexec_lock);
uv__close(signal_pipe[1]);
if (err == 0) {
do
r = read(signal_pipe[0], &exec_errorno, sizeof(exec_errorno));
while (r == -1 && errno == EINTR);
if (r == 0)
; /* okay, EOF */
else if (r == sizeof(exec_errorno)) {
do
err = waitpid(*pid, &status, 0); /* okay, read errorno */
while (err == -1 && errno == EINTR);
assert(err == *pid);
err = exec_errorno;
} else if (r == -1 && errno == EPIPE) {
/* Something unknown happened to our child before spawn */
do
err = waitpid(*pid, &status, 0); /* okay, got EPIPE */
while (err == -1 && errno == EINTR);
assert(err == *pid);
err = UV_EPIPE;
} else
abort();
}
uv__close_nocheckstdio(signal_pipe[0]);
return err;
}
int uv_spawn(uv_loop_t* loop,
uv_process_t* process,
const uv_process_options_t* options) {
#if defined(__APPLE__) && (TARGET_OS_TV || TARGET_OS_WATCH)
/* fork is marked __WATCHOS_PROHIBITED __TVOS_PROHIBITED. */
return UV_ENOSYS;
#else
int pipes_storage[8][2];
int (*pipes)[2];
int stdio_count;
pid_t pid;
int err;
int exec_errorno;
int i;
assert(options->file != NULL);
assert(!(options->flags & ~(UV_PROCESS_DETACHED |
UV_PROCESS_SETGID |
UV_PROCESS_SETUID |
UV_PROCESS_WINDOWS_HIDE |
UV_PROCESS_WINDOWS_HIDE_CONSOLE |
UV_PROCESS_WINDOWS_HIDE_GUI |
UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS)));
uv__handle_init(loop, (uv_handle_t*)process, UV_PROCESS);
QUEUE_INIT(&process->queue);
process->status = 0;
stdio_count = options->stdio_count;
if (stdio_count < 3)
stdio_count = 3;
err = UV_ENOMEM;
pipes = pipes_storage;
if (stdio_count > (int) ARRAY_SIZE(pipes_storage))
pipes = uv__malloc(stdio_count * sizeof(*pipes));
if (pipes == NULL)
goto error;
for (i = 0; i < stdio_count; i++) {
pipes[i][0] = -1;
pipes[i][1] = -1;
}
for (i = 0; i < options->stdio_count; i++) {
err = uv__process_init_stdio(options->stdio + i, pipes[i]);
if (err)
goto error;
}
#ifdef UV_USE_SIGCHLD
uv_signal_start(&loop->child_watcher, uv__chld, SIGCHLD);
#endif
/* Spawn the child */
exec_errorno = uv__spawn_and_init_child(loop, options, stdio_count, pipes, &pid);
#if 0
/* This runs into a nodejs issue (it expects initialized streams, even if the
* exec failed).
* See https://github.com/libuv/libuv/pull/3107#issuecomment-782482608 */
if (exec_errorno != 0)
goto error;
#endif
/* Activate this handle if exec() happened successfully, even if we later
* fail to open a stdio handle. This ensures we can eventually reap the child
* with waitpid. */
if (exec_errorno == 0) {
#ifndef UV_USE_SIGCHLD
struct kevent event;
EV_SET(&event, pid, EVFILT_PROC, EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, 0);
if (kevent(loop->backend_fd, &event, 1, NULL, 0, NULL)) {
if (errno != ESRCH)
abort();
/* Process already exited. Call waitpid on the next loop iteration. */
process->flags |= UV_HANDLE_REAP;
loop->flags |= UV_LOOP_REAP_CHILDREN;
}
#endif
process->pid = pid;
process->exit_cb = options->exit_cb;
QUEUE_INSERT_TAIL(&loop->process_handles, &process->queue);
uv__handle_start(process);
}
for (i = 0; i < options->stdio_count; i++) {
err = uv__process_open_stream(options->stdio + i, pipes[i]);
if (err == 0)
continue;
while (i--)
uv__process_close_stream(options->stdio + i);
goto error;
}
if (pipes != pipes_storage)
uv__free(pipes);
return exec_errorno;
error:
if (pipes != NULL) {
for (i = 0; i < stdio_count; i++) {
if (i < options->stdio_count)
if (options->stdio[i].flags & (UV_INHERIT_FD | UV_INHERIT_STREAM))
continue;
if (pipes[i][0] != -1)
uv__close_nocheckstdio(pipes[i][0]);
if (pipes[i][1] != -1)
uv__close_nocheckstdio(pipes[i][1]);
}
if (pipes != pipes_storage)
uv__free(pipes);
}
return err;
#endif
}
int uv_process_kill(uv_process_t* process, int signum) {
return uv_kill(process->pid, signum);
}
int uv_kill(int pid, int signum) {
if (kill(pid, signum)) {
#if defined(__MVS__)
/* EPERM is returned if the process is a zombie. */
siginfo_t infop;
if (errno == EPERM &&
waitid(P_PID, pid, &infop, WNOHANG | WNOWAIT | WEXITED) == 0)
return 0;
#endif
return UV__ERR(errno);
} else
return 0;
}
void uv__process_close(uv_process_t* handle) {
QUEUE_REMOVE(&handle->queue);
uv__handle_stop(handle);
if (QUEUE_EMPTY(&handle->loop->process_handles))
uv_signal_stop(&handle->loop->child_watcher);
}
| /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/ |
parser_state.ml |
type mode = Normal | Ignore | Ident
let mode = ref Normal
let mode_normal () = mode := Normal
let mode_ignore () = mode := Ignore
let mode_ident () = mode := Ident
| |
dune |
(install
(files Makefile.preprocess)
(section lib)
(package visitors)
)
| |
fasta_sequence_lengths.ml |
open! Base
let fasta_file = (Sys.get_argv ()).(1)
let () =
(* This open gives you [In_channel] and [Record]. *)
let open Bio_io.Fasta in
In_channel.with_file_iter_records fasta_file ~f:(fun record ->
(* Print the ID and the length of the sequence. *)
Stdio.printf "%s => %d\n" (Record.id record) (Record.seq_length record))
| |
bounded.mli | (** This module implements bounded (or refined) versions of data types. *)
(** Bounded [int32]. *)
module Int32 : sig
(** Bounds.
Formally each [B : BOUND] represents the interval of all integers
between [B.min_int] and [B.max_int]. This is a closed interval, e.g.
the endpoints are included.
Intervals can be empty, for example [struct let min_int = 1; let max_int
0 end] is empty.
*)
module type BOUNDS = sig
val min_int : int32
val max_int : int32
end
module type S = sig
type t
include BOUNDS
include Compare.S with type t := t
val encoding : t Data_encoding.t
val to_int32 : t -> int32
val of_int32 : int32 -> t option
end
(** Produce a module [_ : S] of bounded integers.
If the given interval is empty, [S.t] is the empty type, and [of_int32]
returns [Error] for all inputs.
{4 Encoding}
[(Make B).encoding] is based on the underlying [int32] encoding. This
allow future compatiblity with larger bounds, at the price of addding 1-3
redundant bytes to each message.
*)
module Make (_ : BOUNDS) : S
end
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2022 Trili Tech, <contact@trili.tech> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
dune |
(library
(name build_path_prefix_map))
| |
List.ml |
open Functional
let nil = []
let cons x xs = x :: xs
let fold items null_case list_case =
let rec _visit xs return =
match xs with
| [] -> return null_case
| x :: xs' ->
_visit xs' (return <== (list_case x))
in
_visit items identity
let fold_rev items null_case list_case =
let rec _visit xs result =
match xs with
| [] -> result
| x :: xs' ->
_visit xs' (list_case x result)
in
_visit items null_case
let length items =
fold_rev items Nat.zero (fun _x -> Nat.succ)
let iter items func =
fold items () (fun item () -> func item)
let init count item =
if count <= 0 then [] else
let rec _visit index result =
if index = count then result else
_visit (index + 1) (item :: result)
in
_visit 0 []
let map func items =
fold items [] (cons <== func)
let conc left right =
fold left right cons
let flatten items =
fold items [] conc
let rec zip xs ys fail return =
match xs, ys with
| [], [] -> return []
| x :: xs1, y :: ys1 ->
zip xs1 ys1 fail @@ fun xys ->
return ((x, y) :: xys)
| _, _ -> fail ()
let select order n xs =
let _ordered x1 x2 =
let open Order in
match order x1 x2 with
| LT | EQ -> true
| GT -> false
in
let _sort_2 x1 x2 return =
if _ordered x1 x2
then return x1 x2
else return x2 x1
in
let _sort_3 x1 x2 x3 return =
_sort_2 x1 x2 @@ fun x4 x5 ->
if _ordered x3 x4 then return x3 x4 x5 else
if _ordered x3 x5 then return x4 x3 x5 else
return x4 x5 x3
in
let _sort_4 x1 x2 x3 x4 return =
_sort_3 x1 x2 x3 @@ fun x5 x6 x7 ->
if _ordered x4 x5 then return x4 x5 x6 x7 else
if _ordered x4 x6 then return x5 x4 x6 x7 else
if _ordered x4 x7 then return x5 x6 x4 x7 else
return x5 x6 x7 x4
in
let _sort_5 x1 x2 x3 x4 x5 return =
_sort_4 x1 x2 x3 x4 @@ fun x6 x7 x8 x9 ->
if _ordered x7 x5 then
if _ordered x5 x8 then return x6 x7 x5 x8 x9 else
if _ordered x5 x9 then return x6 x7 x8 x5 x9 else
return x6 x7 x8 x9 x5
else
if _ordered x6 x5
then return x6 x5 x7 x8 x9
else return x5 x6 x7 x8 x9
in
let rec _median_of_medians xs return =
let rec _median_of_fives xs return =
match xs with
| [] -> assert false (* Invariant *)
| x1 :: [] -> return [ x1 ]
| x1 :: x2 :: [] ->
_sort_2 x1 x2 @@ fun _x3 x4 -> return [ x4 ]
| x1 :: x2 :: x3 :: [] ->
_sort_3 x1 x2 x3 @@ fun _x4 x5 _x6 -> return [ x5 ]
| x1 :: x2 :: x3 :: x4 :: [] ->
_sort_4 x1 x2 x3 x4 @@ fun _x5 x6 _x7 _x8 -> return [ x6 ]
| x1 :: x2 :: x3 :: x4 :: x5 :: [] ->
_sort_5 x1 x2 x3 x4 x5 @@ fun _x6 _x7 x8 _x9 _x10 -> return [ x8 ]
| x1 :: x2 :: x3 :: x4 :: x5 :: xs1 ->
_sort_5 x1 x2 x3 x4 x5 @@ fun _x6 _x7 x8 _x9 _x10 ->
_median_of_fives xs1 (return <== (cons x8))
in
match xs with
| [] -> assert false (* Invariant *)
| x1 :: [] -> return x1
| x1 :: x2 :: [] ->
_sort_2 x1 x2 @@ fun x3 _x4 -> return x3
| x1 :: x2 :: x3 :: [] ->
_sort_3 x1 x2 x3 @@ fun _x4 x5 _x6 -> return x5
| x1 :: x2 :: x3 :: x4 :: [] ->
_sort_4 x1 x2 x3 x4 @@ fun _x5 x6 _x7 _x8 -> return x6
| x1 :: x2 :: x3 :: x4 :: x5 :: [] ->
_sort_5 x1 x2 x3 x4 x5 @@ fun _x6 _x7 x8 _x9 _x10 -> return x8
| _ ->
_median_of_fives xs @@ fun medians ->
_median_of_medians medians return
in
let _partition xs pivot return =
let rec _visit xs k left right =
match xs with
| [] -> return k left right
| x :: xs1 ->
if _ordered x pivot
then _visit xs1 (k + 1) (x :: left) right
else _visit xs1 k left (x :: right)
in
_visit xs 0 [] []
in
let rec _quick n xs return =
match xs with
| [] -> assert false (* Invariant *)
| x1 :: [] ->
begin match n with
| 0 -> return x1
| _ -> assert false (* Invariant *)
end
| x1 :: x2 :: [] ->
_sort_2 x1 x2 @@ fun x3 x4 ->
begin match n with
| 0 -> return x3
| 1 -> return x4
| _ -> assert false (* Invariant *)
end
| x1 :: x2 :: x3 :: [] ->
_sort_3 x1 x2 x3 @@ fun x4 x5 x6 ->
begin match n with
| 0 -> return x4
| 1 -> return x5
| 2 -> return x6
| _ -> assert false (* Invariant *)
end
| x1 :: x2 :: x3 :: x4 :: [] ->
_sort_4 x1 x2 x3 x4 @@ fun x5 x6 x7 x8 ->
begin match n with
| 0 -> return x5
| 1 -> return x6
| 2 -> return x7
| 3 -> return x8
| _ -> assert false (* Invariant *)
end
| x1 :: x2 :: x3 :: x4 :: x5 :: [] ->
_sort_5 x1 x2 x3 x4 x5 @@ fun x6 x7 x8 x9 x10 ->
begin match n with
| 0 -> return x6
| 1 -> return x7
| 2 -> return x8
| 3 -> return x9
| 4 -> return x10
| _ -> assert false (* Invariant *)
end
| _ ->
_median_of_medians xs @@ fun pivot ->
_partition xs pivot @@ fun k left right ->
length xs |> fun l ->
if k = l then return pivot else
if n < k then _quick n left return else
_quick (n - k) right return
in
_quick n xs identity
let sort order xs =
let _ordered x1 x2 =
let open Order in
match order x1 x2 with
| LT | EQ -> true
| GT -> false
in
let _sort_2 x1 x2 return =
if _ordered x1 x2
then return x1 x2
else return x2 x1
in
let _sort_3 x1 x2 x3 return =
_sort_2 x1 x2 @@ fun x4 x5 ->
if _ordered x3 x4 then return x3 x4 x5 else
if _ordered x3 x5 then return x4 x3 x5 else
return x4 x5 x3
in
let _sort_4 x1 x2 x3 x4 return =
_sort_3 x1 x2 x3 @@ fun x5 x6 x7 ->
if _ordered x4 x5 then return x4 x5 x6 x7 else
if _ordered x4 x6 then return x5 x4 x6 x7 else
if _ordered x4 x7 then return x5 x6 x4 x7 else
return x5 x6 x7 x4
in
let _sort_5 x1 x2 x3 x4 x5 return =
_sort_4 x1 x2 x3 x4 @@ fun x6 x7 x8 x9 ->
if _ordered x7 x5 then
if _ordered x5 x8 then return x6 x7 x5 x8 x9 else
if _ordered x5 x9 then return x6 x7 x8 x5 x9 else
return x6 x7 x8 x9 x5
else
if _ordered x6 x5
then return x6 x5 x7 x8 x9
else return x5 x6 x7 x8 x9
in
let _partition xs pivot return =
let rec _visit xs ln rn left right =
match xs with
| [] -> return ln rn left right
| x :: xs1 ->
if _ordered x pivot
then _visit xs1 (ln + 1) rn (x :: left) right
else _visit xs1 ln (rn + 1) left (x :: right)
in
_visit xs 0 0 [] []
in
let rec _quick xs n result return =
match xs with
| [] -> return result
| x1 :: [] -> return (x1 :: result)
| x1 :: x2 :: [] ->
_sort_2 x1 x2 @@ fun x3 x4 ->
return (x3 :: x4 :: result)
| x1 :: x2 :: x3 :: [] ->
_sort_3 x1 x2 x3 @@ fun x4 x5 x6 ->
return (x4 :: x5 :: x6 :: result)
| x1 :: x2 :: x3 :: x4 :: [] ->
_sort_4 x1 x2 x3 x4 @@ fun x5 x6 x7 x8 ->
return (x5 :: x6 :: x7 :: x8 :: result)
| x1 :: x2 :: x3 :: x4 :: x5 :: [] ->
_sort_5 x1 x2 x3 x4 x5 @@ fun x6 x7 x8 x9 x10 ->
return (x6 :: x7 :: x8 :: x9 :: x10 :: result)
| _ ->
select order (n / 2) xs |> fun pivot ->
_partition xs pivot @@ fun ln rn left right ->
length xs |> fun l ->
if ln = l then return xs else
_quick right rn result @@ fun result1 ->
_quick left ln result1 return
in
length xs |> fun l ->
_quick xs l [] identity
let sort_unique order xs =
let open Order in
let rec _visit x xs return =
match xs with
| [] -> return [ x ]
| y :: xs1 ->
match order x y with
| GT -> assert false (* Invariant *)
| LT -> _visit y xs1 (return <== (cons x))
| EQ -> _visit x xs1 return
in
sort order xs |> fun xs1 ->
match xs1 with
| [] -> []
| x :: xs2 ->
_visit x xs2 identity
| |
plist_xml.ml |
include Plist_tree
include Token
include Error
let dtd =
{|<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">|}
let dtd_signal = `Dtd (Some dtd)
let plist_start_signal = `El_start (("", "plist"), [])
let array_start_signal = `El_start (("", "array"), [])
let data_start_signal = `El_start (("", "data"), [])
let date_start_signal = `El_start (("", "date"), [])
let dict_start_signal = `El_start (("", "dict"), [])
let false_start_signal = `El_start (("", "false"), [])
let integer_start_signal = `El_start (("", "integer"), [])
let key_start_signal = `El_start (("", "key"), [])
let real_start_signal = `El_start (("", "real"), [])
let string_start_signal = `El_start (("", "string"), [])
let true_start_signal = `El_start (("", "true"), [])
let error_message = function
| `Expected_tag tag -> "Expected_tag " ^ tag
| `Expected_start -> "Expected_start"
| `Expected_end -> "Expected_end"
| `Expected_start_or_end -> "Expected_start_or_end"
| `Expected_data -> "Expected_data"
| `Malformed_base64 s -> "Malformed_base64 " ^ s
| `Malformed_date s -> "Malformed_date " ^ s
| `Malformed_int s -> "Malformed_int " ^ s
| `Malformed_real s -> "Malformed_real " ^ s
| `Unknown_tag s -> "Unknown_tag " ^ s
let error input error = raise (Error (Xmlm.pos input, error))
let is_whitespace = function
| ' ' | '\x0C' | '\n' | '\r' | '\t' -> true
| _ -> false
let all_whitespace = String.for_all is_whitespace
let skip_whitespace input =
match Xmlm.peek input with
| `Data data when all_whitespace data -> ignore (Xmlm.input input)
| _ -> ()
let lose_whitespace str =
let count =
String.fold_left
(fun count ch -> if is_whitespace ch then count else count + 1)
0 str
in
let fixed = Bytes.create count in
let _ =
String.fold_left
(fun count ch ->
if is_whitespace ch then count
else (
Bytes.set fixed count ch;
count + 1))
0 str
in
Bytes.unsafe_to_string fixed
let close input =
match Xmlm.input input with
| `El_end -> ()
| _ -> error input `Expected_end
let data input =
match Xmlm.input input with
| `Data data ->
close input;
data
| `El_end -> ""
| _ -> error input `Expected_data
let rec decode_tag input sink = function
| "array" ->
sink `Array_start;
let rec loop () =
skip_whitespace input;
match Xmlm.input input with
| `El_end -> sink `Array_end
| `El_start ((_, name), _) ->
decode_tag input sink name;
loop ()
| _ -> error input `Expected_start_or_end
in
loop ()
| "data" -> (
let data = data input in
match Base64.decode (lose_whitespace data) with
| Error _e -> error input (`Malformed_base64 data)
| Ok data -> sink (`Data data))
| "date" ->
let datetime =
let data = data input in
try ISO8601.Permissive.datetime_tz ~reqtime:false data
with Failure _ -> error input (`Malformed_date data)
in
sink (`Date datetime)
| "dict" ->
sink `Dict_start;
let rec loop () =
skip_whitespace input;
match Xmlm.input input with
| `El_end -> sink `Dict_end
| `El_start ((_, "key"), _) -> (
sink (`Key (data input));
skip_whitespace input;
match Xmlm.input input with
| `El_start ((_, name), _) ->
decode_tag input sink name;
loop ()
| _ -> error input `Expected_start)
| `El_start ((_, _), _) -> error input (`Expected_tag "key")
| _ -> error input `Expected_start_or_end
in
loop ()
| "false" ->
close input;
sink `False
| "integer" -> (
let data = data input in
match int_of_string_opt data with
| None -> error input (`Malformed_int data)
| Some int -> sink (`Int int))
| "real" -> (
let data = data input in
match float_of_string_opt data with
| None -> error input (`Malformed_real data)
| Some float -> sink (`Real float))
| "string" -> sink (`String (data input))
| "true" ->
close input;
sink `True
| s -> error input (`Unknown_tag s)
let decode source sink =
let input = Xmlm.make_input (`Fun source) in
match Xmlm.input input with
| `Dtd _ -> (
match Xmlm.input input with
| `El_start ((_, "plist"), _) -> (
skip_whitespace input;
match Xmlm.input input with
| `El_start ((_, name), _) -> (
decode_tag input sink name;
skip_whitespace input;
match Xmlm.input input with
| `El_end -> sink `EOI
| _ -> error input `Expected_end)
| _ -> error input `Expected_start)
| _ -> error input (`Expected_tag "plist"))
| _ -> ()
let encode_token output = function
| `Array_start -> Xmlm.output output array_start_signal
| `Array_end -> Xmlm.output output `El_end
| `Data data ->
Xmlm.output output data_start_signal;
let data = Base64.encode_string data in
if data <> "" then Xmlm.output output (`Data data);
Xmlm.output output `El_end
| `Date (datetime, None) ->
Xmlm.output output date_start_signal;
Xmlm.output output (`Data (ISO8601.Permissive.string_of_datetime datetime));
Xmlm.output output `El_end
| `Date (datetime, Some tz) ->
Xmlm.output output date_start_signal;
Xmlm.output output
(`Data (ISO8601.Permissive.string_of_datetimezone (datetime, tz)));
Xmlm.output output `El_end
| `Dict_start -> Xmlm.output output dict_start_signal
| `Dict_end -> Xmlm.output output `El_end
| `False ->
Xmlm.output output false_start_signal;
Xmlm.output output `El_end
| `Int int ->
Xmlm.output output integer_start_signal;
Xmlm.output output (`Data (string_of_int int));
Xmlm.output output `El_end
| `Key key ->
Xmlm.output output key_start_signal;
if key <> "" then Xmlm.output output (`Data key);
Xmlm.output output `El_end
| `Real float ->
Xmlm.output output real_start_signal;
Xmlm.output output (`Data (string_of_float float));
Xmlm.output output `El_end
| `String data ->
Xmlm.output output string_start_signal;
if data <> "" then Xmlm.output output (`Data data);
Xmlm.output output `El_end
| `True ->
Xmlm.output output true_start_signal;
Xmlm.output output `El_end
let encode source sink =
let output = Xmlm.make_output (`Fun sink) in
Xmlm.output output dtd_signal;
Xmlm.output output (`El_start (("", "plist"), []));
let rec loop () =
match source () with
| `EOI -> ()
| #token as token ->
encode_token output token;
loop ()
in
loop ();
Xmlm.output output `El_end
let token_of_signal = function
| `Array_start -> Parser.ARRAY_START
| `Array_end -> Parser.ARRAY_END
| `Data str -> Parser.DATA str
| `Date date -> Parser.DATE date
| `Dict_start -> Parser.DICT_START
| `Dict_end -> Parser.DICT_END
| `False -> Parser.FALSE
| `Int int -> Parser.INT int
| `Key key -> Parser.KEY key
| `Real float -> Parser.REAL float
| `String str -> Parser.STRING str
| `True -> Parser.TRUE
| `EOI -> Parser.EOI
module I = Parser.MenhirInterpreter
let parse source =
let exception E of t in
let checkpoint = ref (Parser.Incremental.main Lexing.dummy_pos) in
let sink signal =
let rec loop = function
| I.InputNeeded _ as checkpoint' -> checkpoint := checkpoint'
| (I.Shifting _ | I.AboutToReduce _) as checkpoint ->
loop (I.resume checkpoint)
| I.HandlingError _ -> assert false
| I.Accepted v -> raise (E v)
| I.Rejected -> assert false
in
loop
(I.offer !checkpoint
(token_of_signal signal, Lexing.dummy_pos, Lexing.dummy_pos))
in
try
decode source sink;
assert false
with E v -> v
let from_channel in_channel = parse (fun () -> input_byte in_channel)
let from_string string =
let idx = ref 0 in
let source () =
let i = !idx in
if i >= String.length string then raise End_of_file
else (
idx := i + 1;
Char.code string.[i])
in
parse source
let rec tokens sink = function
| `Bool false -> sink `False
| `Bool true -> sink `True
| `Data data -> sink (`Data data)
| `Date date -> sink (`Date date)
| `Float float -> sink (`Real float)
| `Int int -> sink (`Int int)
| `String string -> sink (`String string)
| `Array elts ->
sink `Array_start;
List.iter (tokens sink) elts;
sink `Array_end
| `Dict kvs ->
sink `Dict_start;
List.iter
(fun (k, v) ->
sink (`Key k);
tokens sink v)
kvs;
sink `Dict_end
let print sink t =
let output = Xmlm.make_output (`Fun sink) in
Xmlm.output output dtd_signal;
Xmlm.output output plist_start_signal;
tokens (encode_token output) t;
Xmlm.output output `El_end
let to_buffer buffer = print (Buffer.add_uint8 buffer)
let to_channel out_channel = print (output_byte out_channel)
let to_string t =
let buffer = Buffer.create 512 in
to_buffer buffer t;
Buffer.contents buffer
| |
stake_storage.ml | module Selected_distribution_for_cycle = struct
module Cache_client = struct
type cached_value = (Signature.Public_key_hash.t * Tez_repr.t) list
let namespace = Cache_repr.create_namespace "stake_distribution"
let cache_index = 1
let value_of_identifier ctxt identifier =
let cycle = Cycle_repr.of_string_exn identifier in
Storage.Stake.Selected_distribution_for_cycle.get ctxt cycle
end
module Cache = (val Cache_repr.register_exn (module Cache_client))
let identifier_of_cycle cycle = Format.asprintf "%a" Cycle_repr.pp cycle
let init ctxt cycle stakes =
let id = identifier_of_cycle cycle in
Storage.Stake.Selected_distribution_for_cycle.init ctxt cycle stakes
>>=? fun ctxt ->
let size = 1 (* that's symbolic: 1 cycle = 1 entry *) in
Cache.update ctxt id (Some (stakes, size)) >>?= fun ctxt -> return ctxt
let get ctxt cycle =
let id = identifier_of_cycle cycle in
Cache.find ctxt id >>=? function
| None -> Storage.Stake.Selected_distribution_for_cycle.get ctxt cycle
| Some v -> return v
let remove_existing ctxt cycle =
let id = identifier_of_cycle cycle in
Cache.update ctxt id None >>?= fun ctxt ->
Storage.Stake.Selected_distribution_for_cycle.remove_existing ctxt cycle
end
let get_staking_balance = Storage.Stake.Staking_balance.get
let get_initialized_stake ctxt delegate =
Storage.Stake.Staking_balance.find ctxt delegate >>=? function
| Some staking_balance -> return (staking_balance, ctxt)
| None ->
Frozen_deposits_storage.init ctxt delegate >>=? fun ctxt ->
let balance = Tez_repr.zero in
Storage.Stake.Staking_balance.init ctxt delegate balance >>=? fun ctxt ->
return (balance, ctxt)
let remove_stake ctxt delegate amount =
get_initialized_stake ctxt delegate >>=? fun (staking_balance_before, ctxt) ->
Tez_repr.(staking_balance_before -? amount) >>?= fun staking_balance ->
Storage.Stake.Staking_balance.update ctxt delegate staking_balance
>>=? fun ctxt ->
let tokens_per_roll = Constants_storage.tokens_per_roll ctxt in
if Tez_repr.(staking_balance_before >= tokens_per_roll) then
Delegate_activation_storage.is_inactive ctxt delegate >>=? fun inactive ->
if (not inactive) && Tez_repr.(staking_balance < tokens_per_roll) then
Storage.Stake.Active_delegate_with_one_roll.remove ctxt delegate
>>= fun ctxt -> return ctxt
else return ctxt
else
(* The delegate was not in Stake.Active_delegate_with_one_roll,
either because it was inactive, or because it did not have a
roll, in which case it still does not have a roll. *)
return ctxt
let add_stake ctxt delegate amount =
get_initialized_stake ctxt delegate >>=? fun (staking_balance_before, ctxt) ->
Tez_repr.(amount +? staking_balance_before) >>?= fun staking_balance ->
Storage.Stake.Staking_balance.update ctxt delegate staking_balance
>>=? fun ctxt ->
let tokens_per_roll = Constants_storage.tokens_per_roll ctxt in
if Tez_repr.(staking_balance >= tokens_per_roll) then
Delegate_activation_storage.is_inactive ctxt delegate >>=? fun inactive ->
if inactive || Tez_repr.(staking_balance_before >= tokens_per_roll) then
return ctxt
else
Storage.Stake.Active_delegate_with_one_roll.add ctxt delegate ()
>>= fun ctxt -> return ctxt
else
(* The delegate was not in Stake.Active_delegate_with_one_roll,
because it did not have a roll (as otherwise it would have a
roll now). *)
return ctxt
let deactivate_only_call_from_delegate_storage ctxt delegate =
Storage.Stake.Active_delegate_with_one_roll.remove ctxt delegate
let activate_only_call_from_delegate_storage ctxt delegate =
get_initialized_stake ctxt delegate >>=? fun (staking_balance, ctxt) ->
let tokens_per_roll = Constants_storage.tokens_per_roll ctxt in
if Tez_repr.(staking_balance >= tokens_per_roll) then
Storage.Stake.Active_delegate_with_one_roll.add ctxt delegate ()
>>= fun ctxt -> return ctxt
else return ctxt
let snapshot ctxt =
Storage.Stake.Last_snapshot.get ctxt >>=? fun index ->
Storage.Stake.Last_snapshot.update ctxt (index + 1) >>=? fun ctxt ->
Storage.Stake.Staking_balance.snapshot ctxt index >>=? fun ctxt ->
Storage.Stake.Active_delegate_with_one_roll.snapshot ctxt index
let max_snapshot_index = Storage.Stake.Last_snapshot.get
let set_selected_distribution_for_cycle ctxt cycle stakes total_stake =
let stakes = List.sort (fun (_, x) (_, y) -> Tez_repr.compare y x) stakes in
Selected_distribution_for_cycle.init ctxt cycle stakes >>=? fun ctxt ->
Storage.Total_active_stake.add ctxt cycle total_stake >>= fun ctxt ->
(* cleanup snapshots *)
Storage.Stake.Staking_balance.Snapshot.clear ctxt >>= fun ctxt ->
Storage.Stake.Active_delegate_with_one_roll.Snapshot.clear ctxt
>>= fun ctxt -> Storage.Stake.Last_snapshot.update ctxt 0
let clear_cycle ctxt cycle =
Storage.Total_active_stake.remove_existing ctxt cycle >>=? fun ctxt ->
Selected_distribution_for_cycle.remove_existing ctxt cycle
let fold ctxt ~f ~order init =
Storage.Stake.Active_delegate_with_one_roll.fold
ctxt
~order
~init:(Ok init)
~f:(fun delegate () acc ->
acc >>?= fun acc ->
get_staking_balance ctxt delegate >>=? fun stake ->
f (delegate, stake) acc)
let fold_snapshot ctxt ~index ~f ~init =
Storage.Stake.Active_delegate_with_one_roll.fold_snapshot
ctxt
index
~order:`Sorted
~init
~f:(fun delegate () acc ->
Storage.Stake.Staking_balance.Snapshot.get ctxt (index, delegate)
>>=? fun stake -> f (delegate, stake) acc)
let clear_at_cycle_end ctxt ~new_cycle =
let max_slashing_period = Constants_storage.max_slashing_period ctxt in
match Cycle_repr.sub new_cycle max_slashing_period with
| None -> return ctxt
| Some cycle_to_clear -> clear_cycle ctxt cycle_to_clear
let get ctxt delegate =
Storage.Stake.Active_delegate_with_one_roll.mem ctxt delegate >>= function
| true -> get_staking_balance ctxt delegate
| false -> return Tez_repr.zero
let fold_on_active_delegates_with_rolls =
Storage.Stake.Active_delegate_with_one_roll.fold
let get_selected_distribution = Selected_distribution_for_cycle.get
let find_selected_distribution =
Storage.Stake.Selected_distribution_for_cycle.find
let prepare_stake_distribution ctxt =
let level = Level_storage.current ctxt in
Selected_distribution_for_cycle.get ctxt level.cycle >>=? fun stakes ->
let stake_distribution =
List.fold_left
(fun map (pkh, stake) -> Signature.Public_key_hash.Map.add pkh stake map)
Signature.Public_key_hash.Map.empty
stakes
in
return
(Raw_context.init_stake_distribution_for_current_cycle
ctxt
stake_distribution)
let get_total_active_stake = Storage.Total_active_stake.get
let remove_contract_stake ctxt contract amount =
Contract_delegate_storage.find ctxt contract >>=? function
| None -> return ctxt
| Some delegate -> remove_stake ctxt delegate amount
let add_contract_stake ctxt contract amount =
Contract_delegate_storage.find ctxt contract >>=? function
| None -> return ctxt
| Some delegate -> add_stake ctxt delegate amount
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2021 Nomadic Labs, <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
jmphash.mli | (** An implementation of "A Fast, Minimal Memory, Consistent Hash Algorithm" *)
(** [host ~hosts key] tells you on which host, between 0 and hosts-1, you should
store value indexed by [key].
*)
val host : hosts:int -> int64 -> int
(* Runtime is O(log n).
The key property of the result for a given key is that, when [hosts] goes
from [n] to [m], n < m, the probability of the result changing is (m-n)/m.
If you are storing data on different servers:
- this formula allows you to distribute data uniformly,
- when adding or removing boxes, a minimum amoun of data has to be
moved.
This is completely stateless, you will have to keep track separately of the
meaning associated to each host.
The algorithm is described in this paper:
A Fast, Minimal Memory, Consistent Hash Algorithm
John Lamping and Eric Veach
http://arxiv.org/abs/1406.2294
*)
| (** An implementation of "A Fast, Minimal Memory, Consistent Hash Algorithm" *)
|
dune_rpc_server.mli |
open Stdune
open Dune_rpc_private
module Poller : sig
type t
val to_dyn : t -> Dyn.t
val compare : t -> t -> Ordering.t
val name : t -> Procedures.Poll.Name.t
end
module Session : sig
module Id : Stdune.Id.S
(** Session representing a connected client with a custom state. *)
type 'a t
val id : _ t -> Id.t
(* [initialize session] returns the initialize request used to initialize this
session *)
val initialize : _ t -> Initialize.Request.t
(** [get session] returns the current session state. It is an error to access
the state after [on_terminate] finishes. *)
val get : 'a t -> 'a
(** [get session a] sets the curent state to [a].*)
val set : 'a t -> 'a -> unit
val active : _ t -> bool
(** [notification session n a] Send notification [a] defined by [n] to
[session] *)
val notification : _ t -> 'a Decl.Notification.witness -> 'a -> unit Fiber.t
val compare : 'a t -> 'a t -> Ordering.t
val request_close : 'a t -> unit Fiber.t
val to_dyn : ('a -> Dyn.t) -> 'a t -> Dyn.t
val has_poller : _ t -> Poller.t -> bool
(** A ['a Session.Stage1.t] represents a session prior to version negotiation.
Used during initialization. *)
module Stage1 : sig
type 'a t
val id : _ t -> Id.t
val initialize : _ t -> Initialize.Request.t
val get : 'a t -> 'a
val set : 'a t -> 'a -> unit
val active : _ t -> bool
val compare : 'a t -> 'a t -> Ordering.t
val request_close : 'a t -> unit Fiber.t
val to_dyn : ('a -> Dyn.t) -> 'a t -> Dyn.t
(** Register a callback to be called once version negotiation has concluded.
At most one callback can be set at once; calling this function multiple
times for the same session will override previous invocations.
The registered callback is guaranteed to be called at most once. *)
val register_upgrade_callback : _ t -> (Menu.t -> unit) -> unit
end
end
module Handler : sig
(** A handler defines everything necessary to serve a session. It contains
- A way to defined requests and notifications
- A hook for handling session initiation/termination *)
type 'a t
val create :
?on_terminate:('a Session.t -> unit Fiber.t)
(** Termination hook. It is guaranteed that the session state will not
modified after this function is called *)
-> on_init:('a Session.Stage1.t -> Initialize.Request.t -> 'a Fiber.t)
(** Initiation hook. It's guaranteed to be called before any
requests/notifications. It's job is to initialize the session
state. *)
-> version:int * int
(** version of the rpc. it's expected to support all earlier versions *)
-> unit
-> 'a t
(** [implement_request handler decl callback] Add a request to [handler] using
[callback] as the implementation and [decl] as the metadata *)
val implement_request :
's t -> ('a, 'b) Decl.request -> ('s Session.t -> 'a -> 'b Fiber.t) -> unit
(** [implement_notification handler decl callback] Add a notification to
[handler] using [callback] as the implementation and [decl] as the
metadata *)
val implement_notification :
's t -> 'a Decl.notification -> ('s Session.t -> 'a -> unit Fiber.t) -> unit
(** [declare_notification handler decl] Declares that this server may send
notifications according to metadata [decl]. *)
val declare_notification : 's t -> 'a Decl.notification -> unit
val implement_long_poll :
_ t
-> 'diff Procedures.Poll.t
-> 'state Fiber.Svar.t
-> equal:('state -> 'state -> bool)
-> diff:(last:'state option -> now:'state -> 'diff)
-> unit
module Private : sig
val implement_poll :
's t
-> 'a Procedures.Poll.t
-> on_poll:('s Session.t -> Poller.t -> 'a option Fiber.t)
-> on_cancel:('s Session.t -> Poller.t -> unit Fiber.t)
-> unit
end
end
type t
val make : 'a Handler.t -> t
(** Functor to create a server implementation *)
module Make (S : sig
type t
(* [write t x] writes the s-expression when [x] is [Some _], and closes the
session if [x = None] *)
val write : t -> Sexp.t list option -> unit Fiber.t
(* [read t] attempts to read from [t]. If an s-expression is read, it is
returned as [Some sexp], otherwise [None] is returned and the session is
closed. *)
val read : t -> Sexp.t option Fiber.t
end) : sig
(** [serve sessions handler] serve all [sessions] using [handler] *)
val serve : S.t Fiber.Stream.In.t -> Dune_stats.t option -> t -> unit Fiber.t
end
| |
RPC.ml | open Environment
open Error_monad
type error +=
| Cannot_construct_external_message
| Cannot_deserialize_external_message
let () =
register_error_kind
`Permanent
~id:"dac_cannot_construct_external_message"
~title:"External rollup message could not be constructed"
~description:"External rollup message could not be constructed"
~pp:(fun ppf () ->
Format.fprintf ppf "External rollup message could not be constructed")
Data_encoding.unit
(function Cannot_construct_external_message -> Some () | _ -> None)
(fun () -> Cannot_construct_external_message) ;
register_error_kind
`Permanent
~id:"dac_cannot_deserialize_rollup_external_message"
~title:"External rollup message could not be deserialized"
~description:"External rollup message could not be deserialized"
~pp:(fun ppf () ->
Format.fprintf ppf "External rollup message could not be deserialized")
Data_encoding.unit
(function Cannot_deserialize_external_message -> Some () | _ -> None)
(fun () -> Cannot_deserialize_external_message)
module Registration = struct
let register0_noctxt ~chunked s f dir =
RPC_directory.register ~chunked dir s (fun _rpc_ctxt q i -> f q i)
end
module DAC = struct
module Hash_storage = Dac_preimage_data_manager.Reveal_hash
let store_preimage_request_encoding =
Data_encoding.(
obj2
(req "payload" Data_encoding.(bytes Hex))
(req "pagination_scheme" Dac_pages_encoding.pagination_scheme_encoding))
(* A variant of [Sc_rollup_reveal_hash.encoding] that prefers hex
encoding over b58check encoding for JSON. *)
let root_hash_encoding =
let binary = Protocol.Sc_rollup_reveal_hash.encoding in
Data_encoding.(
splitted
~binary
~json:
(conv_with_guard
Protocol.Sc_rollup_reveal_hash.to_hex
(fun str ->
Result.of_option
~error:"Not a valid hash"
(Protocol.Sc_rollup_reveal_hash.of_hex str))
(string Plain)))
let store_preimage_response_encoding =
Data_encoding.(
obj2
(req "root_hash" root_hash_encoding)
(req "external_message" (bytes Hex)))
let external_message_query =
let open RPC_query in
query (fun hex_string -> hex_string)
|+ opt_field "external_message" RPC_arg.string (fun s -> s)
|> seal
module S = struct
let dac_store_preimage =
RPC_service.put_service
~description:"Split DAC reveal data"
~query:RPC_query.empty
~input:store_preimage_request_encoding
~output:store_preimage_response_encoding
RPC_path.(open_root / "dac" / "store_preimage")
(* DAC/FIXME: https://gitlab.com/tezos/tezos/-/issues/4263
remove this endpoint once end-to-end tests are in place. *)
let verify_external_message_signature =
RPC_service.get_service
~description:"Verify signature of an external message to inject in L1"
~query:external_message_query
~output:Data_encoding.bool
RPC_path.(open_root / "dac" / "verify_signature")
end
let handle_serialize_dac_store_preimage cctxt dac_sk_uris reveal_data_dir
(data, pagination_scheme) =
let open Lwt_result_syntax in
let open Dac_pages_encoding in
let for_each_page (hash, page_contents) =
Dac_manager.Reveal_hash.Storage.save_bytes
reveal_data_dir
hash
page_contents
in
let* root_hash =
match pagination_scheme with
| Merkle_tree_V0 ->
let size =
Protocol.Alpha_context.Constants.sc_rollup_message_size_limit
in
Merkle_tree.V0.serialize_payload
~max_page_size:size
data
~for_each_page
| Hash_chain_V0 -> Hash_chain.V0.serialize_payload ~for_each_page data
in
let* signature, witnesses =
Dac_manager.Reveal_hash.Signatures.sign_root_hash
cctxt
dac_sk_uris
root_hash
in
let*? external_message =
match
Dac_manager.Reveal_hash.External_message.make
root_hash
signature
witnesses
with
| Ok external_message -> Ok external_message
| Error _ -> Error_monad.error Cannot_construct_external_message
in
return (root_hash, external_message)
let handle_verify_external_message_signature public_keys_opt
encoded_l1_message =
let open Lwt_result_syntax in
let open Dac_manager.Reveal_hash in
let external_message =
let open Option_syntax in
let* encoded_l1_message = encoded_l1_message in
let* as_bytes = Hex.to_bytes @@ `Hex encoded_l1_message in
External_message.of_bytes as_bytes
in
match external_message with
| None -> tzfail @@ Cannot_deserialize_external_message
| Some (External_message.Dac_message {root_hash; signature; witnesses}) ->
Signatures.verify ~public_keys_opt root_hash signature witnesses
let register_serialize_dac_store_preimage cctxt dac_sk_uris reveal_data_dir =
Registration.register0_noctxt
~chunked:false
S.dac_store_preimage
(fun () input ->
handle_serialize_dac_store_preimage
cctxt
dac_sk_uris
reveal_data_dir
input)
let register_verify_external_message_signature public_keys_opt =
Registration.register0_noctxt
~chunked:false
S.verify_external_message_signature
(fun external_message () ->
handle_verify_external_message_signature
public_keys_opt
external_message)
let register reveal_data_dir cctxt dac_public_keys_opt dac_sk_uris =
(RPC_directory.empty : unit RPC_directory.t)
|> register_serialize_dac_store_preimage cctxt dac_sk_uris reveal_data_dir
|> register_verify_external_message_signature dac_public_keys_opt
end
let rpc_services ~reveal_data_dir cctxt dac_public_keys_opt dac_sk_uris
_threshold =
DAC.register reveal_data_dir cctxt dac_public_keys_opt dac_sk_uris
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2022 Trili Tech <contact@trili.tech> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
logger.mli |
(** Log module
*
* 1. Provide functions to log arbitrary messages, filtered according to a
* section and a verbosity level.
*
* 2. Allow to setup a destination for these log messages.
*
**)
val log
: section:string -> title:string -> ('b, unit, string, unit) format4 -> 'b
val fmt : unit -> (Format.formatter -> unit) -> string
val json : unit -> (unit -> Std.json) -> string
val exn : unit -> exn -> string
val log_flush : unit -> unit
type notification = {
section: string;
msg: string;
}
val notify : section:string -> ('b, unit, string, unit) format4 -> 'b
val with_notifications : notification list ref -> (unit -> 'a) -> 'a
val with_log_file : string option -> ?sections:string list -> (unit -> 'a) -> 'a
type 'a printf = title:string -> ('a, unit, string, unit) format4 -> 'a
type logger = { log : 'a. 'a printf }
val for_section : string -> logger
| (* {{{ COPYING *(
This file is part of Merlin, an helper for ocaml editors
Copyright (C) 2013 - 2015 Frédéric Bour <frederic.bour(_)lakaban.net>
Thomas Refis <refis.thomas(_)gmail.com>
Simon Castellan <simon.castellan(_)iuwt.fr>
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.
)* }}} *) |
legacy_test_prevalidator_pending_operations.ml | (* FIXME: https://gitlab.com/tezos/tezos/-/issues/4113
This file is part of the test suite for the legacy mempool, which
is compatible with Kathmandu and therefore usable on Mainnet.
This file should be removed once Lima has been activated on Mainnet.
When you modify this file, consider whether you should also change
the ones that test the more recent mempool for Lima and newer
protocols. *)
(** Testing
-------
Component: Shell (Legacy prevalidator pending operations)
Invocation: dune exec src/lib_shell/test/legacy_test_prevalidator_pending_operations.exe
Subject: Unit tests the Prevalidator pending operations APIs
*)
open Qcheck2_helpers
module Prevalidation = Legacy_prevalidation
module Pending_ops = Legacy_prevalidator_pending_operations
module Generators = Legacy_generators
module CompareListQ = Compare.List (Q)
let pending_of_list =
List.fold_left
(fun pendings (op, priority) ->
if
Operation_hash.Set.mem
(Prevalidation.Internal_for_tests.hash_of op)
(Pending_ops.hashes pendings)
then (* no duplicate hashes *)
pendings
else Pending_ops.add op priority pendings)
Pending_ops.empty
(* 1. Test iterators ordering *)
let test_iterators_ordering ~name ~iterator return_value =
let open QCheck2 in
Test.make
~name:
(Format.sprintf
"Ensure that %s returns operations in their priority ordering"
name)
(Gen.small_list (Generators.operation_with_hash_and_priority_gen ()))
@@ fun ops ->
let previous_priority = ref `High in
let previous_prio_ok ~priority ~previous_priority =
match (previous_priority, priority) with
| `High, `High -> true
| (`High | `Medium), `Medium -> true
| (`High | `Medium), `Low _ -> true
| `Low q_prev, `Low q_new -> CompareListQ.(q_new <= q_prev)
| _, _ -> false
in
iterator
(fun priority _hash _op () ->
(* Here, we check the priority ordering in the iterators of
prevalidator_pending_operations module : if the current considered
priority is `High, it should be true that the previously seen is also
`High. *)
if not @@ previous_prio_ok ~priority ~previous_priority:!previous_priority
then
QCheck.Test.fail_reportf
"Pending operations are not ordered by priority" ;
previous_priority := priority ;
return_value)
(pending_of_list ops)
()
|> fun _ -> true
let test_iter_ordering =
test_iterators_ordering
~name:"iter"
~iterator:(fun f ops _acc -> Pending_ops.iter (fun p h o -> f p h o ()) ops)
()
let test_fold_ordering =
test_iterators_ordering ~name:"fold" ~iterator:Pending_ops.fold ()
let test_fold_es_ordering =
test_iterators_ordering
~name:"fold_es"
~iterator:Pending_ops.fold_es
Lwt_result_syntax.return_unit
(* 2. Test partial iteration with fold_es *)
let test_partial_fold_es =
let open QCheck2 in
Test.make
~name:"Test cardinal after partial iteration with fold_es"
(Gen.pair
(Gen.small_list (Generators.operation_with_hash_and_priority_gen ()))
Gen.small_nat)
@@ fun (ops, to_process) ->
let pending = pending_of_list ops in
let card0 = Pending_ops.cardinal pending in
Lwt_main.run
@@ Pending_ops.fold_es
(fun _priority hash _op (remaining_to_process, acc) ->
assert (remaining_to_process >= 0) ;
if remaining_to_process = 0 then Lwt.return_error acc
else
Lwt.return_ok (remaining_to_process - 1, Pending_ops.remove hash acc))
pending
(to_process, pending)
|> function
| Ok (remaining_to_process, pending) ->
(* [Ok] means we have reached the end of the collection before exhausting
the limit of iterations: the remaining collection is empty && we spent
as many iterations as there were elements in the original collection. *)
let card1 = Pending_ops.cardinal pending in
qcheck_eq' ~pp:Format.pp_print_int ~expected:0 ~actual:card1 ()
&& qcheck_eq'
~pp:Format.pp_print_int
~expected:card0
~actual:(to_process - remaining_to_process)
()
| Error pending ->
(* [Error] means we have reached the limit of the number of iterations:
the number of removed elements is exactly the number of iterations &&
there are still elements in the resulting collection. *)
let card1 = Pending_ops.cardinal pending in
qcheck_eq'
~pp:Format.pp_print_int
~expected:to_process
~actual:(card0 - card1)
()
&& qcheck_neq ~pp:Format.pp_print_int card1 0
let () =
let mk_tests label tests = (label, qcheck_wrap tests) in
Alcotest.run
"Prevalidator_pending_operations"
[
mk_tests "iter ordering" [test_iter_ordering];
mk_tests "fold ordering" [test_fold_ordering];
mk_tests "fold_es ordering" [test_fold_es_ordering];
mk_tests "partial fold_es" [test_partial_fold_es];
]
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2022 Nomadic Labs. <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|
type.ml |
open Catala_utils
open Definitions
type t = typ
let equal_tlit l1 l2 = l1 = l2
let compare_tlit l1 l2 = Stdlib.compare l1 l2
let rec equal ty1 ty2 =
match Marked.unmark ty1, Marked.unmark ty2 with
| TLit l1, TLit l2 -> equal_tlit l1 l2
| TTuple tys1, TTuple tys2 -> equal_list tys1 tys2
| TStruct n1, TStruct n2 -> StructName.equal n1 n2
| TEnum n1, TEnum n2 -> EnumName.equal n1 n2
| TOption t1, TOption t2 -> equal t1 t2
| TArrow (t1, t1'), TArrow (t2, t2') -> equal_list t1 t2 && equal t1' t2'
| TArray t1, TArray t2 -> equal t1 t2
| TAny, TAny -> true
| ( ( TLit _ | TTuple _ | TStruct _ | TEnum _ | TOption _ | TArrow _
| TArray _ | TAny ),
_ ) ->
false
and equal_list tys1 tys2 =
try List.for_all2 equal tys1 tys2 with Invalid_argument _ -> false
(* Similar to [equal], but allows TAny holes *)
let rec unifiable ty1 ty2 =
match Marked.unmark ty1, Marked.unmark ty2 with
| TAny, _ | _, TAny -> true
| TLit l1, TLit l2 -> equal_tlit l1 l2
| TTuple tys1, TTuple tys2 -> unifiable_list tys1 tys2
| TStruct n1, TStruct n2 -> StructName.equal n1 n2
| TEnum n1, TEnum n2 -> EnumName.equal n1 n2
| TOption t1, TOption t2 -> unifiable t1 t2
| TArrow (t1, t1'), TArrow (t2, t2') ->
unifiable_list t1 t2 && unifiable t1' t2'
| TArray t1, TArray t2 -> unifiable t1 t2
| ( (TLit _ | TTuple _ | TStruct _ | TEnum _ | TOption _ | TArrow _ | TArray _),
_ ) ->
false
and unifiable_list tys1 tys2 =
try List.for_all2 unifiable tys1 tys2 with Invalid_argument _ -> false
let rec compare ty1 ty2 =
match Marked.unmark ty1, Marked.unmark ty2 with
| TLit l1, TLit l2 -> compare_tlit l1 l2
| TTuple tys1, TTuple tys2 -> List.compare compare tys1 tys2
| TStruct n1, TStruct n2 -> StructName.compare n1 n2
| TEnum en1, TEnum en2 -> EnumName.compare en1 en2
| TOption t1, TOption t2 -> compare t1 t2
| TArrow (a1, b1), TArrow (a2, b2) -> (
match List.compare compare a1 a2 with 0 -> compare b1 b2 | n -> n)
| TArray t1, TArray t2 -> compare t1 t2
| TAny, TAny -> 0
| TLit _, _ -> -1
| _, TLit _ -> 1
| TTuple _, _ -> -1
| _, TTuple _ -> 1
| TStruct _, _ -> -1
| _, TStruct _ -> 1
| TEnum _, _ -> -1
| _, TEnum _ -> 1
| TOption _, _ -> -1
| _, TOption _ -> 1
| TArrow _, _ -> -1
| _, TArrow _ -> 1
| TArray _, _ -> -1
| _, TArray _ -> 1
let rec arrow_return = function TArrow (_, b), _ -> arrow_return b | t -> t
| (* This file is part of the Catala compiler, a specification language for tax
and social benefits computation rules. Copyright (C) 2020 Inria, contributor:
Louis Gesbert <louis.gesbert@inria.fr>
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License. *) |
main.ml |
open Cmdliner
open PyreAst
let read_file_content = function
| "-" -> Stdio.In_channel.(input_all stdin) |> Result.ok
| filename ->
(try Stdio.In_channel.(read_all filename) |> Result.ok with
| Sys_error message -> Result.error message)
;;
let parse ~f content =
Parser.with_context (fun context ->
f ~context content
|> Result.map_error
(fun { Parser.Error.message; line; column; end_line; end_column } ->
Format.sprintf
"Parse error at line %d, column %d to line %d, column %d: %s"
line
column
end_line
end_column
message))
;;
let handle_result ~f = function
| Result.Ok result -> f result
| Result.Error message -> Format.eprintf "%s\n" message
;;
let parse_module enable_type_comment filename =
let open Opine.Unparse.State in
let result =
let open Base.Result in
read_file_content filename
>>= fun content ->
parse content ~f:(fun ~context content ->
Parser.Concrete.parse_module ~context ~enable_type_comment content)
in
handle_result result ~f:(fun ast ->
(* let s = Transformations.Stats.py_module Transformations.Stats.State.default ast in *)
(* let ast = Transformations.Envise.py_module s ast in *)
(* Format.printf "%a\n" Sexplib.Sexp.pp_hum (Concrete.Module.sexp_of_t ast); *)
(* Format.printf *)
(* "Methods count:%a\n" *)
(* Sexplib.Sexp.pp_hum *)
(* (Transformations.Stats.State.sexp_of_t s); *)
let src =
Buffer.contents
(Opine.Unparse.py_module (Opine.Unparse.State.default ()) ast).source
in
(* Stdio.Out_channel.write_all "pyre.txt" ~data:src; *)
Format.printf "%s\n" src)
;;
let parse_expression filename =
let result =
let open Base.Result in
read_file_content filename
>>= fun content ->
parse content ~f:(fun ~context content ->
Parser.Concrete.parse_expression ~context content)
in
handle_result result ~f:(fun ast ->
(* Format.printf "%a\n" Sexplib.Sexp.pp_hum (Concrete.Expression.sexp_of_t ast); *)
Format.printf
"%s\n"
(Buffer.contents (Opine.Unparse.expr (Opine.Unparse.State.default ()) ast).source))
;;
let help_sections =
[ `S Manpage.s_common_options
; `P "These options are common to all commands."
; `S "MORE HELP"
; `P "Use `$(mname) $(i,COMMAND) --help' for help on a single command."
; `Noblank
; `S Manpage.s_bugs
; `P "Check bug reports at https://github.com/grievejia/pyre-ast/issues."
]
;;
let filename_arg =
let doc = "File name to be parsed. If the name is '-', read from stdin." in
Arg.(required & pos 0 (some string) None & info [] ~docv:"FILE_NAME" ~doc)
;;
let type_comment_arg =
let doc = "Whether to parse type comments or not" in
Arg.(value & flag & info [ "c"; "enable-type-comment" ] ~doc)
;;
let parse_expression_cmd =
let doc = "Parse the given input file as a Python expression." in
let man =
[ `S Manpage.s_description
; `P
"Read the given input file and parse it as a Python expression. Print the AST as \
an s-expression to stdout"
; `Blocks help_sections
]
in
let info = Cmd.info "expression" ~doc ~man in
Cmd.v info Term.(const parse_expression $ filename_arg)
;;
let parse_module_cmd =
let doc = "Parse the given input file as a Python module." in
let man =
[ `S Manpage.s_description
; `P
"Read the given input file and parse it as a Python module. Print the AST as an \
s-expression to stdout"
; `Blocks help_sections
]
in
let info = Cmd.info "module" ~doc ~man in
Cmd.v info Term.(const parse_module $ type_comment_arg $ filename_arg)
;;
let main_cmd =
let doc = "A Python parser based on `pyre-ast` for idiom-ml" in
let sdocs = Manpage.s_common_options in
let info = Cmd.info "opine-parse" ~version:"dev" ~doc ~sdocs ~man:help_sections in
let default = Term.(ret (const (`Help (`Pager, None)))) in
Cmd.group info ~default [ parse_expression_cmd; parse_module_cmd ]
;;
let () = Stdlib.exit (Cmd.eval main_cmd)
| |
template.ml |
let test_email_rendering_simple () =
let data = [ "foo", "bar" ] in
let actual, _ = Sihl_email.Template.render data "{foo}" None in
Alcotest.(check string) "Renders template" "bar" actual;
let data = [ "foo", "hey"; "bar", "ho" ] in
let actual, _ = Sihl_email.Template.render data "{foo} {bar}" None in
Alcotest.(check string) "Renders template" "hey ho" actual
;;
let test_email_rendering_complex () =
let data = [ "foo", "hey"; "bar", "ho" ] in
let actual, _ = Sihl_email.Template.render data "{foo} {bar}{foo}" None in
Alcotest.(check string) "Renders template" "hey hohey" actual
;;
let suite =
Alcotest.
[ ( "email"
, [ test_case "render simple" `Quick test_email_rendering_simple
; test_case "render complex" `Quick test_email_rendering_complex
] )
]
;;
let () =
Unix.putenv "SIHL_ENV" "test";
Alcotest.run "template" suite
;;
| |
test_bls12_381_projective.ml |
open Mec.Curve
module G1ValueGeneration =
Utils.PBT.MakeValueGeneration (BLS12_381.G1.Projective)
module G1Equality = Utils.PBT.MakeEquality (BLS12_381.G1.Projective)
module G1ECProperties = Utils.PBT.MakeECProperties (BLS12_381.G1.Projective)
let () =
let open Alcotest in
run
~verbose:true
"BLS12-381 G1 projective form"
[ G1ValueGeneration.get_tests ();
G1Equality.get_tests ();
G1ECProperties.get_tests () ]
| |
test_sc_rollup_inbox.ml | (** Testing
-------
Component: Protocol (smart contract rollup inbox)
Invocation: dune exec src/proto_alpha/lib_protocol/test/unit/main.exe \
-- test "^\[Unit\] sc rollup inbox$"
Subject: These unit tests check the off-line inbox implementation for
smart contract rollups
*)
open Protocol
open Sc_rollup_inbox_repr
exception Sc_rollup_inbox_test_error of string
let err x = Exn (Sc_rollup_inbox_test_error x)
let rollup = Sc_rollup_repr.Address.hash_string [""]
let level =
Raw_level_repr.of_int32 0l |> function Ok x -> x | _ -> assert false
let create_context () =
Context.init1 () >>=? fun (block, _contract) -> return block.context
let test_empty () =
let inbox = empty rollup level in
fail_unless
Z.(equal (number_of_available_messages inbox) zero)
(err "An empty inbox should have no available message.")
let setup_inbox_with_messages list_of_payloads f =
create_context () >>=? fun ctxt ->
let empty_messages = Environment.Context.Tree.empty ctxt in
let inbox = empty rollup level in
let history = history_at_genesis ~bound:10000L in
let rec aux level history inbox inboxes messages = function
| [] -> return (messages, history, inbox, inboxes)
| payloads :: ps ->
add_messages history inbox level payloads messages
>>=? fun (messages, history, inbox') ->
let level = Raw_level_repr.succ level in
aux level history inbox' (inbox :: inboxes) messages ps
in
aux level history inbox [] empty_messages list_of_payloads
>|= Environment.wrap_tzresult
>>=? fun (messages, history, inbox, inboxes) ->
f messages history inbox inboxes
let test_add_messages payloads =
let nb_payloads = List.length payloads in
setup_inbox_with_messages [payloads]
@@ fun _messages _history inbox _inboxes ->
fail_unless
Z.(equal (number_of_available_messages inbox) (of_int nb_payloads))
(err "Invalid number of available messages.")
let test_consume_messages (payloads, nb_consumed_messages) =
let nb_payloads = List.length payloads in
setup_inbox_with_messages [payloads]
@@ fun _messages _history inbox _inboxes ->
consume_n_messages nb_consumed_messages inbox |> Environment.wrap_tzresult
>>?= function
| Some inbox ->
let available_messages = nb_payloads - nb_consumed_messages in
fail_unless
Z.(
equal (number_of_available_messages inbox) (of_int available_messages))
(err "Invalid number of available messages.")
| None ->
fail_unless
(nb_consumed_messages > nb_payloads)
(err
"Message consumption fails only when trying to consume more than \
the number of available messages.")
let check_payload message payload =
Environment.Context.Tree.find message ["payload"] >>= function
| None -> fail (err "No payload in message")
| Some payload' ->
let payload' = Bytes.to_string payload' in
fail_unless
(payload = payload')
(err (Printf.sprintf "Expected payload %s, got %s" payload payload'))
let test_get_message payloads =
setup_inbox_with_messages [payloads]
@@ fun messages _history _inbox _inboxes ->
List.iteri_es
(fun i payload ->
get_message messages (Z.of_int i) >>= function
| Some message -> check_payload message payload
| None -> fail (err (Printf.sprintf "No message number %d in messages" i)))
payloads
let test_get_message_payload payloads =
setup_inbox_with_messages [payloads]
@@ fun messages _history _inbox _inboxes ->
List.iteri_es
(fun i payload ->
get_message_payload messages (Z.of_int i) >>= function
| Some payload' ->
fail_unless
(String.equal payload' payload)
(err (Printf.sprintf "Expected %s, got %s" payload payload'))
| None ->
fail
(err (Printf.sprintf "No message payload number %d in messages" i)))
payloads
let test_inclusion_proof_production (list_of_payloads, n) =
setup_inbox_with_messages list_of_payloads
@@ fun _messages history _inbox inboxes ->
let inbox = Stdlib.List.hd inboxes in
let old_inbox = Stdlib.List.nth inboxes n in
produce_inclusion_proof history old_inbox inbox |> function
| None ->
fail
@@ err
"It should be possible to produce an inclusion proof between two \
versions of the same inbox."
| Some proof ->
fail_unless
(verify_inclusion_proof proof old_inbox inbox)
(err "The produced inclusion proof is invalid.")
let test_inclusion_proof_verification (list_of_payloads, n) =
setup_inbox_with_messages list_of_payloads
@@ fun _messages history _inbox inboxes ->
let inbox = Stdlib.List.hd inboxes in
let old_inbox = Stdlib.List.nth inboxes n in
produce_inclusion_proof history old_inbox inbox |> function
| None ->
fail
@@ err
"It should be possible to produce an inclusion proof between two \
versions of the same inbox."
| Some proof ->
let old_inbox' = Stdlib.List.nth inboxes (Random.int (1 + n)) in
fail_unless
(equal old_inbox old_inbox'
|| not (verify_inclusion_proof proof old_inbox' inbox))
(err
"Verification should rule out a valid proof which is not about the \
given inboxes.")
let tests =
[
Tztest.tztest "Empty inbox" `Quick test_empty;
Tztest.tztest_qcheck
~name:"Added messages are available."
QCheck.(list string)
test_add_messages;
Tztest.tztest_qcheck
~name:"Get message."
QCheck.(list string)
test_get_message;
Tztest.tztest_qcheck
~name:"Get message payload."
QCheck.(list string)
test_get_message_payload;
Tztest.tztest_qcheck
~name:"Consume only available messages."
QCheck.(
make
Gen.(
let* l = list_size small_int string in
let* n = 0 -- ((List.length l * 2) + 1) in
return (l, n)))
test_consume_messages;
]
@
let gen_inclusion_proof_inputs =
QCheck.(
make
Gen.(
let small = 2 -- 10 in
let* a = list_size small string in
let* b = list_size small string in
let* l = list_size small (list_size small string) in
let l = a :: b :: l in
let* n = 0 -- (List.length l - 2) in
return (l, n)))
in
[
Tztest.tztest_qcheck
~count:10
~name:"Produce inclusion proof between two related inboxes."
gen_inclusion_proof_inputs
test_inclusion_proof_production;
Tztest.tztest_qcheck
~count:10
~name:"Verify inclusion proofs."
gen_inclusion_proof_inputs
test_inclusion_proof_verification;
]
| (*****************************************************************************)
(* *)
(* Open Source License *)
(* Copyright (c) 2022 Nomadic Labs, <contact@nomadic-labs.com> *)
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
(* and/or sell copies of the Software, and to permit persons to whom the *)
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
|