filename
stringlengths
3
67
data
stringlengths
0
58.3M
license
stringlengths
0
19.5k
extBytes.ml
#if OCAML >= 402 || defined WITH_BYTES module Bytes = Bytes #else module Bytes = struct include String let empty = "" let of_string = copy let to_string = copy let sub_string = sub let blit_string = blit let unsafe_to_string : t -> string = fun s -> s let unsafe_of_string : string -> t = fun s -> s end #endif
Neural_network.ml
let () = Wrap_utils.init ();; let __wrap_namespace = Py.import "sklearn.neural_network" let get_py name = Py.Module.get __wrap_namespace name module BernoulliRBM = struct type tag = [`BernoulliRBM] type t = [`BaseEstimator | `BernoulliRBM | `Object | `TransformerMixin] Obj.t let of_pyobject x = ((Obj.of_pyobject x) : t) let to_pyobject x = Obj.to_pyobject x let as_transformer x = (x :> [`TransformerMixin] Obj.t) let as_estimator x = (x :> [`BaseEstimator] Obj.t) let create ?n_components ?learning_rate ?batch_size ?n_iter ?verbose ?random_state () = Py.Module.get_function_with_keywords __wrap_namespace "BernoulliRBM" [||] (Wrap_utils.keyword_args [("n_components", Wrap_utils.Option.map n_components Py.Int.of_int); ("learning_rate", Wrap_utils.Option.map learning_rate Py.Float.of_float); ("batch_size", Wrap_utils.Option.map batch_size Py.Int.of_int); ("n_iter", Wrap_utils.Option.map n_iter Py.Int.of_int); ("verbose", Wrap_utils.Option.map verbose Py.Int.of_int); ("random_state", Wrap_utils.Option.map random_state Py.Int.of_int)]) |> of_pyobject let fit ?y ~x self = Py.Module.get_function_with_keywords (to_pyobject self) "fit" [||] (Wrap_utils.keyword_args [("y", y); ("X", Some(x |> Np.Obj.to_pyobject))]) |> of_pyobject let fit_transform ?y ?fit_params ~x self = Py.Module.get_function_with_keywords (to_pyobject self) "fit_transform" [||] (List.rev_append (Wrap_utils.keyword_args [("y", Wrap_utils.Option.map y Np.Obj.to_pyobject); ("X", Some(x |> Np.Obj.to_pyobject))]) (match fit_params with None -> [] | Some x -> x)) |> (fun py -> (Np.Obj.of_pyobject py : [>`ArrayLike] Np.Obj.t)) let get_params ?deep self = Py.Module.get_function_with_keywords (to_pyobject self) "get_params" [||] (Wrap_utils.keyword_args [("deep", Wrap_utils.Option.map deep Py.Bool.of_bool)]) |> Dict.of_pyobject let gibbs ~v self = Py.Module.get_function_with_keywords (to_pyobject self) "gibbs" [||] (Wrap_utils.keyword_args [("v", Some(v |> Np.Obj.to_pyobject))]) |> (fun py -> (Np.Obj.of_pyobject py : [>`ArrayLike] Np.Obj.t)) let partial_fit ?y ~x self = Py.Module.get_function_with_keywords (to_pyobject self) "partial_fit" [||] (Wrap_utils.keyword_args [("y", y); ("X", Some(x |> Np.Obj.to_pyobject))]) |> of_pyobject let score_samples ~x self = Py.Module.get_function_with_keywords (to_pyobject self) "score_samples" [||] (Wrap_utils.keyword_args [("X", Some(x |> Np.Obj.to_pyobject))]) |> (fun py -> (Np.Obj.of_pyobject py : [>`ArrayLike] Np.Obj.t)) let set_params ?params self = Py.Module.get_function_with_keywords (to_pyobject self) "set_params" [||] (match params with None -> [] | Some x -> x) |> of_pyobject let transform ~x self = Py.Module.get_function_with_keywords (to_pyobject self) "transform" [||] (Wrap_utils.keyword_args [("X", Some(x |> Np.Obj.to_pyobject))]) |> (fun py -> (Np.Obj.of_pyobject py : [>`ArrayLike] Np.Obj.t)) let intercept_hidden_opt self = match Py.Object.get_attr_string (to_pyobject self) "intercept_hidden_" with | None -> failwith "attribute intercept_hidden_ not found" | Some x -> if Py.is_none x then None else Some ((fun py -> (Np.Obj.of_pyobject py : [>`ArrayLike] Np.Obj.t)) x) let intercept_hidden_ self = match intercept_hidden_opt self with | None -> raise Not_found | Some x -> x let intercept_visible_opt self = match Py.Object.get_attr_string (to_pyobject self) "intercept_visible_" with | None -> failwith "attribute intercept_visible_ not found" | Some x -> if Py.is_none x then None else Some ((fun py -> (Np.Obj.of_pyobject py : [>`ArrayLike] Np.Obj.t)) x) let intercept_visible_ self = match intercept_visible_opt self with | None -> raise Not_found | Some x -> x let components_opt self = match Py.Object.get_attr_string (to_pyobject self) "components_" with | None -> failwith "attribute components_ not found" | Some x -> if Py.is_none x then None else Some ((fun py -> (Np.Obj.of_pyobject py : [>`ArrayLike] Np.Obj.t)) x) let components_ self = match components_opt self with | None -> raise Not_found | Some x -> x let h_samples_opt self = match Py.Object.get_attr_string (to_pyobject self) "h_samples_" with | None -> failwith "attribute h_samples_ not found" | Some x -> if Py.is_none x then None else Some ((fun py -> (Np.Obj.of_pyobject py : [>`ArrayLike] Np.Obj.t)) x) let h_samples_ self = match h_samples_opt self with | None -> raise Not_found | Some x -> x let to_string self = Py.Object.to_string (to_pyobject self) let show self = to_string self let pp formatter self = Format.fprintf formatter "%s" (show self) end module MLPClassifier = struct type tag = [`MLPClassifier] type t = [`BaseEstimator | `BaseMultilayerPerceptron | `ClassifierMixin | `MLPClassifier | `Object] Obj.t let of_pyobject x = ((Obj.of_pyobject x) : t) let to_pyobject x = Obj.to_pyobject x let as_classifier x = (x :> [`ClassifierMixin] Obj.t) let as_multilayer_perceptron x = (x :> [`BaseMultilayerPerceptron] Obj.t) let as_estimator x = (x :> [`BaseEstimator] Obj.t) let create ?hidden_layer_sizes ?activation ?solver ?alpha ?batch_size ?learning_rate ?learning_rate_init ?power_t ?max_iter ?shuffle ?random_state ?tol ?verbose ?warm_start ?momentum ?nesterovs_momentum ?early_stopping ?validation_fraction ?beta_1 ?beta_2 ?epsilon ?n_iter_no_change ?max_fun () = Py.Module.get_function_with_keywords __wrap_namespace "MLPClassifier" [||] (Wrap_utils.keyword_args [("hidden_layer_sizes", hidden_layer_sizes); ("activation", Wrap_utils.Option.map activation (function | `Identity -> Py.String.of_string "identity" | `Logistic -> Py.String.of_string "logistic" | `Tanh -> Py.String.of_string "tanh" | `Relu -> Py.String.of_string "relu" )); ("solver", Wrap_utils.Option.map solver (function | `Lbfgs -> Py.String.of_string "lbfgs" | `Sgd -> Py.String.of_string "sgd" | `Adam -> Py.String.of_string "adam" )); ("alpha", Wrap_utils.Option.map alpha Py.Float.of_float); ("batch_size", Wrap_utils.Option.map batch_size Py.Int.of_int); ("learning_rate", Wrap_utils.Option.map learning_rate (function | `Constant -> Py.String.of_string "constant" | `Invscaling -> Py.String.of_string "invscaling" | `Adaptive -> Py.String.of_string "adaptive" )); ("learning_rate_init", Wrap_utils.Option.map learning_rate_init Py.Float.of_float); ("power_t", Wrap_utils.Option.map power_t Py.Float.of_float); ("max_iter", Wrap_utils.Option.map max_iter Py.Int.of_int); ("shuffle", Wrap_utils.Option.map shuffle Py.Bool.of_bool); ("random_state", Wrap_utils.Option.map random_state Py.Int.of_int); ("tol", Wrap_utils.Option.map tol Py.Float.of_float); ("verbose", Wrap_utils.Option.map verbose Py.Int.of_int); ("warm_start", Wrap_utils.Option.map warm_start Py.Bool.of_bool); ("momentum", Wrap_utils.Option.map momentum Py.Float.of_float); ("nesterovs_momentum", Wrap_utils.Option.map nesterovs_momentum Py.Bool.of_bool); ("early_stopping", Wrap_utils.Option.map early_stopping Py.Bool.of_bool); ("validation_fraction", Wrap_utils.Option.map validation_fraction Py.Float.of_float); ("beta_1", Wrap_utils.Option.map beta_1 Py.Float.of_float); ("beta_2", Wrap_utils.Option.map beta_2 Py.Float.of_float); ("epsilon", Wrap_utils.Option.map epsilon Py.Float.of_float); ("n_iter_no_change", Wrap_utils.Option.map n_iter_no_change Py.Int.of_int); ("max_fun", Wrap_utils.Option.map max_fun Py.Int.of_int)]) |> of_pyobject let fit ~x ~y self = Py.Module.get_function_with_keywords (to_pyobject self) "fit" [||] (Wrap_utils.keyword_args [("X", Some(x |> Np.Obj.to_pyobject)); ("y", Some(y |> Np.Obj.to_pyobject))]) |> of_pyobject let get_params ?deep self = Py.Module.get_function_with_keywords (to_pyobject self) "get_params" [||] (Wrap_utils.keyword_args [("deep", Wrap_utils.Option.map deep Py.Bool.of_bool)]) |> Dict.of_pyobject let partial_fit ?classes ~x ~y self = Py.Module.get_function_with_keywords (to_pyobject self) "partial_fit" [||] (Wrap_utils.keyword_args [("classes", classes); ("X", Some(x )); ("y", Some(y ))]) |> of_pyobject let predict ~x self = Py.Module.get_function_with_keywords (to_pyobject self) "predict" [||] (Wrap_utils.keyword_args [("X", Some(x |> Np.Obj.to_pyobject))]) |> (fun py -> (Np.Obj.of_pyobject py : [>`ArrayLike] Np.Obj.t)) let predict_log_proba ~x self = Py.Module.get_function_with_keywords (to_pyobject self) "predict_log_proba" [||] (Wrap_utils.keyword_args [("X", Some(x |> Np.Obj.to_pyobject))]) |> (fun py -> (Np.Obj.of_pyobject py : [>`ArrayLike] Np.Obj.t)) let predict_proba ~x self = Py.Module.get_function_with_keywords (to_pyobject self) "predict_proba" [||] (Wrap_utils.keyword_args [("X", Some(x |> Np.Obj.to_pyobject))]) |> (fun py -> (Np.Obj.of_pyobject py : [>`ArrayLike] Np.Obj.t)) let score ?sample_weight ~x ~y self = Py.Module.get_function_with_keywords (to_pyobject self) "score" [||] (Wrap_utils.keyword_args [("sample_weight", Wrap_utils.Option.map sample_weight Np.Obj.to_pyobject); ("X", Some(x |> Np.Obj.to_pyobject)); ("y", Some(y |> Np.Obj.to_pyobject))]) |> Py.Float.to_float let set_params ?params self = Py.Module.get_function_with_keywords (to_pyobject self) "set_params" [||] (match params with None -> [] | Some x -> x) |> of_pyobject let classes_opt self = match Py.Object.get_attr_string (to_pyobject self) "classes_" with | None -> failwith "attribute classes_ not found" | Some x -> if Py.is_none x then None else Some ((fun py -> (Np.Obj.of_pyobject py : [>`ArrayLike] Np.Obj.t)) x) let classes_ self = match classes_opt self with | None -> raise Not_found | Some x -> x let loss_opt self = match Py.Object.get_attr_string (to_pyobject self) "loss_" with | None -> failwith "attribute loss_ not found" | Some x -> if Py.is_none x then None else Some (Py.Float.to_float x) let loss_ self = match loss_opt self with | None -> raise Not_found | Some x -> x let coefs_opt self = match Py.Object.get_attr_string (to_pyobject self) "coefs_" with | None -> failwith "attribute coefs_ not found" | Some x -> if Py.is_none x then None else Some (Wrap_utils.id x) let coefs_ self = match coefs_opt self with | None -> raise Not_found | Some x -> x let intercepts_opt self = match Py.Object.get_attr_string (to_pyobject self) "intercepts_" with | None -> failwith "attribute intercepts_ not found" | Some x -> if Py.is_none x then None else Some (Wrap_utils.id x) let intercepts_ self = match intercepts_opt self with | None -> raise Not_found | Some x -> x let n_iter_opt self = match Py.Object.get_attr_string (to_pyobject self) "n_iter_" with | None -> failwith "attribute n_iter_ not found" | Some x -> if Py.is_none x then None else Some (Py.Int.to_int x) let n_iter_ self = match n_iter_opt self with | None -> raise Not_found | Some x -> x let n_layers_opt self = match Py.Object.get_attr_string (to_pyobject self) "n_layers_" with | None -> failwith "attribute n_layers_ not found" | Some x -> if Py.is_none x then None else Some (Py.Int.to_int x) let n_layers_ self = match n_layers_opt self with | None -> raise Not_found | Some x -> x let n_outputs_opt self = match Py.Object.get_attr_string (to_pyobject self) "n_outputs_" with | None -> failwith "attribute n_outputs_ not found" | Some x -> if Py.is_none x then None else Some (Py.Int.to_int x) let n_outputs_ self = match n_outputs_opt self with | None -> raise Not_found | Some x -> x let out_activation_opt self = match Py.Object.get_attr_string (to_pyobject self) "out_activation_" with | None -> failwith "attribute out_activation_ not found" | Some x -> if Py.is_none x then None else Some (Py.String.to_string x) let out_activation_ self = match out_activation_opt self with | None -> raise Not_found | Some x -> x let to_string self = Py.Object.to_string (to_pyobject self) let show self = to_string self let pp formatter self = Format.fprintf formatter "%s" (show self) end module MLPRegressor = struct type tag = [`MLPRegressor] type t = [`BaseEstimator | `BaseMultilayerPerceptron | `MLPRegressor | `Object | `RegressorMixin] Obj.t let of_pyobject x = ((Obj.of_pyobject x) : t) let to_pyobject x = Obj.to_pyobject x let as_estimator x = (x :> [`BaseEstimator] Obj.t) let as_multilayer_perceptron x = (x :> [`BaseMultilayerPerceptron] Obj.t) let as_regressor x = (x :> [`RegressorMixin] Obj.t) let create ?hidden_layer_sizes ?activation ?solver ?alpha ?batch_size ?learning_rate ?learning_rate_init ?power_t ?max_iter ?shuffle ?random_state ?tol ?verbose ?warm_start ?momentum ?nesterovs_momentum ?early_stopping ?validation_fraction ?beta_1 ?beta_2 ?epsilon ?n_iter_no_change ?max_fun () = Py.Module.get_function_with_keywords __wrap_namespace "MLPRegressor" [||] (Wrap_utils.keyword_args [("hidden_layer_sizes", hidden_layer_sizes); ("activation", Wrap_utils.Option.map activation (function | `Identity -> Py.String.of_string "identity" | `Logistic -> Py.String.of_string "logistic" | `Tanh -> Py.String.of_string "tanh" | `Relu -> Py.String.of_string "relu" )); ("solver", Wrap_utils.Option.map solver (function | `Lbfgs -> Py.String.of_string "lbfgs" | `Sgd -> Py.String.of_string "sgd" | `Adam -> Py.String.of_string "adam" )); ("alpha", Wrap_utils.Option.map alpha Py.Float.of_float); ("batch_size", Wrap_utils.Option.map batch_size Py.Int.of_int); ("learning_rate", Wrap_utils.Option.map learning_rate (function | `Constant -> Py.String.of_string "constant" | `Invscaling -> Py.String.of_string "invscaling" | `Adaptive -> Py.String.of_string "adaptive" )); ("learning_rate_init", Wrap_utils.Option.map learning_rate_init Py.Float.of_float); ("power_t", Wrap_utils.Option.map power_t Py.Float.of_float); ("max_iter", Wrap_utils.Option.map max_iter Py.Int.of_int); ("shuffle", Wrap_utils.Option.map shuffle Py.Bool.of_bool); ("random_state", Wrap_utils.Option.map random_state Py.Int.of_int); ("tol", Wrap_utils.Option.map tol Py.Float.of_float); ("verbose", Wrap_utils.Option.map verbose Py.Int.of_int); ("warm_start", Wrap_utils.Option.map warm_start Py.Bool.of_bool); ("momentum", Wrap_utils.Option.map momentum Py.Float.of_float); ("nesterovs_momentum", Wrap_utils.Option.map nesterovs_momentum Py.Bool.of_bool); ("early_stopping", Wrap_utils.Option.map early_stopping Py.Bool.of_bool); ("validation_fraction", Wrap_utils.Option.map validation_fraction Py.Float.of_float); ("beta_1", Wrap_utils.Option.map beta_1 Py.Float.of_float); ("beta_2", Wrap_utils.Option.map beta_2 Py.Float.of_float); ("epsilon", Wrap_utils.Option.map epsilon Py.Float.of_float); ("n_iter_no_change", Wrap_utils.Option.map n_iter_no_change Py.Int.of_int); ("max_fun", Wrap_utils.Option.map max_fun Py.Int.of_int)]) |> of_pyobject let fit ~x ~y self = Py.Module.get_function_with_keywords (to_pyobject self) "fit" [||] (Wrap_utils.keyword_args [("X", Some(x |> Np.Obj.to_pyobject)); ("y", Some(y |> Np.Obj.to_pyobject))]) |> of_pyobject let get_params ?deep self = Py.Module.get_function_with_keywords (to_pyobject self) "get_params" [||] (Wrap_utils.keyword_args [("deep", Wrap_utils.Option.map deep Py.Bool.of_bool)]) |> Dict.of_pyobject let partial_fit ~x ~y self = Py.Module.get_function_with_keywords (to_pyobject self) "partial_fit" [||] (Wrap_utils.keyword_args [("X", Some(x )); ("y", Some(y ))]) |> of_pyobject let predict ~x self = Py.Module.get_function_with_keywords (to_pyobject self) "predict" [||] (Wrap_utils.keyword_args [("X", Some(x |> Np.Obj.to_pyobject))]) |> (fun py -> (Np.Obj.of_pyobject py : [>`ArrayLike] Np.Obj.t)) let score ?sample_weight ~x ~y self = Py.Module.get_function_with_keywords (to_pyobject self) "score" [||] (Wrap_utils.keyword_args [("sample_weight", Wrap_utils.Option.map sample_weight Np.Obj.to_pyobject); ("X", Some(x |> Np.Obj.to_pyobject)); ("y", Some(y |> Np.Obj.to_pyobject))]) |> Py.Float.to_float let set_params ?params self = Py.Module.get_function_with_keywords (to_pyobject self) "set_params" [||] (match params with None -> [] | Some x -> x) |> of_pyobject let loss_opt self = match Py.Object.get_attr_string (to_pyobject self) "loss_" with | None -> failwith "attribute loss_ not found" | Some x -> if Py.is_none x then None else Some (Py.Float.to_float x) let loss_ self = match loss_opt self with | None -> raise Not_found | Some x -> x let coefs_opt self = match Py.Object.get_attr_string (to_pyobject self) "coefs_" with | None -> failwith "attribute coefs_ not found" | Some x -> if Py.is_none x then None else Some (Wrap_utils.id x) let coefs_ self = match coefs_opt self with | None -> raise Not_found | Some x -> x let intercepts_opt self = match Py.Object.get_attr_string (to_pyobject self) "intercepts_" with | None -> failwith "attribute intercepts_ not found" | Some x -> if Py.is_none x then None else Some (Wrap_utils.id x) let intercepts_ self = match intercepts_opt self with | None -> raise Not_found | Some x -> x let n_iter_opt self = match Py.Object.get_attr_string (to_pyobject self) "n_iter_" with | None -> failwith "attribute n_iter_ not found" | Some x -> if Py.is_none x then None else Some (Py.Int.to_int x) let n_iter_ self = match n_iter_opt self with | None -> raise Not_found | Some x -> x let n_layers_opt self = match Py.Object.get_attr_string (to_pyobject self) "n_layers_" with | None -> failwith "attribute n_layers_ not found" | Some x -> if Py.is_none x then None else Some (Py.Int.to_int x) let n_layers_ self = match n_layers_opt self with | None -> raise Not_found | Some x -> x let n_outputs_opt self = match Py.Object.get_attr_string (to_pyobject self) "n_outputs_" with | None -> failwith "attribute n_outputs_ not found" | Some x -> if Py.is_none x then None else Some (Py.Int.to_int x) let n_outputs_ self = match n_outputs_opt self with | None -> raise Not_found | Some x -> x let out_activation_opt self = match Py.Object.get_attr_string (to_pyobject self) "out_activation_" with | None -> failwith "attribute out_activation_ not found" | Some x -> if Py.is_none x then None else Some (Py.String.to_string x) let out_activation_ self = match out_activation_opt self with | None -> raise Not_found | Some x -> x let to_string self = Py.Object.to_string (to_pyobject self) let show self = to_string self let pp formatter self = Format.fprintf formatter "%s" (show self) end
dune
(cram (deps (glob_files bin/*.exe)))
path_intf.ml
module type S = sig type t val hash : t -> int val to_string : t -> string val of_string : string -> t val parse_string_exn : loc:Loc0.t -> string -> t (** a directory is smaller than its descendants *) include Comparator.S with type t := t include Comparator.OPS with type t := t val to_dyn : t -> Dyn.t val extension : t -> string (** [set_extension path ~ext] replaces extension of [path] by [ext] *) val set_extension : t -> ext:string -> t (** [map_extension path ~f] replaces extension of [path] by [f extension]*) val map_extension : t -> f:(string -> string) -> t val split_extension : t -> t * string val basename : t -> string val basename_opt : t -> string option val extend_basename : t -> suffix:string -> t module Map : Map.S with type key = t module Set : sig include Set.S with type elt = t and type 'a map = 'a Map.t val to_dyn : t Dyn.builder val of_listing : dir:elt -> filenames:string list -> t end module Table : Hashtbl.S with type key = t val relative : ?error_loc:Loc0.t -> t -> string -> t val to_string_maybe_quoted : t -> string val is_descendant : t -> of_:t -> bool val is_root : t -> bool val parent_exn : t -> t val parent : t -> t option val unlink_no_err : t -> unit end (** [Unspecified.w] is a type-level placeholder of an unspecified path. (see [Local_gen] for how it's used) *) module Unspecified = struct type w end (** ['w Local_gen.t] is the type of local paths that live under ['w]. If [x : w Local_gen.t] and [w] is a type-level witness corresponding to a (real or hypothetical) filesystem location [base], then we think of [x] as referring to the location [to_string base ^/ to_string x]. *) module type Local_gen = sig type 'w t val hash : 'w t -> int (* it's not clear that these should be polymorphic over 'w, maybe they should additionally ask for an object that fixes 'w *) val to_string : 'w t -> string val of_string : string -> 'w t val parse_string_exn : loc:Loc0.t -> string -> 'w t (** a directory is smaller than its descendants *) val compare : 'w t -> 'w t -> Ordering.t val to_dyn : 'w t -> Dyn.t val extension : 'w t -> string (** [set_extension path ~ext] replaces extension of [path] by [ext] *) val set_extension : 'w t -> ext:string -> 'w t (** [map_extension path ~f] replaces extension of [path] by [f extension]*) val map_extension : 'W t -> f:(string -> string) -> 'W t val split_extension : 'w t -> 'w t * string val basename : 'w t -> string val extend_basename : 'w t -> suffix:string -> 'w t module Fix_root (Root : sig type w end) : sig module Map : Map.S with type key = Root.w t module Set : sig include Set.S with type elt = Root.w t and type 'a map = 'a Map.t val to_dyn : t Dyn.builder val of_listing : dir:elt -> filenames:string list -> t end module Table : Hashtbl.S with type key = Root.w t end val relative : ?error_loc:Loc0.t -> 'w t -> string -> 'w t val to_string_maybe_quoted : 'w t -> string val is_descendant : 'w t -> of_:'w t -> bool val is_root : 'w t -> bool val parent_exn : 'w t -> 'w t val parent : 'w t -> 'w t option val explode : 'w t -> string list val root : 'w t val append : 'w t -> Unspecified.w t -> 'w t val descendant : 'w t -> of_:'w t -> Unspecified.w t option val reach : 'w t -> from:'w t -> string val split_first_component : 'w t -> (string * Unspecified.w t) option module L : sig val relative : ?error_loc:Loc0.t -> 'w t -> string list -> 'w t val relative_result : 'w t -> string list -> ('w t, [ `Outside_the_workspace ]) Result.t end val unlink_no_err : 'w t -> unit end
from.c
void main() { if(x) goto lab1; else y(); lab1: ; while(x) goto lab2; lab2: ; for(i = 0; i < 5; i++) goto lab3; lab3: ; { int a; goto lab4; x++; y++; } lab4: ; }
testInfo.mli
(* Extract information from test, at the moment name + fname + hash *) (* Type of information *) module T : sig type t = { tname : string ; fname : string ; hash : string ; } val compare : t -> t -> int end (* Extract information out of parsed test *) module Make(A:ArchBase.S)(Pte:PteVal.S) : sig val zyva : Name.t -> A.pseudo MiscParser.t -> T.t end (* Parser an extract *) module Z : sig val from_file : string -> T.t end
(****************************************************************************) (* the diy toolsuite *) (* *) (* Jade Alglave, University College London, UK. *) (* Luc Maranget, INRIA Paris-Rocquencourt, France. *) (* *) (* Copyright 2016-present Institut National de Recherche en Informatique et *) (* en Automatique and the authors. All rights reserved. *) (* *) (* This software is governed by the CeCILL-B license under French law and *) (* abiding by the rules of distribution of free software. You can use, *) (* modify and/ or redistribute the software under the terms of the CeCILL-B *) (* license as circulated by CEA, CNRS and INRIA at the following URL *) (* "http://www.cecill.info". We also give a copy in LICENSE.txt. *) (****************************************************************************)
dune
(mdx (files README.md) (packages pkg))
doubly_linked_test.ml
open OUnit open Core open Poly module type S = sig val name : string module Elt : sig type 'a t val value : 'a t -> 'a val equal : 'a t -> 'a t -> bool val sexp_of_t : ('a -> Sexp.t) -> 'a t -> Sexp.t end type 'a t include Container.S1 with type 'a t := 'a t include Invariant.S1 with type 'a t := 'a t include Sexpable.S1 with type 'a t := 'a t val create : unit -> 'a t val of_list : 'a list -> 'a t val equal : 'a t -> 'a t -> bool val is_first : 'a t -> 'a Elt.t -> bool val is_last : 'a t -> 'a Elt.t -> bool val first_elt : 'a t -> 'a Elt.t option val last_elt : 'a t -> 'a Elt.t option val first : 'a t -> 'a option val last : 'a t -> 'a option val next : 'a t -> 'a Elt.t -> 'a Elt.t option val prev : 'a t -> 'a Elt.t -> 'a Elt.t option val insert_before : 'a t -> 'a Elt.t -> 'a -> 'a Elt.t val insert_after : 'a t -> 'a Elt.t -> 'a -> 'a Elt.t val insert_first : 'a t -> 'a -> 'a Elt.t val insert_last : 'a t -> 'a -> 'a Elt.t val remove : 'a t -> 'a Elt.t -> unit val remove_first : 'a t -> 'a option val remove_last : 'a t -> 'a option val find_elt : 'a t -> f:('a -> bool) -> 'a Elt.t option val clear : 'a t -> unit val copy : 'a t -> 'a t val transfer : src:'a t -> dst:'a t -> unit val filter_inplace : 'a t -> f:('a -> bool) -> unit end module Hero : S = struct let name = "hero" include Doubly_linked end module Foil : S = struct let name = "foil" type 'a t = { mutable elts : 'a elt list ; mutable num_readers : int } and 'a elt = { value : 'a ; mutable root : 'a t } module Elt = struct type 'a t = 'a elt let equal (t1 : _ t) t2 = phys_equal t1 t2 let value t = t.value let sexp_of_t sexp_of_a t = sexp_of_a t.value end let to_list t = List.map ~f:Elt.value t.elts let of_list xs = let t = { elts = []; num_readers = 0 } in t.elts <- List.map xs ~f:(fun x -> { value = x; root = t }); t ;; let length t = List.length (to_list t) let is_empty t = List.is_empty (to_list t) let to_array t = List.to_array (to_list t) let read_wrap t f = t.num_readers <- t.num_readers + 1; Exn.protect ~f ~finally:(fun () -> t.num_readers <- t.num_readers - 1) ;; let for_all t ~f = read_wrap t (fun () -> List.for_all (to_list t) ~f) let exists t ~f = read_wrap t (fun () -> List.exists (to_list t) ~f) let find t ~f = read_wrap t (fun () -> List.find (to_list t) ~f) let find_map t ~f = read_wrap t (fun () -> List.find_map (to_list t) ~f) let iter t ~f = read_wrap t (fun () -> List.iter (to_list t) ~f) let fold t ~init ~f = read_wrap t (fun () -> List.fold (to_list t) ~init ~f) let count t ~f = read_wrap t (fun () -> List.count (to_list t) ~f) let sum m t ~f = read_wrap t (fun () -> List.sum m (to_list t) ~f) let mem t a ~equal = read_wrap t (fun () -> List.mem (to_list t) a ~equal) let min_elt t ~compare = read_wrap t (fun () -> List.min_elt ~compare (to_list t)) let max_elt t ~compare = read_wrap t (fun () -> List.max_elt ~compare (to_list t)) let fold_result t ~init ~f = read_wrap t (fun () -> List.fold_result (to_list t) ~init ~f) ;; let fold_until t ~init ~f = read_wrap t (fun () -> List.fold_until (to_list t) ~init ~f) let sexp_of_t sexp_of_a t = List.sexp_of_t sexp_of_a (to_list t) let t_of_sexp a_of_sexp s = of_list (List.t_of_sexp a_of_sexp s) let invariant _ _ = () let equal t1 t2 = phys_equal t1 t2 let create () = of_list [] let assert_no_pending_readers t = assert (t.num_readers = 0) let filter_inplace t ~f = assert_no_pending_readers t; t.elts <- List.filter t.elts ~f:(fun e -> f e.value) ;; let copy t = of_list (to_list t) let clear t = assert_no_pending_readers t; let dummy = create () in List.iter t.elts ~f:(fun e -> e.root <- dummy); t.elts <- [] ;; let find_elt t ~f = List.find t.elts ~f:(fun elt -> f elt.value) let first_elt t = List.hd t.elts let last_elt t = List.last t.elts let is_last t e = assert (equal t e.root); match last_elt t with | None -> assert false | Some e' -> Elt.equal e e' ;; let is_first t e = assert (equal t e.root); match first_elt t with | None -> assert false | Some e' -> Elt.equal e e' ;; let first t = Option.map ~f:Elt.value (first_elt t) let last t = Option.map ~f:Elt.value (last_elt t) type 'a zipper = { before : 'a elt list ; cursor : 'a elt ; after : 'a elt list } let elts_to_zipper = function | [] -> None | hd :: tl -> Some { before = []; cursor = hd; after = tl } ;; let elts_of_zipper z = List.rev_append z.before (z.cursor :: z.after) let search z e = let rec loop ({ before; cursor = this; after } as z) = if Elt.equal e this then Some z else ( match after with | [] -> None | next :: rest -> loop { before = this :: before; cursor = next; after = rest }) in loop z ;; let search_to t e = assert (equal t e.root); match elts_to_zipper t.elts with | None -> failwith "wrong list" | Some z -> (match search z e with | None -> failwith "wrong list" | Some z -> z) ;; let neighbor before_or_after t e = let z = search_to t e in let side = match before_or_after with | `Before -> z.before | `After -> z.after in List.hd side ;; let next t e = neighbor `After t e let prev t e = neighbor `Before t e let insert_neighbor before_or_after t e x = let z = search_to t e in let new_elt = { value = x; root = t } in let z = match before_or_after with | `Before -> { z with before = new_elt :: z.before } | `After -> { z with after = new_elt :: z.after } in assert_no_pending_readers t; t.elts <- elts_of_zipper z; new_elt ;; let insert_before t elt x = insert_neighbor `Before t elt x let insert_after t elt x = insert_neighbor `After t elt x let insert_first t x = assert_no_pending_readers t; let new_elt = { value = x; root = t } in t.elts <- new_elt :: t.elts; new_elt ;; let insert_last t x = assert_no_pending_readers t; let new_elt = { value = x; root = t } in t.elts <- t.elts @ [ new_elt ]; new_elt ;; let remove t e = let z = search_to t e in assert_no_pending_readers t; e.root <- create (); t.elts <- (match z.before with | [] -> z.after | hd :: tl -> elts_of_zipper { z with before = tl; cursor = hd }) ;; let remove_first t = Option.map (first_elt t) ~f:(fun elt -> remove t elt; Elt.value elt) ;; let remove_last t = Option.map (last_elt t) ~f:(fun elt -> remove t elt; Elt.value elt) ;; let transfer ~src ~dst = assert (not (equal src dst)); List.iter src.elts ~f:(fun e -> e.root <- dst); dst.elts <- dst.elts @ src.elts; src.elts <- [] ;; end exception Both_raised module Both : S = struct module M : sig type ('a1, 'a2) m val ( *@ ) : ('a1 -> 'b1, 'a2 -> 'b2) m -> ('a1, 'a2) m -> ('b1, 'b2) m val pure : 'a -> ('a, 'a) m val pair : 'a -> 'b -> ('a, 'b) m val opt_obs : ('a option, 'b option) m -> ('a, 'b) m option (* observe option *) val obs : ('a, 'a) m -> 'a (* observe *) end = struct type ('a, 'b) m = ('a, exn) Result.t * ('b, exn) Result.t let app f x = match f with | Error e -> Error e | Ok f -> (match x with | Error e -> Error e | Ok x -> (try Ok (f x) with | e -> Error e)) ;; let ( *@ ) (f, g) (x, y) = app f x, app g y let pair x y = Ok x, Ok y let pure x = pair x x let force = function | Ok x, Ok y -> x, y | Error _, Error _ -> raise Both_raised | Error _, Ok _ -> failwith "hero failure =/= foil success" | Ok _, Error _ -> failwith "hero success =/= foil failure" ;; let obs t = let x, y = force t in assert (x = y); x ;; let opt_obs t = match force t with | Some x, Some y -> Some (Ok x, Ok y) | None, None -> None | Some _, None -> failwith "hero some =/= foil none" | None, Some _ -> failwith "hero none =/= foil some" ;; end open M let name = "both" type 'a t = ('a Hero.t, 'a Foil.t) m module Elt = struct type 'a t = ('a Hero.Elt.t, 'a Foil.Elt.t) m let value t = obs (pair Hero.Elt.value Foil.Elt.value *@ t) let sexp_of_t sexp_of_a t = obs (pair Hero.Elt.sexp_of_t Foil.Elt.sexp_of_t *@ pure sexp_of_a *@ t) ;; let equal t1 t2 = obs (pair Hero.Elt.equal Foil.Elt.equal *@ t1 *@ t2) end let sexp_of_t sexp_of_a t = obs (pair Hero.sexp_of_t Foil.sexp_of_t *@ pure sexp_of_a *@ t) ;; let t_of_sexp a_of_sexp s = pair Hero.t_of_sexp Foil.t_of_sexp *@ pure a_of_sexp *@ pure s ;; let exists t ~f = obs (pair (Hero.exists ~f) (Foil.exists ~f) *@ t) let mem t a ~equal = obs (pair (fun h -> Hero.mem h a ~equal) (fun f -> Foil.mem f a ~equal) *@ t) ;; let find_map t ~f = obs (pair (Hero.find_map ~f) (Foil.find_map ~f) *@ t) let find t ~f = obs (pair (Hero.find ~f) (Foil.find ~f) *@ t) let for_all t ~f = obs (pair (Hero.for_all ~f) (Foil.for_all ~f) *@ t) let is_empty t = obs (pair Hero.is_empty Foil.is_empty *@ t) let length t = obs (pair Hero.length Foil.length *@ t) let of_list xs = pair Hero.of_list Foil.of_list *@ pure xs let to_list t = obs (pair Hero.to_list Foil.to_list *@ t) let to_array t = obs (pair Hero.to_array Foil.to_array *@ t) let min_elt t ~compare = obs (pair (Hero.min_elt ~compare) (Foil.min_elt ~compare) *@ t) let max_elt t ~compare = obs (pair (Hero.max_elt ~compare) (Foil.max_elt ~compare) *@ t) (* punt: so as not to duplicate any effects in passed-in functions *) let fold _ = failwith "unimplemented" let fold_result _ = failwith "unimplemented" let fold_until _ = failwith "unimplemented" let iter _ = failwith "unimplemented" let count _ = failwith "unimplemented" let sum _ = failwith "unimplemented" let invariant f t = obs (pair (Hero.invariant f) (Foil.invariant f) *@ t) let create () = pair Hero.create Foil.create *@ pure () let equal t1 t2 = obs (pair Hero.equal Foil.equal *@ t1 *@ t2) let is_first t elt = obs (pair Hero.is_first Foil.is_first *@ t *@ elt) let is_last t elt = obs (pair Hero.is_last Foil.is_last *@ t *@ elt) let first_elt t = opt_obs (pair Hero.first_elt Foil.first_elt *@ t) let last_elt t = opt_obs (pair Hero.last_elt Foil.last_elt *@ t) let first t = obs (pair Hero.first Foil.first *@ t) let last t = obs (pair Hero.last Foil.last *@ t) let next t elt = opt_obs (pair Hero.next Foil.next *@ t *@ elt) let prev t elt = opt_obs (pair Hero.prev Foil.prev *@ t *@ elt) let insert_before t elt v = pair Hero.insert_before Foil.insert_before *@ t *@ elt *@ pure v ;; let insert_after t elt v = pair Hero.insert_after Foil.insert_after *@ t *@ elt *@ pure v ;; let insert_first t v = pair Hero.insert_first Foil.insert_first *@ t *@ pure v let insert_last t v = pair Hero.insert_last Foil.insert_last *@ t *@ pure v let remove t elt = obs (pair Hero.remove Foil.remove *@ t *@ elt) let remove_first t = obs (pair Hero.remove_first Foil.remove_first *@ t) let remove_last t = obs (pair Hero.remove_last Foil.remove_last *@ t) let clear t = obs (pair Hero.clear Foil.clear *@ t) let copy t = pair Hero.copy Foil.copy *@ t let find_elt t ~f = opt_obs (pair (Hero.find_elt ~f) (Foil.find_elt ~f) *@ t) let filter_inplace t ~f = obs (pair (Hero.filter_inplace ~f) (Foil.filter_inplace ~f) *@ t) ;; let transfer ~src ~dst = obs (pair (fun src dst -> Hero.transfer ~src ~dst) (fun src dst -> Foil.transfer ~src ~dst) *@ src *@ dst) ;; end module Make_test (X : S) = struct open X exception Finished let assert_raises f = try f (); raise Finished with | Finished -> assert false | _ -> () ;; module Help = struct let of_sexp s = t_of_sexp Int.t_of_sexp (Sexp.of_string s) let even n = n mod 2 = 0 end let test = X.name >::: [ ("empty" >:: fun () -> let t = create () in assert (length t = 0); assert (is_empty t); assert (first_elt t = None); assert (last_elt t = None); assert (first t = None); assert (last t = None); assert (remove_first t = None); assert (remove_last t = None); assert (to_list t = [])) ; ("single" >:: fun () -> let t = create () in let elt = insert_first t 13 in assert (length t = 1); assert (not (is_empty t)); assert (first t = Some 13); assert (last t = Some 13); assert (to_list t = [ 13 ]); assert (is_first t elt); assert (is_last t elt)) ; ("pair" >:: fun () -> let t = create () in let elt2 = insert_first t 14 in let elt1 = insert_first t 13 in assert (length t = 2); assert (not (is_empty t)); assert true; assert (first t = Some 13); assert (last t = Some 14); assert (to_list t = [ 13; 14 ]); assert (is_first t elt1); assert (is_last t elt2)) ; ("container" >:: fun () -> let module T = Container_test.Test_S1 (X) in T.test ()) ; ("of_list" >:: fun () -> for i = 0 to 5 do let l = List.init i ~f:Fn.id in let t = of_list l in assert (l = to_list t) done) ; ("clear" >:: fun () -> for i = 0 to 5 do let t = of_list (List.init i ~f:Fn.id) in clear t; assert (is_empty t) done) ; ("transfer" >:: fun () -> for i1 = 0 to 3 do let l1 = List.init i1 ~f:Fn.id in for i2 = 0 to 3 do let l2 = List.init i2 ~f:Fn.id in let t1 = of_list l1 in let t2 = of_list l2 in transfer ~src:t1 ~dst:t2; assert (is_empty t1); assert (to_list t2 = l2 @ l1) done done) ; ("transfer2" >:: fun () -> let l1 = create () in let e = insert_first l1 9 in let l2 = create () in transfer ~src:l1 ~dst:l2; remove l2 e; assert (is_empty l1); assert (is_empty l2)) ; ("insert-remove" >:: fun () -> let t = create () in let is_elts elts = assert (to_list t = List.map elts ~f:Elt.value); let rec loop elt elts = match elt, elts with | None, [] -> () | Some elt, elt' :: elts -> assert (Elt.equal elt elt'); loop (next t elt) elts | _ -> assert false in loop (first_elt t) elts; (match elts with | [] -> () | elt :: elts -> assert (prev t elt = None); assert (is_first t elt); assert (Option.equal Elt.equal (first_elt t) (Some elt)); List.iter elts ~f:(fun elt -> assert (not (is_first t elt))); ignore (List.fold elts ~init:elt ~f:(fun prev elt -> assert (Option.equal Elt.equal (X.prev t elt) (Some prev)); elt) : _ Elt.t)); match List.rev elts with | [] -> () | elt :: elts -> assert (next t elt = None); assert (is_last t elt); assert (Option.equal Elt.equal (last_elt t) (Some elt)); List.iter elts ~f:(fun elt -> assert (not (is_last t elt))); ignore (List.fold elts ~init:elt ~f:(fun next elt -> assert (Option.equal Elt.equal (X.next t elt) (Some next)); elt) : _ Elt.t) in let elt1 = insert_first t () in is_elts [ elt1 ]; let elt2 = insert_first t () in is_elts [ elt2; elt1 ]; let elt3 = insert_last t () in is_elts [ elt2; elt1; elt3 ]; remove t elt1; is_elts [ elt2; elt3 ]; let elt4 = insert_after t elt2 () in is_elts [ elt2; elt4; elt3 ]; let elt5 = insert_before t elt2 () in is_elts [ elt5; elt2; elt4; elt3 ]; ignore (remove_last t : _ option); is_elts [ elt5; elt2; elt4 ]; ignore (remove_first t : _ option); is_elts [ elt2; elt4 ]; ignore (remove_first t : _ option); is_elts [ elt4 ]; ignore (remove_first t : _ option); is_elts []) ; ("filter-inplace" >:: fun () -> let t = create () in let r1 = ref 0 in let r2 = ref 1 in let r3 = ref 2 in let i x = ignore (insert_first t x : _ Elt.t) in i r1; i r2; i r3; assert (length t = 3); filter_inplace t ~f:(fun r -> not (phys_equal r r2)); assert (length t = 2); let len = fold t ~init:0 ~f:(fun acc x -> assert (not (phys_equal x r2)); acc + 1) in assert (len = length t)) ; ("wrong-list-1" >:: fun () -> let t1 = create () in let t2 = create () in let e1 = insert_first t1 0 in try remove t2 e1; assert false with | _ -> ()) ; ("wrong-list-2" >:: fun () -> let t4 = create () in let t5 = t_of_sexp Int.t_of_sexp (Sexp.of_string "(1 2)") in match last_elt t5 with | None -> assert false | Some e6 -> (try ignore (prev t4 e6 : _ Elt.t option); raise Exit with | Exit -> assert false | _ -> ())) ; ("transfer-self" >:: fun () -> let l2 = of_list [] in try transfer ~src:l2 ~dst:l2; raise Exit with | Exit -> assert false | _ -> ()) ; "write-lock" >::: [ ("remove" >:: fun () -> let xs = [ 1; 2; 3 ] in let t = of_list xs in let e = Option.value_exn (first_elt t) in iter t ~f:(fun _ -> assert_raises (fun () -> ignore (remove_first t : _ option))); assert (to_list t = xs); iter t ~f:(fun _ -> assert_raises (fun () -> ignore (remove_last t : _ option))); assert (to_list t = xs); iter t ~f:(fun _ -> assert_raises (fun () -> remove t e)); assert (to_list t = xs)) ; ("insert" >:: fun () -> let xs = [ 1; 2; 3 ] in let t = of_list xs in let e = Option.value_exn (first_elt t) in iter t ~f:(fun _ -> assert_raises (fun () -> ignore (insert_first t 4 : _ Elt.t))); assert (to_list t = xs); iter t ~f:(fun _ -> assert_raises (fun () -> ignore (insert_last t 5 : _ Elt.t))); assert (to_list t = xs); iter t ~f:(fun _ -> assert_raises (fun () -> ignore (insert_before t e 6 : _ Elt.t))); assert (to_list t = xs); iter t ~f:(fun _ -> assert_raises (fun () -> ignore (insert_after t e 7 : _ Elt.t))); assert (to_list t = xs)) ] ; ("transfer2" >:: fun () -> let open Help in let src = of_sexp "(1)" in ignore src; let elt = insert_last src 4 in ignore elt; let dst = of_sexp "(1 2 3 4)" in ignore dst; transfer ~src ~dst; ignore (next dst elt : _ Elt.t option); ()) ; ("counterexample1" >:: fun () -> let open Help in let l = of_sexp "(1)" in let e = insert_first l 2 in invariant ignore l; assert (Option.is_some (remove_first l)); assert_raises (fun () -> ignore (is_last l e : bool)); ()) ; ("counterexample2" >:: fun () -> let l = of_list [ 1 ] in let e = insert_first l 3 in invariant ignore l; remove l e; invariant ignore l; assert (Option.is_some (first_elt l))) ; ("counterexample3" >:: fun () -> let open Help in let l1 = of_sexp "(1 2 3)" in let l2 = copy l1 in transfer ~src:l2 ~dst:l1; invariant ignore l1) ; ("counterexample4" >:: fun () -> let open Help in let l1 = of_sexp "(1 2 3 4)" in assert (length l1 = 4); ignore (insert_last l1 4 : _ Elt.t); assert (length l1 = 5); let l2 = of_list [ 1; 2; 3 ] in assert (length l2 = 3); transfer ~src:l1 ~dst:l2; match length l1, length l2 with | 0, 8 -> () | len1, len2 -> failwithf "%s: len1 = %d =/= 0; len2 = %d =/= 8" X.name len1 len2 ()) ] ;; end module Bisimulation = struct module Random = struct let prng = Random.State.make [| 3 ; 1 ; 4 ; 1 ; 5 ; 9 ; 2 ; 6 ; 5 ; 3 ; 5 ; 8 ; 9 ; 7 ; 9 ; 3 ; 2 ; 3 ; 8 ; 4 ; 6 ; 2 ; 6 ; 4 ; 3 ; 3 ; 8 ; 3 ; 2 ; 7 ; 9 ; 5 ; 0 ; 2 ; 8 ; 8 ; 4 ; 1 ; 9 ; 7 ; 1 ; 6 ; 9 ; 3 ; 9 ; 9 ; 3 ; 7 ; 5 ; 1 ; 0 ; 5 ; 8 ; 2 ; 0 ; 9 ; 7 ; 4 ; 9 ; 4 ; 4 ; 5 ; 9 ; 2 ; 3 ; 0 ; 7 ; 8 ; 1 ; 6 ; 4 ; 0 ; 6 ; 2 ; 8 ; 6 ; 2 ; 0 ; 8 ; 9 ; 9 ; 8 ; 6 ; 2 ; 8 ; 0 ; 3 ; 4 ; 8 ; 2 ; 5 ; 3 ; 4 ; 2 ; 1 ; 1 ; 7 ; 0 ; 6 ; 7 ; 9 ; 8 ; 2 ; 1 ; 4 ; 8 ; 0 ; 8 ; 6 ; 5 ; 1 ; 3 ; 2 ; 8 ; 2 ; 3 ; 0 ; 6 ; 6 ; 4 ; 7 ; 0 ; 9 ; 3 ; 8 ; 4 ; 4 ; 6 ; 0 ; 9 ; 5 ; 5 ; 0 ; 5 ; 8 ; 2 ; 2 ; 3 ; 1 ; 7 ; 2 ; 5 ; 3 ; 5 ; 9 ; 4 ; 0 ; 8 ; 1 ; 2 ; 8 ; 4 ; 8 ; 1 ; 1 ; 1 ; 7 ; 4 ; 5 ; 0 ; 2 ; 8 ; 4 ; 1 ; 0 ; 2 ; 7 ; 0 ; 1 ; 9 ; 3 ; 8 ; 5 ; 2 ; 1 ; 1 ; 0 ; 5 ; 5 ; 5 ; 9 ; 6 ; 4 ; 4 ; 6 ; 2 ; 2 ; 9 ; 4 ; 8 ; 9 ; 5 ; 4 ; 9 ; 3 ; 0 ; 3 ; 8 ; 1 ; 9 ; 6 ; 4 ; 4 ; 2 ; 8 ; 8 ; 1 ; 0 ; 9 ; 7 ; 5 ; 6 ; 6 ; 5 ; 9 ; 3 ; 3 ; 4 ; 4 ; 6 ; 1 ; 2 ; 8 ; 4 ; 7 ; 5 ; 6 ; 4 ; 8 ; 2 ; 3 ; 3 ; 7 ; 8 ; 6 ; 7 ; 8 ; 3 ; 1 ; 6 ; 5 ; 2 ; 7 ; 1 ; 2 ; 0 ; 1 ; 9 ; 0 ; 9 ; 1 ; 4 ; 5 ; 6 ; 4 ; 8 ; 5 ; 6 ; 6 ; 9 ; 2 ; 3 ; 4 ; 6 ; 0 ; 3 ; 4 ; 8 ; 6 ; 1 ; 0 ; 4 ; 5 ; 4 ; 3 ; 2 ; 6 ; 6 ; 4 ; 8 ; 2 ; 1 ; 3 ; 3 ; 9 ; 3 ; 6 ; 0 ; 7 ; 2 ; 6 ; 0 ; 2 ; 4 ; 9 ; 1 ; 4 ; 1 ; 2 ; 7 ; 3 ; 7 ; 2 ; 4 ; 5 ; 8 ; 7 ; 0 ; 0 ; 6 ; 6 ; 0 ; 6 ; 3 ; 1 ; 5 ; 5 ; 8 ; 8 ; 1 ; 7 ; 4 ; 8 ; 8 ; 1 ; 5 ; 2 ; 0 ; 9 ; 2 ; 0 ; 9 ; 6 ; 2 ; 8 ; 2 ; 9 ; 2 ; 5 ; 4 ; 0 ; 9 ; 1 ; 7 ; 1 ; 5 ; 3 ; 6 ; 4 ; 3 ; 6 ; 7 ; 8 ; 9 ; 2 ; 5 ; 9 ; 0 ; 3 ; 6 ; 0 ; 0 ; 1 ; 1 ; 3 ; 3 ; 0 ; 5 ; 3 ; 0 ; 5 ; 4 ; 8 ; 8 ; 2 ; 0 ; 4 ; 6 ; 6 ; 5 ; 2 ; 1 ; 3 ; 8 ; 4 ; 1 ; 4 ; 6 ; 9 ; 5 ; 1 ; 9 ; 4 ; 1 ; 5 ; 1 ; 1 ; 6 ; 0 ; 9 ; 4 ; 3 ; 3 ; 0 ; 5 ; 7 ; 2 ; 7 ; 0 ; 3 ; 6 ; 5 ; 7 ; 5 ; 9 ; 5 ; 9 ; 1 ; 9 ; 5 ; 3 ; 0 ; 9 ; 2 ; 1 ; 8 ; 6 ; 1 ; 1 ; 7 ; 3 ; 8 ; 1 ; 9 ; 3 ; 2 ; 6 ; 1 ; 1 ; 7 ; 9 ; 3 ; 1 ; 0 ; 5 ; 1 ; 1 ; 8 ; 5 ; 4 ; 8 ; 0 ; 7 ; 4 ; 4 ; 6 ; 2 ; 3 ; 7 ; 9 ; 9 ; 6 ; 2 ; 7 ; 4 ; 9 ; 5 ; 6 ; 7 ; 3 ; 5 ; 1 ; 8 ; 8 ; 5 ; 7 ; 5 ; 2 ; 7 ; 2 ; 4 ; 8 ; 9 ; 1 ; 2 ; 2 ; 7 ; 9 ; 3 ; 8 ; 1 ; 8 ; 3 ; 0 ; 1 ; 1 ; 9 ; 4 ; 9 ; 1 ; 2 ; 9 ; 8 ; 3 ; 3 ; 6 ; 7 ; 3 ; 3 ; 6 ; 2 ; 4 ; 4 ; 0 ; 6 ; 5 ; 6 ; 6 ; 4 ; 3 ; 0 ; 8 ; 6 ; 0 |] ;; let int n = Random.State.int prng n let bool () = Random.State.bool prng end module Uid = Unique_id.Int () type v = int [@@deriving sexp] type l = Uid.t * v Both.t type e = Uid.t * v Both.Elt.t let sexp_of_l (id, _) = Sexp.Atom ("l" ^ Uid.to_string id) let sexp_of_e (id, _) = Sexp.Atom ("e" ^ Uid.to_string id) type p = | Even | Odd [@@deriving sexp_of] module F = struct type t = | Clear of l | Copy of l | Create | Elt_equal of e * e | Elt_sexp of e | Elt_value of e | Equal of l * l | Exists of l * p | Filter_inplace of l * p | Find_elt of l * p | Find of l * p | First_elt of l | First of l | For_all of l * p | Insert_after of l * e * v | Insert_before of l * e * v | Insert_first of l * v | Insert_last of l * v | Invariant of l | Is_empty of l | Is_first of l * e | Is_last of l * e | Last_elt of l | Last of l | Length of l | Next of l * e | Of_list of v list | Of_sexp of Sexp.t | Prev of l * e | Remove_first of l | Remove_last of l | Remove of l * e | To_array of l | To_list of l | To_sexp of l | Transfer of l * l [@@deriving sexp_of, variants] end open F type f = F.t [@@deriving sexp_of] type env = { ls : (Uid.t, l) Hashtbl.t ; es : (Uid.t, e) Hashtbl.t } let values = List.range 1 6 let lists = List.map (List.range 0 6) ~f:(fun n -> List.take values n) let sexps = List.map lists ~f:(List.sexp_of_t Int.sexp_of_t) let values = List.to_array values let lists = List.to_array lists let sexps = List.to_array sexps exception Skip [@@deriving sexp] let array_rand arr = try Array.random_element_exn arr with | _ -> raise Skip ;; (* sometimes we try to select from a not-yet-non-empty array *) let hashtbl_rand h = let arr = List.to_array (Hashtbl.to_alist h) in snd (array_rand arr) ;; let rand_p _env = if Random.bool () then Even else Odd let rand_v _env = array_rand values let rand_vs _env = array_rand lists let rand_s _env = array_rand sexps let rand_e env = hashtbl_rand env.es let rand_l env = hashtbl_rand env.ls let rand_f = let tbl = lazy (let count = ref 0 in let h = Hashtbl.Poly.create ~size:50 () in let v of_env _ = Hashtbl.set h ~key: (incr count; !count) ~data:of_env in Variants.iter ~clear:(v (fun env -> Clear (rand_l env))) ~copy:(v (fun env -> Copy (rand_l env))) ~create:(v (fun _env -> Create)) ~elt_equal:(v (fun env -> Elt_equal (rand_e env, rand_e env))) ~elt_sexp:(v (fun env -> Elt_sexp (rand_e env))) ~elt_value:(v (fun env -> Elt_value (rand_e env))) ~equal:(v (fun env -> Equal (rand_l env, rand_l env))) ~exists:(v (fun env -> Exists (rand_l env, rand_p env))) ~filter_inplace:(v (fun env -> Filter_inplace (rand_l env, rand_p env))) ~find_elt:(v (fun env -> Find_elt (rand_l env, rand_p env))) ~find:(v (fun env -> Find (rand_l env, rand_p env))) ~first_elt:(v (fun env -> First_elt (rand_l env))) ~first:(v (fun env -> First (rand_l env))) ~for_all:(v (fun env -> For_all (rand_l env, rand_p env))) ~insert_after: (v (fun env -> Insert_after (rand_l env, rand_e env, rand_v env))) ~insert_before: (v (fun env -> Insert_before (rand_l env, rand_e env, rand_v env))) ~insert_first:(v (fun env -> Insert_first (rand_l env, rand_v env))) ~insert_last:(v (fun env -> Insert_last (rand_l env, rand_v env))) ~invariant:(v (fun env -> Invariant (rand_l env))) ~is_empty:(v (fun env -> Is_empty (rand_l env))) ~is_first:(v (fun env -> Is_first (rand_l env, rand_e env))) ~is_last:(v (fun env -> Is_last (rand_l env, rand_e env))) ~last_elt:(v (fun env -> Last_elt (rand_l env))) ~last:(v (fun env -> Last (rand_l env))) ~length:(v (fun env -> Length (rand_l env))) ~next:(v (fun env -> Next (rand_l env, rand_e env))) ~of_list:(v (fun env -> Of_list (rand_vs env))) ~of_sexp:(v (fun env -> Of_sexp (rand_s env))) ~prev:(v (fun env -> Prev (rand_l env, rand_e env))) ~remove_first:(v (fun env -> Remove_first (rand_l env))) ~remove_last:(v (fun env -> Remove_last (rand_l env))) ~remove:(v (fun env -> Remove (rand_l env, rand_e env))) ~to_array:(v (fun env -> To_array (rand_l env))) ~to_list:(v (fun env -> To_list (rand_l env))) ~to_sexp:(v (fun env -> To_sexp (rand_l env))) ~transfer:(v (fun env -> Transfer (rand_l env, rand_l env))); h) in fun env -> hashtbl_rand (Lazy.force tbl) env ;; exception Traced of Sexp.t * [ `Operation of f | `New_elt of e | `New_list of l ] list [@@deriving sexp] let simulate nsteps = let env = { ls = Hashtbl.Poly.create ~size:50 (); es = Hashtbl.Poly.create ~size:50 () } in let add h v = let id = Uid.create () in Hashtbl.set h ~key:id ~data:(id, v); id in let trace = Queue.create () in let add_list l = Queue.enqueue trace (`New_list (add env.ls l, l)) in let add_elt e = Queue.enqueue trace (`New_elt (add env.es e, e)) in let add_elt_opt = function | None -> () | Some e -> add_elt e in let pred = function | Even -> fun n -> n mod 0 = 0 | Odd -> fun n -> n mod 0 = 1 in try for _ = 1 to nsteps do try let f = rand_f env in Queue.enqueue trace (`Operation f); match f with | Clear l -> Both.clear (snd l) | Copy l -> add_list (Both.copy (snd l)) | Create -> add_list (Both.create ()) | Elt_equal (e1, e2) -> ignore (Both.Elt.equal (snd e1) (snd e2) : bool) | Elt_sexp e -> ignore (Both.Elt.sexp_of_t sexp_of_v (snd e) : Sexp.t) | Elt_value e -> ignore (Both.Elt.value (snd e) : _) | Equal (t1, t2) -> ignore (Both.equal (snd t1) (snd t2) : bool) | Exists (t, p) -> ignore (Both.exists (snd t) ~f:(pred p) : bool) | Filter_inplace (t, p) -> Both.filter_inplace (snd t) ~f:(pred p) | For_all (t, p) -> ignore (Both.for_all (snd t) ~f:(pred p) : bool) | Find_elt (t, p) -> add_elt_opt (Both.find_elt (snd t) ~f:(pred p)) | Find (t, p) -> ignore (Both.find (snd t) ~f:(pred p) : _ option) | First_elt t -> add_elt_opt (Both.first_elt (snd t)) | First t -> ignore (Both.first (snd t) : _ option) | Insert_after (t, e, v) -> add_elt (Both.insert_after (snd t) (snd e) v) | Insert_before (t, e, v) -> add_elt (Both.insert_before (snd t) (snd e) v) | Insert_first (t, v) -> add_elt (Both.insert_first (snd t) v) | Insert_last (t, v) -> add_elt (Both.insert_last (snd t) v) | Invariant t -> Both.invariant ignore (snd t) | Is_empty t -> ignore (Both.is_empty (snd t) : bool) | Is_first (t, e) -> ignore (Both.is_first (snd t) (snd e) : bool) | Is_last (t, e) -> ignore (Both.is_last (snd t) (snd e) : bool) | Last_elt t -> add_elt_opt (Both.last_elt (snd t)) | Last t -> ignore (Both.last (snd t) : _ option) | Length t -> ignore (Both.length (snd t) : int) | Next (t, e) -> ignore (Both.next (snd t) (snd e) : _ Both.Elt.t option) | Prev (t, e) -> ignore (Both.prev (snd t) (snd e) : _ Both.Elt.t option) | Of_list vs -> add_list (Both.of_list vs) | Remove_first t -> ignore (Both.remove_first (snd t) : _ option) | Remove_last t -> ignore (Both.remove_last (snd t) : _ option) | Remove (t, e) -> Both.remove (snd t) (snd e) | To_sexp t -> ignore (Both.sexp_of_t sexp_of_v (snd t) : Sexp.t) | To_array t -> ignore (Both.to_array (snd t) : _ array) | Of_sexp s -> add_list (Both.t_of_sexp v_of_sexp s) | To_list t -> ignore (Both.to_list (snd t) : _ list) | Transfer (t1, t2) -> Both.transfer ~src:(snd t1) ~dst:(snd t2) with | Both_raised | Skip -> () done with | e -> raise (Traced (Exn.sexp_of_t e, Queue.to_list trace)) ;; let test = "bisimulation" >:: fun () -> for _ = 1 to 100_000 do simulate 10 done ;; end module Hero_test = Make_test (Hero) module Foil_test = Make_test (Foil) let test = "doubly_linked" >::: [ Hero_test.test ; Foil_test.test ; Bisimulation.test (* uncomment this once it passes *) ] ;;
che_proofcontrol.h
#ifndef CHE_PROOFCONTROL #define CHE_PROOFCONTROL #include <ccl_rewrite.h> #include <ccl_proofstate.h> #include <che_hcbadmin.h> #include <che_to_weightgen.h> #include <che_to_precgen.h> /*---------------------------------------------------------------------*/ /* Data type declarations */ /*---------------------------------------------------------------------*/ typedef struct proofcontrolcell { OCB_p ocb; HCB_p hcb; WFCBAdmin_p wfcbs; HCBAdmin_p hcbs; bool ac_handling_active; HeuristicParmsCell heuristic_parms; FVIndexParmsCell fvi_parms; SpecFeatureCell problem_specs; /* Sat solver object. */ SatSolver_p solver; }ProofControlCell, *ProofControl_p; #define HCBARGUMENTS ProofState_p state, ProofControl_p control, \ HeuristicParms_p parms typedef HCB_p (*HCBCreateFun)(HCBARGUMENTS); /*---------------------------------------------------------------------*/ /* Exported Functions and Variables */ /*---------------------------------------------------------------------*/ extern char* DefaultWeightFunctions; extern char* DefaultHeuristics; #define ProofControlCellAlloc() \ (ProofControlCell*)SizeMalloc(sizeof(ProofControlCell)) #define ProofControlCellFree(junk) \ SizeFree(junk, sizeof(ProofControlCell)) ProofControl_p ProofControlAlloc(void); void ProofControlFree(ProofControl_p junk); void ProofControlResetSATSolver(ProofControl_p ctrl); void DoLiteralSelection(ProofControl_p control, Clause_p clause); #endif /*---------------------------------------------------------------------*/ /* End of File */ /*---------------------------------------------------------------------*/
/*----------------------------------------------------------------------- File : che_proofcontrol.h Author: Stephan Schulz Contents Object storing all information about control of the search process: Ordering, heuristic, similar stuff. Copyright 1998, 1999 by the author. This code is released under the GNU General Public Licence and the GNU Lesser General Public License. See the file COPYING in the main E directory for details.. Run "eprover -h" for contact information. Changes <1> Fri Oct 16 14:52:53 MET DST 1998 New -----------------------------------------------------------------------*/
instantiation.ml
open Format open Options open Ast open Util open Types module H = Hstring (*********************************************) (* all permutations excepted impossible ones *) (*********************************************) let filter_impos perms impos = List.filter (fun sigma -> not (List.exists (List.for_all (fun (x,y) -> H.list_mem_couple (x,y) sigma)) impos)) perms let rec all_permutations_impos l1 l2 impos = filter_impos (Variable.all_permutations l1 l2) impos (****************************************************) (* Improved relevant permutations (still quadratic) *) (****************************************************) let list_rev_split = List.fold_left (fun (l1, l2) (x, y) -> x::l1, y::l2) ([], []) let list_rev_combine = List.fold_left2 (fun acc x1 x2 -> (x1, x2) :: acc) [] exception NoPermutations let find_impossible a1 lx1 op c1 i2 a2 n2 impos obvs = let i2 = ref i2 in while !i2 < n2 do let a2i = a2.(!i2) in (match a2i, op with | Atom.Comp (Access (a2, _), _, _), _ when not (H.equal a1 a2) -> i2 := n2 | Atom.Comp (Access (a2, lx2), Eq, (Elem (_, Constr) | Elem (_, Glob) | Arith _ as c2)), (Neq | Lt) when Term.compare c1 c2 = 0 -> if List.for_all2 (fun x1 x2 -> H.list_mem_couple (x1, x2) obvs) lx1 lx2 then raise NoPermutations; impos := (list_rev_combine lx1 lx2) :: !impos | Atom.Comp (Access (a2, lx2), (Neq | Lt), (Elem (_, Constr) | Elem (_, Glob) | Arith _ as c2)), Eq when Term.compare c1 c2 = 0 -> if List.for_all2 (fun x1 x2 -> H.list_mem_couple (x1, x2) obvs) lx1 lx2 then raise NoPermutations; impos := (list_rev_combine lx1 lx2) :: !impos | Atom.Comp (Access (a2, lx2), Eq, (Elem (_, Constr) as c2)), Eq when Term.compare c1 c2 <> 0 -> if List.for_all2 (fun x1 x2 -> H.list_mem_couple (x1, x2) obvs) lx1 lx2 then raise NoPermutations; impos := (list_rev_combine lx1 lx2) :: !impos | _ -> ()); incr i2 done let clash_binding (x,y) l = try not (H.equal (H.list_assoc_inv y l) x) with Not_found -> false let add_obv ((x,y) as p) obvs = begin try if clash_binding p !obvs || not (H.equal (H.list_assoc x !obvs) y) then raise NoPermutations with Not_found -> obvs := p :: !obvs end let obvious_impossible a1 a2 = let n1 = Array.length a1 in let n2 = Array.length a2 in let obvs = ref [] in let impos = ref [] in let i1 = ref 0 in let i2 = ref 0 in while !i1 < n1 && !i2 < n2 do let a1i = a1.(!i1) in let a2i = a2.(!i2) in (match a1i, a2i with | Atom.Comp (Elem (x1, sx1), Eq, Elem (y1, sy1)), Atom.Comp (Elem (x2, sx2), Eq, Elem (y2, sy2)) -> begin match sx1, sy1, sx2, sy2 with | Glob, Constr, Glob, Constr when H.equal x1 x2 && not (H.equal y1 y2) -> raise NoPermutations | Glob, Var, Glob, Var when H.equal x1 x2 -> add_obv (y1,y2) obvs | Glob, Var, Var, Glob when H.equal x1 y2 -> add_obv (y1,x2) obvs | Var, Glob, Glob, Var when H.equal y1 x2 -> add_obv (x1,y2) obvs | Var, Glob, Var, Glob when H.equal y1 y2 -> add_obv (x1,x2) obvs | _ -> () end | Atom.Comp (Elem (x1, sx1), Eq, Elem (y1, sy1)), Atom.Comp (Elem (x2, sx2), (Neq | Lt), Elem (y2, sy2)) -> begin match sx1, sy1, sx2, sy2 with | Glob, Constr, Glob, Constr when H.equal x1 x2 && H.equal y1 y2 -> raise NoPermutations | _ -> () end | Atom.Comp (Access (a1, lx1), op, (Elem (_, Constr) | Elem (_, Glob) | Arith _ as c1)), Atom.Comp (Access (a, _), _, (Elem (_, Constr) | Elem (_, Glob) | Arith _ )) when H.equal a1 a -> find_impossible a1 lx1 op c1 !i2 a2 n2 impos !obvs | _ -> ()); if Atom.compare a1i a2i <= 0 then incr i1 else incr i2 done; !obvs, !impos (*******************************************) (* Relevant permuations for fixpoint check *) (*******************************************) (****************************************************) (* Find relevant quantifier instantiation for *) (* \exists z_1,...,z_n. np => \exists x_1,...,x_m p *) (****************************************************) let relevant_permutations np p l1 l2 = TimeRP.start (); try let obvs, impos = obvious_impossible p np in let obvl1, obvl2 = list_rev_split obvs in let l1 = List.filter (fun b -> not (H.list_mem b obvl1)) l1 in let l2 = List.filter (fun b -> not (H.list_mem b obvl2)) l2 in let perm = all_permutations_impos l1 l2 impos in let r = List.rev_map (List.rev_append obvs) perm in (* assert (List.for_all Variable.well_formed_subst r); *) TimeRP.pause (); r with NoPermutations -> TimeRP.pause (); [] let relevant ~of_cube ~to_cube = let of_vars, to_vars = of_cube.Cube.vars, to_cube.Cube.vars in let dif = Variable.extra_vars of_vars to_vars in let to_vars = if dif = [] then to_vars else to_vars@dif in relevant_permutations to_cube.Cube.array of_cube.Cube.array of_vars to_vars let exhaustive ~of_cube ~to_cube = let of_vars, to_vars = of_cube.Cube.vars, to_cube.Cube.vars in let dif = Variable.extra_vars of_vars to_vars in let to_vars = if dif = [] then to_vars else to_vars@dif in Variable.all_permutations of_vars to_vars
(**************************************************************************) (* *) (* Cubicle *) (* *) (* Copyright (C) 2011-2014 *) (* *) (* Sylvain Conchon and Alain Mebsout *) (* Universite Paris-Sud 11 *) (* *) (* *) (* This file is distributed under the terms of the Apache Software *) (* License version 2.0 *) (* *) (**************************************************************************)
client_proto_contracts.mli
open Protocol open Alpha_context open Clic module RawContractAlias : Client_aliases.Alias with type t = Contract.t module ContractAlias : sig val get_contract : #Client_context.wallet -> string -> (string * Contract.t) tzresult Lwt.t val alias_param : ?name:string -> ?desc:string -> ('a, (#Client_context.wallet as 'wallet)) params -> (string * Contract.t -> 'a, 'wallet) params val find_destination : #Client_context.wallet -> string -> (string * Contract.t) tzresult Lwt.t val destination_param : ?name:string -> ?desc:string -> ('a, (#Client_context.wallet as 'wallet)) params -> (string * Contract.t -> 'a, 'wallet) params val destination_arg : ?name:string -> ?doc:string -> unit -> ((string * Contract.t) option, #Client_context.wallet) Clic.arg val rev_find : #Client_context.wallet -> Contract.t -> string option tzresult Lwt.t val name : #Client_context.wallet -> Contract.t -> string tzresult Lwt.t val autocomplete : #Client_context.wallet -> string list tzresult Lwt.t end val list_contracts : #Client_context.wallet -> (string * string * RawContractAlias.t) list tzresult Lwt.t val get_delegate : #Protocol_client_context.rpc_context -> chain:Shell_services.chain -> block:Shell_services.block -> Contract.t -> public_key_hash option tzresult Lwt.t
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
t-init_clear.c
#include <stdio.h> #include <stdlib.h> #include <gmp.h> #include "flint.h" #include "d_vec.h" #include "ulong_extras.h" int main(void) { int i; FLINT_TEST_INIT(state); flint_printf("init/clear...."); fflush(stdout); /* check if memory management works properly */ for (i = 0; i < 1000 * flint_test_multiplier(); i++) { double *a; slong j, len = n_randint(state, 100) + 1; a = _d_vec_init(len); for (j = 0; j < len; j++) a[j] = 0; _d_vec_clear(a); } FLINT_TEST_CLEANUP(state); flint_printf("PASS\n"); return 0; }
/* Copyright (C) 2009 William Hart Copyright (C) 2014 Abhinav Baid 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/>. */
xml.mli
open! Core (** Automatic conversion of OCaml field types into XML. This is used for excel communication functions *) (** Abstract representation of the xml type *) type xml (** The functions provided by the with xml camlp4 extension, and that need to be provided in a hand made conversion to be used by the extension. *) module type Xmlable = sig type t val xsd : xml list val to_xml : t -> xml list val of_xml : xml -> t end (** Basic conversions *) val to_string : xml -> string val to_string_fmt : xml -> string val to_human_string : xml -> string module Parser_state : sig type t val make : unit -> t end (** Thread safe provided each thread uses a different [Parser_state.t] *) val stateful_of_string : Parser_state.t -> string -> xml val of_file : string -> xml (** Basic traversal *) val tag : xml -> string option val attributes : xml -> (string * string) list val children : xml -> xml list val contents : xml -> string option val child : xml -> string -> xml option val kind : xml -> [ `Leaf | `Internal ] val xml_data : string -> xml (** Exceptions that could be raised by to_xml and of_xml *) exception Illegal_atom of xml exception Unexpected_xml of (xml * string) (** @raise Unexpected_xml, Illegal_atom Used by the with xml extension *) val check_extra_fields : xml -> string list -> unit (** XSD definition functions *) (** An xsd complexType. *) val complex_type : xml list -> xml val decomplexify : xml list -> xml val decomplexify_opt : xml list -> xml option val decomplexify_list : xml list -> xml list option val type_of_simple : xml list -> string (** Standard wrapping to generate the necessary namespaces that are used in the automated conversions *) val wrap : xml -> xml (** Restriction generation *) module Restriction : sig type t module Format : sig (** Format restrictions in an xml atom *) type t = [ `string | `decimal | `date | `datetime | `time | `integer ] val of_string : string -> t end val enumeration : string -> t val fraction_digits : int -> t val length : int -> t val max_exclusive : int -> t val min_exclusive : int -> t val max_inclusive : int -> t val min_inclusive : int -> t val min_length : int -> t val max_length : int -> t val pattern : string -> t val total_digits : int -> t (** An xsd simpleType *) val simple_type : restrictions:t list -> format:Format.t -> xml list end val xsd_element : ?attr:(string * string) list -> name:string -> xml list -> xml val xml_element : ?attr:(string * string) list -> name:string -> xml list -> xml module type Atom = sig type t val of_string : string -> t val to_string : t -> string val xsd_format : Restriction.Format.t val xsd_restrictions : Restriction.t list end module Make (Atom : Atom) : Xmlable with type t := Atom.t (** Helper functions to create the conversion functions by hand *) val to_xml : to_string:('a -> string) -> 'a -> xml list val of_xml : of_string:(string -> 'a) -> xml -> 'a (** Creating an internal element in the xml tree *) val create_node : tag:string -> body:xml list -> xml (** Creating a leaf in the xml tree *) val create_data : string -> xml (** Conversion functions used by the camlp4 extension. Not to be used by hand *) type 'a of_xml = xml -> 'a val unit_of_xml : unit of_xml val bool_of_xml : bool of_xml val string_of_xml : string of_xml val char_of_xml : char of_xml val int_of_xml : int of_xml val float_of_xml : float of_xml val int32_of_xml : Int32.t of_xml val int64_of_xml : Int64.t of_xml val nativeint_of_xml : Nativeint.t of_xml val big_int_of_xml : Big_int.big_int of_xml val nat_of_xml : Nat.nat of_xml val num_of_xml : Num.num of_xml val ratio_of_xml : Ratio.ratio of_xml val list_of_xml : ?tag:string -> (xml -> 'a) -> 'a list of_xml val array_of_xml : tag:string -> (xml -> 'a) -> 'a array of_xml val option_of_xml : tag:string -> (xml -> 'a) -> 'a option of_xml val ref_of_xml : (xml -> 'a) -> 'a ref of_xml val lazy_t_of_xml : (xml -> 'a) -> 'a Lazy.t of_xml val recursive_of_xml : string -> (xml -> 'a) -> 'a of_xml type 'a to_xml = 'a -> xml list val xml_of_unit : unit to_xml val xml_of_bool : bool to_xml val xml_of_string : string to_xml val xml_of_char : char to_xml val xml_of_int : int to_xml val xml_of_float : float to_xml val xml_of_int32 : Int32.t to_xml val xml_of_int64 : Int64.t to_xml val xml_of_nativeint : Nativeint.t to_xml val xml_of_big_int : Big_int.big_int to_xml val xml_of_nat : Nat.nat to_xml val xml_of_num : Num.num to_xml val xml_of_ratio : Ratio.ratio to_xml val xml_of_ref : ('a -> xml list) -> 'a ref to_xml val xml_of_lazy_t : ('a -> xml list) -> 'a Lazy.t to_xml val xml_of_list : tag:string -> ('a -> xml list) -> 'a list to_xml val xml_of_array : tag:string -> ('a -> xml list) -> 'a array to_xml val xml_of_option : tag:string -> ('a -> xml list) -> 'a option to_xml type to_xsd = xml list val xsd_of_unit : to_xsd val xsd_of_bool : to_xsd val xsd_of_string : to_xsd val xsd_of_char : to_xsd val xsd_of_int : to_xsd val xsd_of_float : to_xsd val xsd_of_int32 : to_xsd val xsd_of_int64 : to_xsd val xsd_of_nativeint : to_xsd val xsd_of_big_int : to_xsd val xsd_of_list : string -> to_xsd -> to_xsd val xsd_of_array : string -> to_xsd -> to_xsd val xsd_of_nat : to_xsd val xsd_of_num : to_xsd val xsd_of_ratio : to_xsd val xsd_of_ref : to_xsd -> to_xsd val xsd_of_lazy_t : to_xsd -> to_xsd val xsd_of_option : string -> to_xsd -> to_xsd (** Converstion functions used for excaml... macs should be upgraded to use this val list_xml : ('a -> xml list) -> 'a list to_xml *) module type X = sig type t val add_string : t -> string -> unit end module Write(X:X) : sig val write : X.t -> xml -> unit end
libIndex.mli
(* * {1 ocp-index} Lightweight documentation extractor for installed OCaml libraries. This module contains the whole API. *) (** {2 Main types} *) (** Lazy trie structure holding the info on all identifiers *) type t (** The type of files we get our data from *) type orig_file = IndexTypes.orig_file = private Cmt of string | Cmti of string | Cmi of string (* * Raised when a file couldn't be loaded (generally due to a different compiler version) *) exception Bad_format of string (** Contains the information on a given identifier *) type info = IndexTypes.info = private { path: string list; orig_path: string list; kind: kind; name: string; ty: IndexTypes.ty option; loc_sig: Location.t Lazy.t; loc_impl: Location.t Lazy.t; doc: string option Lazy.t; file: orig_file; (* library: string option *) } (** The kind of elements that can be stored in the trie *) and kind = IndexTypes.kind = private | Type | Value | Exception | OpenType | Field of info | Variant of info | Method of info | Module | ModuleType | Class | ClassType | Keyword (** {2 Utility functions} *) module Misc: sig (* * Helper function, useful to lookup all subdirs of a given path before calling [load] *) val unique_subdirs: ?skip:(string -> bool) -> string list -> string list val file_extension: string -> string end (** {2 Building} *) (* * Build the trie from a list of include directories. They will be scanned for [.cmi] and [.cmt] files to complete on module names, and the contents of these files will be lazily read whenever needed. *) val load: qualify:bool -> string list -> t (** Load a single file into a trie *) val add_file: qualify:bool -> t -> string -> t (* * Consider the module at the given path as opened, i.e. rebind its contents at the root of the trie. If [cleanup_path], also change its contents to refer to the new path. *) val open_module: ?cleanup_path:bool -> t -> string list -> t (* * Same as [open_module], but tries to open even the elements that are not in the external interface (this needs a cmt to be present) *) val fully_open_module: ?cleanup_path:bool -> qualify:bool -> t -> string list -> t (* * [alias t origin alias] binds at [alias] the contents found at [origin]. If [~cleanup_path] is set, also change its contents to refer to the new path. *) val alias: ?cleanup_path:bool -> t -> string list -> string list -> t (** {2 Querying} *) (** Returns all bindings in the trie *) val all: t -> info list (** Lookup an identifier in a trie (eg. [option] or [List.map]) *) val get: t -> string -> info (* * Same as [get], but returns all existing bindings instead of only one. There can consistently be several if they are of different kinds (eg. a type and a value...) *) val get_all: t -> string -> info list (* * Lookup identifiers starting with the given string. Completion stops at module boundaries (it wont unfold contents of modules) *) val complete: t -> ?filter:(info -> bool) -> string -> info list (** {2 Output} *) include module type of IndexOut
(**************************************************************************) (* *) (* Copyright 2013 OCamlPro *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the Lesser GNU Public License version 3.0. *) (* *) (* 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 *) (* Lesser GNU General Public License for more details. *) (* *) (**************************************************************************)
log.ml
let src = Logs.Src.create "current.docker" ~doc:"OCurrent docker plugin" include (val Logs.src_log src : Logs.LOG)
ecm-impl.h
#ifndef _ECM_IMPL_H #define _ECM_IMPL_H 1 #include "config.h" #include "basicdefs.h" #include "ecm.h" #include "sp.h" #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> /* needed for size_t */ #endif #if HAVE_STDINT_H #include <stdint.h> /* needed for int64_t and uint64_t */ /* or configure will define these for us if possible */ #endif /* We do not use torsion.[ch] so far since they are not tested enough. */ #define HAVE_TORSION /* We do not use addlaws.[ch] so far since they are not tested enough. */ #define HAVE_ADDLAWS #include "ecm_int.h" #ifndef TUNE #include "ecm-params.h" #else extern size_t MPZMOD_THRESHOLD; extern size_t REDC_THRESHOLD; #define TUNE_MULREDC_TABLE {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} #define TUNE_SQRREDC_TABLE {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} #define LIST_MUL_TABLE {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} #endif extern size_t mpn_mul_lo_threshold[]; #define TUNE_LIST_MUL_N_MAX_SIZE 32 #include <stdio.h> /* needed for "FILE *" */ #include <limits.h> #if defined (__STDC__) \ || defined (__cplusplus) \ || defined (_AIX) \ || defined (__DECC) \ || (defined (__mips) && defined (_SYSTYPE_SVR4)) \ || defined (_MSC_VER) \ || defined (_WIN32) #define __ECM_HAVE_TOKEN_PASTE 1 #else #define __ECM_HAVE_TOKEN_PASTE 0 #endif #ifndef __ECM #if __ECM_HAVE_TOKEN_PASTE #define __ECM(x) __ecm_##x #else #define __ECM(x) __ecm_/**/x #endif #endif #define ECM_STDOUT __ecm_stdout #define ECM_STDERR __ecm_stderr extern FILE *ECM_STDOUT, *ECM_STDERR; /* #define TIMING_CRT */ /* default B2 choice: pow (B1 * METHOD_COST / 6.0, DEFAULT_B2_EXPONENT) */ #define DEFAULT_B2_EXPONENT 1.43 #define PM1_COST 1.0 / 6.0 #define PP1_COST 2.0 / 6.0 #define ECM_COST 11.0 / 6.0 /* For new P-/+1 stage 2: */ #define PM1FS2_DEFAULT_B2_EXPONENT 1.7 #define PM1FS2_COST 1.0 / 4.0 #define PP1FS2_COST 1.0 / 4.0 /* define top-level multiplication */ #define KARA 2 #define TOOM3 3 #define TOOM4 4 #define KS 5 #define NTT 6 /* maximal limb size of assembly mulredc */ #define MULREDC_ASSEMBLY_MAX 20 #include "sp.h" #include <assert.h> #define ASSERT_ALWAYS(expr) assert (expr) #ifdef WANT_ASSERT #define ASSERT(expr) assert (expr) #else #define ASSERT(expr) do {} while (0) #endif /* thresholds */ #define MPN_MUL_LO_THRESHOLD 32 /* base2mod is used when size(2^n+/-1) <= BASE2_THRESHOLD * size(cofactor) */ #define BASE2_THRESHOLD 1.4 /* default number of probable prime tests */ #define PROBAB_PRIME_TESTS 1 /* threshold for median product */ #define KS_TMUL_THRESHOLD 8e5 #define ABS(x) ((x) >= 0 ? (x) : -(x)) /* getprime */ #define WANT_FREE_PRIME_TABLE(p) (p < 0.0) #define FREE_PRIME_TABLE -1.0 /* 2^n+-1 with n < MOD_MINBASE2 cannot use base-2 reduction */ #define MOD_MINBASE2 16 /* Various logging levels */ /* OUTPUT_ALWAYS means print always, regardless of verbose value */ #define OUTPUT_ALWAYS 0 /* OUTPUT_NORMAL means print during normal program execution */ #define OUTPUT_NORMAL 1 /* OUTPUT_VERBOSE means print if the user requested more verbosity */ #define OUTPUT_VERBOSE 2 /* OUTPUT_RESVERBOSE is for printing residues (after stage 1 etc) */ #define OUTPUT_RESVERBOSE 3 /* OUTPUT_DEVVERBOSE is for printing internal parameters (for developers) */ #define OUTPUT_DEVVERBOSE 4 /* OUTPUT_TRACE is for printing trace data, produces lots of output */ #define OUTPUT_TRACE 5 /* OUTPUT_ERROR is for printing error messages */ #define OUTPUT_ERROR -1 /* Interval length for writing checkpoints in stage 1, in milliseconds */ #define CHKPNT_PERIOD 600000 /* Does the parametrization imply batch mode ? */ #define IS_BATCH_MODE(p) ( p == ECM_PARAM_BATCH_SQUARE || \ p == ECM_PARAM_BATCH_2 || \ p == ECM_PARAM_BATCH_32BITS_D ) typedef mpz_t mpres_t; typedef mpz_t* listz_t; typedef struct { mpres_t x; mpres_t y; } __point_struct; typedef __point_struct point; typedef struct { mpres_t x; mpres_t y; mpres_t A; /* for CM curves */ int disc; mpres_t sq[10]; } __curve_struct; typedef __curve_struct curve; typedef struct { unsigned long d1; unsigned long d2; mpz_t i0; int S; } __root_params_t; typedef __root_params_t root_params_t; typedef struct { unsigned long P, s_1, s_2, l; mpz_t m_1; const char *file_stem; } __faststage2_param_t; typedef __faststage2_param_t faststage2_param_t; typedef struct { unsigned int size_fd; /* How many entries .fd has, always nr * (S+1) */ unsigned int nr; /* How many separate progressions there are */ unsigned int next; /* From which progression to take the next root */ unsigned int S; /* Degree of the polynomials */ unsigned int dsieve; /* Values not coprime to dsieve are skipped */ unsigned int rsieve; /* Which residue mod dsieve current .next belongs to */ int dickson_a; /* Parameter for Dickson polynomials */ } progression_params_t; typedef struct { progression_params_t params; point *fd; unsigned int size_T; /* How many entries T has */ mpres_t *T; /* For temp values. FIXME: should go! */ curve *X; /* The curve the points are on */ } ecm_roots_state_t; typedef struct { progression_params_t params; mpres_t *fd; int invtrick; } pm1_roots_state_t; typedef struct { progression_params_t params; point *fd; /* for S != 1 */ mpres_t tmp[4]; /* for S=1 */ } pp1_roots_state_t; typedef struct { int alloc; int degree; listz_t coeff; } __polyz_struct; typedef __polyz_struct polyz_t[1]; typedef struct { int repr; /* ECM_MOD_MPZ: plain modulus, possibly normalized ECM_MOD_BASE2: base 2 number ECM_MOD_MODMULN: MODMULN ECM_MOD_REDC: REDC representation */ int bits; /* in case of a base 2 number, 2^k[+-]1, bits = [+-]k in case of MODMULN or REDC representation, nr. of bits b so that 2^b > orig_modulus and GMP_NUMB_BITS | b */ int Fermat; /* If repr = 1 (base 2 number): If modulus is 2^(2^m)+1, i.e. bits = 2^m, then Fermat = 2^m, 0 otherwise. If repr != 1, undefined */ mp_limb_t *Nprim; /* For MODMULN */ mpz_t orig_modulus; /* The original modulus N */ mpz_t aux_modulus; /* Used only for MPZ and REDC: - the auxiliary modulus value (i.e. normalized modulus, or -1/N (mod 2^bits) for REDC, - B^(n + ceil(n/2)) mod N for MPZ, where B = 2^GMP_NUMB_BITS */ mpz_t multiple; /* The smallest multiple of N that is larger or equal to 2^bits for REDC/MODMULN */ mpz_t R2, R3; /* For MODMULN and REDC, R^2 and R^3 (mod orig_modulus), where R = 2^bits. */ mpz_t temp1, temp2; /* Temp values used during multiplication etc. */ } __mpmod_struct; typedef __mpmod_struct mpmod_t[1]; #if defined (__cplusplus) extern "C" { #endif /* getprime.c */ #define getprime __ECM(getprime) double getprime (); #define getprime_clear __ECM(getprime_clear) void getprime_clear (); #define getprime_seek __ECM(getprime_seek) void getprime_seek (double); /* pm1fs2.c */ #define pm1fs2_memory_use __ECM(pm1fs2_ntt_memory_use) size_t pm1fs2_memory_use (const unsigned long, const mpz_t, const int); #define pm1fs2_maxlen __ECM(pm1fs2_maxlen) unsigned long pm1fs2_maxlen (const size_t, const mpz_t, const int); #define pp1fs2_memory_use __ECM(pp1fs2_ntt_memory_use) size_t pp1fs2_memory_use (const unsigned long, const mpz_t, const int, const int); #define pp1fs2_maxlen __ECM(pp1fs2_maxlen) unsigned long pp1fs2_maxlen (const size_t, const mpz_t, const int, const int); #define choose_P __ECM(choose_P) long choose_P (const mpz_t, const mpz_t, const unsigned long, const unsigned long, faststage2_param_t *, mpz_t, mpz_t, const int, const int); #define pm1fs2 __ECM(pm1fs2) int pm1fs2 (mpz_t, const mpres_t, mpmod_t, const faststage2_param_t *); #define pm1fs2_ntt __ECM(pm1fs2_ntt) int pm1fs2_ntt (mpz_t, const mpres_t, mpmod_t, const faststage2_param_t *); #define pp1fs2 __ECM(pp1fs2) int pp1fs2 (mpz_t, const mpres_t, mpmod_t, const faststage2_param_t *); #define pp1fs2_ntt __ECM(pp1fs2_ntt) int pp1fs2_ntt (mpz_t, const mpres_t, mpmod_t, const faststage2_param_t *, const int); /* bestd.c */ #define bestD __ECM(bestD) int bestD (root_params_t *, unsigned long *, unsigned long *, mpz_t, mpz_t, int, int, double, int, mpmod_t); /* ecm.c */ #define choose_S __ECM(choose_S) int choose_S (mpz_t); #define add3 __ECM(add3) void add3 (mpres_t, mpres_t, mpres_t, mpres_t, mpres_t, mpres_t, mpres_t, mpres_t, mpmod_t, mpres_t, mpres_t, mpres_t); #define duplicate __ECM(duplicate) void duplicate (mpres_t, mpres_t, mpres_t, mpres_t, mpmod_t, mpres_t, mpres_t, mpres_t, mpres_t); #define ecm_mul __ECM(ecm_mul) void ecm_mul (mpres_t, mpres_t, mpz_t, mpmod_t, mpres_t); #define print_B1_B2_poly __ECM(print_B1_B2_poly) void print_B1_B2_poly (int, int, double, double, mpz_t, mpz_t, mpz_t, int S, mpz_t, int, int, mpz_t, int, unsigned int); #define set_stage_2_params __ECM(set_stage_2_params) int set_stage_2_params (mpz_t, mpz_t, mpz_t, mpz_t, root_params_t *, double, unsigned long *, const int, int, int *, unsigned long *, char *, double, int, mpmod_t); #define print_expcurves __ECM(print_expcurves) void print_expcurves (double, const mpz_t, unsigned long, unsigned long, int, int); #define print_exptime __ECM(print_exptime) void print_exptime (double, const mpz_t, unsigned long, unsigned long, int, double, int); #define montgomery_to_weierstrass __ECM(montgomery_to_weierstrass) int montgomery_to_weierstrass (mpz_t, mpres_t, mpres_t, mpres_t, mpmod_t); /* ecm2.c */ #define ecm_rootsF __ECM(ecm_rootsF) int ecm_rootsF (mpz_t, listz_t, root_params_t *, unsigned long, curve *, mpmod_t); #define ecm_rootsG_init __ECM(ecm_rootsG_init) ecm_roots_state_t* ecm_rootsG_init (mpz_t, curve *, root_params_t *, unsigned long, unsigned long, mpmod_t); #define ecm_rootsG __ECM(ecm_rootsG) int ecm_rootsG (mpz_t, listz_t, unsigned long, ecm_roots_state_t *, mpmod_t); #define ecm_rootsG_clear __ECM(ecm_rootsG_clear) void ecm_rootsG_clear (ecm_roots_state_t *, mpmod_t); /* lucas.c */ #define pp1_mul_prac __ECM(pp1_mul_prac) void pp1_mul_prac (mpres_t, ecm_uint, mpmod_t, mpres_t, mpres_t, mpres_t, mpres_t, mpres_t); /* stage2.c */ #define stage2 __ECM(stage2) int stage2 (mpz_t, void *, mpmod_t, unsigned long, unsigned long, root_params_t *, int, char *, int (*)(void)); #define init_progression_coeffs __ECM(init_progression_coeffs) listz_t init_progression_coeffs (mpz_t, const unsigned long, const unsigned long, const unsigned int, const unsigned int, const unsigned int, const int); #define init_roots_params __ECM(init_roots_params) void init_roots_params (progression_params_t *, const int, const unsigned long, const unsigned long, const double); #define memory_use __ECM(memory_use) double memory_use (unsigned long, unsigned int, unsigned int, mpmod_t); /* listz.c */ #define list_mul_mem __ECM(list_mul_mem) int list_mul_mem (unsigned int); #define init_list __ECM(init_list) listz_t init_list (unsigned int); #define init_list2 __ECM(init_list2) listz_t init_list2 (unsigned int, unsigned int); #define clear_list __ECM(clear_list) void clear_list (listz_t, unsigned int); #define list_inp_raw __ECM(list_inp_raw) int list_inp_raw (listz_t, FILE *, unsigned int); #define list_out_raw __ECM(list_out_raw) int list_out_raw (FILE *, listz_t, unsigned int); #define print_list __ECM(print_list) void print_list (listz_t, unsigned int); #define list_set __ECM(list_set) void list_set (listz_t, listz_t, unsigned int); #define list_revert __ECM(list_revert) void list_revert (listz_t, unsigned int); #define list_swap __ECM(list_swap) void list_swap (listz_t, listz_t, unsigned int); #define list_neg __ECM(list_neg) void list_neg (listz_t, listz_t, unsigned int, mpz_t); #define list_mod __ECM(list_mod) void list_mod (listz_t, listz_t, unsigned int, mpz_t); #define list_add __ECM(list_add) void list_add (listz_t, listz_t, listz_t, unsigned int); #define list_sub __ECM(list_sub) void list_sub (listz_t, listz_t, listz_t, unsigned int); #define list_mul_z __ECM(list_mul_z) void list_mul_z (listz_t, listz_t, mpz_t, unsigned int, mpz_t); #define list_mulup __ECM(list_mulup) void list_mulup (listz_t, unsigned int, mpz_t, mpz_t); #define list_zero __ECM(list_zero) void list_zero (listz_t, unsigned int); #define list_mul __ECM(list_mul) void list_mul (listz_t, listz_t, unsigned int, listz_t, unsigned int, int, listz_t); #define list_mul_high __ECM(list_mul_high) void list_mul_high (listz_t, listz_t, listz_t, unsigned int); #define list_mulmod __ECM(list_mulmod) void list_mulmod (listz_t, listz_t, listz_t, listz_t, unsigned int, listz_t, mpz_t); #define PolyFromRoots __ECM(PolyFromRoots) void PolyFromRoots (listz_t, listz_t, unsigned int, listz_t, mpz_t); #define PolyFromRoots_Tree __ECM(PolyFromRoots_Tree) int PolyFromRoots_Tree (listz_t, listz_t, unsigned int, listz_t, int, mpz_t, listz_t*, FILE*, unsigned int); #define ntt_PolyFromRoots __ECM(ntt_PolyFromRoots) void ntt_PolyFromRoots (mpzv_t, mpzv_t, spv_size_t, mpzv_t, mpzspm_t); #define ntt_PolyFromRoots_Tree __ECM(ntt_PolyFromRoots_Tree) int ntt_PolyFromRoots_Tree (mpzv_t, mpzv_t, spv_size_t, mpzv_t, int, mpzspm_t, mpzv_t *, FILE *); #define ntt_polyevalT __ECM(ntt_polyevalT) int ntt_polyevalT (mpzv_t, spv_size_t, mpzv_t *, mpzv_t, mpzspv_t, mpzspm_t, char *); #define ntt_mul __ECM(ntt_mul) void ntt_mul (mpzv_t, mpzv_t, mpzv_t, spv_size_t, mpzv_t, int, mpzspm_t); #define ntt_PrerevertDivision __ECM(ntt_PrerevertDivision) void ntt_PrerevertDivision (mpzv_t, mpzv_t, mpzv_t, mpzspv_t, mpzspv_t, spv_size_t, mpzv_t, mpzspm_t); #define ntt_PolyInvert __ECM(ntt_PolyInvert) void ntt_PolyInvert (mpzv_t, mpzv_t, spv_size_t, mpzv_t, mpzspm_t); #define PrerevertDivision __ECM(PrerevertDivision) int PrerevertDivision (listz_t, listz_t, listz_t, unsigned int, listz_t, mpz_t); #define PolyInvert __ECM(PolyInvert) void PolyInvert (listz_t, listz_t, unsigned int, listz_t, mpz_t); #define RecursiveDivision __ECM(RecursiveDivision) void RecursiveDivision (listz_t, listz_t, listz_t, unsigned int, listz_t, mpz_t, int); /* polyeval.c */ #define polyeval __ECM(polyeval) void polyeval (listz_t, unsigned int, listz_t*, listz_t, mpz_t, unsigned int); #define polyeval_tellegen __ECM(polyeval_tellegen) int polyeval_tellegen (listz_t, unsigned int, listz_t*, listz_t, unsigned int, listz_t, mpz_t, char *); #define TUpTree __ECM(TUpTree) void TUpTree (listz_t, listz_t *, unsigned int, listz_t, int, unsigned int, mpz_t, FILE *); /* ks-multiply.c */ #define list_mul_n_basecase __ECM(list_mul_n_basecase) void list_mul_n_basecase (listz_t, listz_t, listz_t, unsigned int); #define list_mul_n_karatsuba __ECM(list_mul_n_karatsuba) void list_mul_n_karatsuba (listz_t, listz_t, listz_t, unsigned int); #define list_mul_n_KS1 __ECM(list_mul_n_KS1) void list_mul_n_KS1 (listz_t, listz_t, listz_t, unsigned int); #define list_mul_n_KS2 __ECM(list_mul_n_KS2) void list_mul_n_KS2 (listz_t, listz_t, listz_t, unsigned int); #define list_mult_n __ECM(list_mult_n) void list_mult_n (listz_t, listz_t, listz_t, unsigned int); #define TMulKS __ECM(TMulKS) int TMulKS (listz_t, unsigned int, listz_t, unsigned int, listz_t, unsigned int, mpz_t, int); #define ks_wrapmul_m __ECM(ks_wrapmul_m) unsigned int ks_wrapmul_m (unsigned int, unsigned int, mpz_t); #define ks_wrapmul __ECM(ks_wrapmul) unsigned int ks_wrapmul (listz_t, unsigned int, listz_t, unsigned int, listz_t, unsigned int, mpz_t); /* mpmod.c */ /* Define MPRESN_NO_ADJUSTMENT if mpresn_add, mpresn_sub and mpresn_addsub should perform no adjustment step. This yields constraints on N. */ /* #define MPRESN_NO_ADJUSTMENT */ #define isbase2 __ECM(isbase2) int isbase2 (const mpz_t, const double); #define mpmod_init __ECM(mpmod_init) int mpmod_init (mpmod_t, const mpz_t, int); #define mpmod_init_MPZ __ECM(mpmod_init_MPZ) void mpmod_init_MPZ (mpmod_t, const mpz_t); #define mpmod_init_BASE2 __ECM(mpmod_init_BASE2) int mpmod_init_BASE2 (mpmod_t, const int, const mpz_t); #define mpmod_init_MODMULN __ECM(mpmod_init_MODMULN) void mpmod_init_MODMULN (mpmod_t, const mpz_t); #define mpmod_init_REDC __ECM(mpmod_init_REDC) void mpmod_init_REDC (mpmod_t, const mpz_t); #define mpmod_clear __ECM(mpmod_clear) void mpmod_clear (mpmod_t); #define mpmod_init_set __ECM(mpmod_init_set) void mpmod_init_set (mpmod_t, const mpmod_t); #define mpmod_pausegw __ECM(mpmod_pausegw) void mpmod_pausegw (const mpmod_t modulus); #define mpmod_contgw __ECM(mpmod_contgw) void mpmod_contgw (const mpmod_t modulus); #define mpres_equal __ECM(mpres_equal) int mpres_equal (const mpres_t, const mpres_t, mpmod_t); #define mpres_pow __ECM(mpres_pow) void mpres_pow (mpres_t, const mpres_t, const mpz_t, mpmod_t); #define mpres_ui_pow __ECM(mpres_ui_pow) void mpres_ui_pow (mpres_t, const unsigned long, const mpres_t, mpmod_t); #define mpres_mul __ECM(mpres_mul) void mpres_mul (mpres_t, const mpres_t, const mpres_t, mpmod_t) ATTRIBUTE_HOT; #define mpres_sqr __ECM(mpres_sqr) void mpres_sqr (mpres_t, const mpres_t, mpmod_t) ATTRIBUTE_HOT; #define mpres_mul_z_to_z __ECM(mpres_mul_z_to_z) void mpres_mul_z_to_z (mpz_t, const mpres_t, const mpz_t, mpmod_t); #define mpres_set_z_for_gcd __ECM(mpres_set_z_for_gcd) void mpres_set_z_for_gcd (mpres_t, const mpz_t, mpmod_t); #define mpres_set_z_for_gcd_fix __ECM(mpres_set_z_for_gcd_fix) void mpres_set_z_for_gcd_fix (mpres_t, const mpres_t, const mpz_t, mpmod_t); #define mpres_div_2exp __ECM(mpres_div_2exp) void mpres_div_2exp (mpres_t, const mpres_t, const unsigned int, mpmod_t); #define mpres_add_ui __ECM(mpres_add_ui) void mpres_add_ui (mpres_t, const mpres_t, const unsigned long, mpmod_t); #define mpres_add __ECM(mpres_add) void mpres_add (mpres_t, const mpres_t, const mpres_t, mpmod_t) ATTRIBUTE_HOT; #define mpres_sub_ui __ECM(mpres_sub_ui) void mpres_sub_ui (mpres_t, const mpres_t, const unsigned long, mpmod_t); #define mpres_ui_sub __ECM(mpres_ui_sub) void mpres_ui_sub (mpres_t, const unsigned long, const mpres_t, mpmod_t); #define mpres_sub __ECM(mpres_sub) void mpres_sub (mpres_t, const mpres_t, const mpres_t, mpmod_t) ATTRIBUTE_HOT; #define mpres_set_z __ECM(mpres_set_z) void mpres_set_z (mpres_t, const mpz_t, mpmod_t); #define mpres_get_z __ECM(mpres_get_z) void mpres_get_z (mpz_t, const mpres_t, mpmod_t); #define mpres_set_ui __ECM(mpres_set_ui) void mpres_set_ui (mpres_t, const unsigned long, mpmod_t); #define mpres_set_si __ECM(mpres_set_si) void mpres_set_si (mpres_t, const long, mpmod_t); #define mpres_init __ECM(mpres_init) void mpres_init (mpres_t, const mpmod_t); #define mpres_clear __ECM(mpres_clear) void mpres_clear (mpres_t, const mpmod_t); #define mpres_realloc __ECM(mpres_realloc) void mpres_realloc (mpres_t, const mpmod_t); #define mpres_mul_ui __ECM(mpres_mul_ui) void mpres_mul_ui (mpres_t, const mpres_t, const unsigned long, mpmod_t); #define mpres_mul_2exp __ECM(mpres_mul_2exp) void mpres_mul_2exp (mpres_t, const mpres_t, const unsigned long, mpmod_t); #define mpres_muldivbysomething_si __ECM(mpres_muldivbysomething_si) void mpres_muldivbysomething_si (mpres_t, const mpres_t, const long, mpmod_t); #define mpres_neg __ECM(mpres_neg) void mpres_neg (mpres_t, const mpres_t, mpmod_t); #define mpres_invert __ECM(mpres_invert) int mpres_invert (mpres_t, const mpres_t, mpmod_t); #define mpres_gcd __ECM(mpres_gcd) void mpres_gcd (mpz_t, const mpres_t, const mpmod_t); #define mpres_out_str __ECM(mpres_out_str) void mpres_out_str (FILE *, const unsigned int, const mpres_t, mpmod_t); #define mpres_is_zero __ECM(mpres_is_zero) int mpres_is_zero (const mpres_t, mpmod_t); #define mpres_set(a,b,n) mpz_set (a, b) #define mpres_swap(a,b,n) mpz_swap (a, b) #define mpresn_mul __ECM(mpresn_mul) void mpresn_mul (mpres_t, const mpres_t, const mpres_t, mpmod_t); #define mpresn_addsub __ECM(mpresn_addsub) void mpresn_addsub (mpres_t, mpres_t, const mpres_t, const mpres_t, mpmod_t); #define mpresn_pad __ECM(mpresn_pad) void mpresn_pad (mpres_t R, mpmod_t N); #define mpresn_unpad __ECM(mpresn_unpad) void mpresn_unpad (mpres_t R); #define mpresn_sqr __ECM(mpresn_sqr) void mpresn_sqr (mpres_t, const mpres_t, mpmod_t); #define mpresn_add __ECM(mpresn_add) void mpresn_add (mpres_t, const mpres_t, const mpres_t, mpmod_t); #define mpresn_sub __ECM(mpresn_sub) void mpresn_sub (mpres_t, const mpres_t, const mpres_t, mpmod_t); #define mpresn_mul_1 __ECM(mpresn_mul_ui) void mpresn_mul_1 (mpres_t, const mpres_t, const mp_limb_t, mpmod_t); /* mul_lo.c */ #define ecm_mul_lo_n __ECM(ecm_mul_lo_n) void ecm_mul_lo_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define ecm_mul_lo_basecase __ECM(ecm_mul_lo_basecase) void ecm_mul_lo_basecase (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); /* median.c */ #define TMulGen __ECM(TMulGen) int TMulGen (listz_t, unsigned int, listz_t, unsigned int, listz_t, unsigned int, listz_t, mpz_t); #define TMulGen_space __ECM(TMulGen_space) unsigned int TMulGen_space (unsigned int, unsigned int, unsigned int); /* schoen_strass.c */ #define DEFAULT 0 #define MONIC 1 #define NOPAD 2 #define F_mul __ECM(F_mul) unsigned int F_mul (mpz_t *, mpz_t *, mpz_t *, unsigned int, int, unsigned int, mpz_t *); #define F_mul_trans __ECM(F_mul_trans) unsigned int F_mul_trans (mpz_t *, mpz_t *, mpz_t *, unsigned int, unsigned int, unsigned int, mpz_t *); #define F_clear __ECM(F_clear) void F_clear (); /* rho.c */ #define rhoinit __ECM(rhoinit) void rhoinit (int, int); #define ecmprob __ECM(ecmprob) double ecmprob (double, double, double, double, int); double pm1prob (double, double, double, double, int, const mpz_t); /* pm1.c */ void print_prob (double, const mpz_t, unsigned long, unsigned long, int, const mpz_t); /* auxlib.c */ #define mpz_add_si __ECM(mpz_add_si) void mpz_add_si (mpz_t, mpz_t, long); #define mpz_sub_si __ECM(mpz_sub_si) void mpz_sub_si (mpz_t, mpz_t, long); #define mpz_divby3_1op __ECM(mpz_divby3_1op) void mpz_divby3_1op (mpz_t); #define double_to_size __ECM(double_to_size) size_t double_to_size (double d); #define cputime __ECM(cputime) long cputime (void); #define realtime __ECM(realtime) long realtime (void); #define elltime __ECM(elltime) long elltime (long, long); #define test_verbose __ECM(test_verbose) int test_verbose (int); #define set_verbose __ECM(set_verbose) void set_verbose (int); #define outputf __ECM(outputf) int outputf (int, const char *, ...); #define writechkfile __ECM(writechkfile) void writechkfile (char *, int, double, mpmod_t, mpres_t, mpres_t, mpres_t, mpres_t); #define aux_fseek64 __ECM(aux_fseek64) int aux_fseek64(FILE *, const int64_t, const int); #define ecm_tstbit __ECM(ecm_tstbit) int ecm_tstbit (mpz_srcptr, ecm_uint); /* Due to GMP (6.x and prior) using long as input to mpz_tstbit, factors would be missed on computers with 32-bit longs in batch mode when using B1 > 2977044736UL. So, we need to use our own function when long is not 64-bits wide */ #if ULONG_MAX == 0xffffffffUL #undef mpz_tstbit #define mpz_tstbit ecm_tstbit #endif /* auxarith.c */ #define gcd __ECM(gcd) unsigned long gcd (unsigned long, unsigned long); #define eulerphi __ECM(eulerphi) unsigned long eulerphi (unsigned long); #define ceil_log2 __ECM(ceil_log2) unsigned int ceil_log2 (unsigned long); #define find_factor __ECM(find_factor) unsigned long find_factor (const unsigned long); /* random.c */ #define init_randstate __ECM(init_randstate) void init_randstate (gmp_randstate_t); #define pp1_random_seed __ECM(pp1_random_seed) void pp1_random_seed (mpz_t, mpz_t, gmp_randstate_t); #define pm1_random_seed __ECM(pm1_random_seed) void pm1_random_seed (mpz_t, mpz_t, gmp_randstate_t); #define get_random_ul __ECM(get_random_ul) unsigned long get_random_ul (void); /* Fgw.c */ #ifdef HAVE_GWNUM int gw_ecm_stage1 (mpz_t, curve *, mpmod_t, double, double *, mpz_t, double, unsigned long, unsigned long, signed long); #endif /* batch.c */ #define compute_s __ECM(compute_s ) void compute_s (mpz_t, ecm_uint, int *); #define ecm_stage1_batch __ECM(ecm_stage1_batch) int ecm_stage1_batch (mpz_t, mpres_t, mpres_t, mpmod_t, double, double *, int, mpz_t); /* parametrizations.c */ #define get_curve_from_random_parameter __ECM(get_curve_from_random_parameter) int get_curve_from_random_parameter (mpz_t, mpres_t, mpres_t, mpz_t, int, mpmod_t, gmp_randstate_t); #define get_curve_from_param0 __ECM(get_curve_from_param0) int get_curve_from_param0 (mpz_t, mpres_t, mpres_t, mpz_t, mpmod_t); #define get_curve_from_param1 __ECM(get_curve_from_param1) int get_curve_from_param1 (mpres_t, mpres_t, mpz_t, mpmod_t); #define get_curve_from_param2 __ECM(get_curve_from_param2) int get_curve_from_param2 (mpz_t, mpres_t, mpres_t, mpz_t, mpmod_t); #define get_curve_from_param3 __ECM(get_curve_from_param3) int get_curve_from_param3 (mpres_t, mpres_t, mpz_t, mpmod_t); #define get_default_param __ECM(get_default_param) int get_default_param (int, double, int); /* sets_long.c */ /* A set of long ints */ typedef struct { unsigned long card; long elem[1]; } set_long_t; /* A set of sets of long ints */ typedef struct { unsigned long nr; set_long_t sets[1]; } sets_long_t; #define quicksort_long __ECM(quicksort_long) void quicksort_long (long *, unsigned long); #define sets_print __ECM(sets_print) void sets_print (const int, sets_long_t *); #define sets_max __ECM(sets_max) void sets_max (mpz_t, const unsigned long); #define sets_sumset __ECM(sets_sumset) void sets_sumset (set_long_t *, const sets_long_t *); #define sets_sumset_minmax __ECM(sets_sumset_minmax) void sets_sumset_minmax (mpz_t, const sets_long_t *, const int); #define sets_extract __ECM(sets_extract) void sets_extract (sets_long_t *, size_t *, sets_long_t *, const unsigned long); #define sets_get_factored_sorted __ECM(sets_get_factored_sorted) sets_long_t * sets_get_factored_sorted (const unsigned long); /* Return the size in bytes of a set of cardinality c */ #define set_sizeof __ECM(set_sizeof) ATTRIBUTE_UNUSED static size_t set_sizeof (const unsigned long c) { return sizeof (long) + (size_t) c * sizeof (unsigned long); } /* Return pointer to the next set in "*sets" */ ATTRIBUTE_UNUSED static set_long_t * sets_nextset (const set_long_t *sets) { return (set_long_t *) ((char *)sets + sizeof(unsigned long) + sets->card * sizeof(long)); } #if defined (__cplusplus) } #endif /* a <- b * c where a and b are mpz, c is a double, and t an auxiliary mpz */ /* Not sure how the preprocessor handles shifts by more than the integer width on 32 bit machines, so do the shift by 53 in two pieces */ #if (((ULONG_MAX >> 27) >> 26) >= 1) #define mpz_mul_d(a, b, c, t) \ mpz_mul_ui (a, b, (unsigned long int) c); #else #define mpz_mul_d(a, b, c, t) \ if (c < (double) ULONG_MAX) \ mpz_mul_ui (a, b, (unsigned long int) c); \ else { \ mpz_set_d (t, c); \ mpz_mul (a, b, t); } #endif #endif /* _ECM_IMPL_H */
/* ecm-impl.h - header file for libecm Copyright 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Paul Zimmermann, Alexander Kruppa and Cyril Bouvier. This file is part of the ECM Library. The ECM Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. The ECM Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the ECM Library; see the file COPYING.LIB. If not, see http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
test.ml
module I = struct type t = int let compare = Stdlib.compare end module B = Bag.Make(I) let () = let a = B.add 1 ~mult:1 (B.add 2 ~mult:2 (B.add 3 ~mult:3 B.empty)) in let b = B.add 1 ~mult:4 (B.add 2 ~mult:5 (B.add 3 ~mult:6 B.empty)) in assert (B.cardinal a = 6); assert (B.cardinal (B.sum a b) = 21); assert (B.cardinal (B.union a b) = 15); assert (B.is_empty (B.diff a b)); assert (B.cardinal (B.diff b a) = 9); assert (B.equal (B.inter a b) a); assert (B.included a b); assert (not (B.included b a)); assert (not (B.disjoint b a)); assert (B.elements a = [1,1; 2,2; 3,3]); assert (B.min_elt a = (1,1)); assert (B.max_elt a = (3,3)); let f _ = 1 in assert (B.cardinal (B.map f a) = 3); assert (B.cardinal (B.map f b) = 3); let e = B.filter (fun x _ -> x mod 2 = 0) a in assert (B.min_elt e = (2,2)); assert (B.max_elt e = (2,2)); assert (B.choose e = (2,2)); assert (B.cardinal e = 2); let o = B.filter (fun x _ -> x mod 2 = 1) b in assert (B.min_elt o = (1,4)); assert (B.max_elt o = (3,6)); assert (B.cardinal o = 10); () let test n = let b1 = ref B.empty in let b2 = ref B.empty in for x = 0 to n do b1 := B.add x ~mult:2 !b1; assert (B.cardinal !b1 = 2*(x+1)); b2 := B.add (n-x) !b2; assert (B.cardinal !b2 = 2*x+1); b2 := B.add (n-x) !b2; if x < n/2 then assert (B.disjoint !b1 !b2) done; assert (B.mem n !b1); assert (B.occ n !b1 = 2); assert (B.cardinal !b1 = 2*(n+1)); assert (B.cardinal !b2 = 2*(n+1)); assert (B.equal !b1 !b2); assert (B.for_all (fun x _ -> x <= n) !b1); assert (not (B.for_all (fun x _ -> x < n) !b1)); assert (B.exists (fun x m -> x = 0 && m = 2) !b2); for x = 0 to n do b1 := B.remove_all x !b1; b2 := B.remove (n-x) ~mult:2 !b2; done; assert (B.is_empty !b1); assert (B.is_empty !b2); () let () = for n = 0 to 10 do test (10 * n) done
ast.ml
(* This file is free software, part of dolmen. See file "LICENSE" for more information. *) (** AST requirements for the iCNF format. iCNF is a very simple format intended to express CNFs (conjunctive normal forms) in the simplest format possible. Compared to dimacs, iCNF allows local assumptions, and does not require to declare the number of clauses and formulas. *) module type Term = sig type t (** The type of terms. *) type location (** The type of locations. *) val atom : ?loc:location -> int -> t (** Make an atom from an non-zero integer. Positive integers denotes variables, and negative integers denote the negation of the variable corresponding to their absolute value. *) end (** Requirements for implementations of Dimacs terms. *) module type Statement = sig type t (** The type of statements for iCNF. *) type term (** The type of iCNF terms. *) type location (** The type of locations. *) val p_inccnf : ?loc:location -> unit -> t (** header of an iCNF file. *) val clause : ?loc:location -> term list -> t (** Make a clause from a list of literals. *) val assumption : ?loc:location -> term list -> t (** Generate a solve instruction with the given list of assumptions. *) end (** Requirements for implementations of iCNF statements. *)
Header.ml
open Utils type t = { alg : Jwa.alg; jwk : Jwk.public Jwk.t option; kid : string option; x5t : string option; x5t256 : string option; typ : string option; cty : string option; enc : Jwa.enc option; extra : (string * Yojson.Safe.t) list; } (* TODO: This is probably very slow *) let remove_supported (l : (string * Yojson.Safe.t) list) = l |> List.remove_assoc "alg" |> List.remove_assoc "jwk" |> List.remove_assoc "kid" |> List.remove_assoc "x5t" |> List.remove_assoc "x5t#256" |> List.remove_assoc "typ" |> List.remove_assoc "cty" |> List.remove_assoc "enc" let make_header ?typ ?alg ?enc ?(extra = []) ?(jwk_header = false) (jwk : Jwk.priv Jwk.t) = let alg = match alg with | Some alg -> alg | None -> ( match jwk with | Jwk.Rsa_priv _ -> `RS256 | Jwk.Oct _ -> `HS256 | Jwk.Es256_priv _ -> `ES256 | Jwk.Es384_priv _ -> `ES384 | Jwk.Es512_priv _ -> `ES512 | Jwk.Ed25519_priv _ -> `EdDSA) in let kid = match List.assoc_opt "kid" extra with | Some kid -> Some (Yojson.Safe.Util.to_string kid) | None -> Jwk.get_kid jwk in let extra = remove_supported extra in { alg; jwk = (if jwk_header then Some (Jwk.pub_of_priv jwk) else None); kid; x5t = None; x5t256 = None; typ; cty = None; enc; extra; } module Json = Yojson.Safe.Util let get_extra_headers (json : Yojson.Safe.t) = match json with | `Assoc vals -> ( let extra = remove_supported vals in match extra with [] -> [] | extra -> extra) | _ -> [] (* TODO: raise here? *) let of_json json = try Ok { alg = json |> Json.member "alg" |> Jwa.alg_of_json; jwk = json |> Json.member "jwk" |> Json.to_option (fun jwk_json -> Jwk.of_pub_json jwk_json |> U_Result.to_opt) |> U_Opt.flatten; kid = json |> Json.member "kid" |> Json.to_string_option; x5t = json |> Json.member "x5t" |> Json.to_string_option; x5t256 = json |> Json.member "x5t#256" |> Json.to_string_option; typ = json |> Json.member "typ" |> Json.to_string_option; cty = json |> Json.member "cty" |> Json.to_string_option; enc = json |> Json.member "enc" |> Json.to_string_option |> U_Opt.map Jwa.enc_of_string; extra = get_extra_headers json; } with Json.Type_error (s, _) -> Error (`Msg s) let to_json t = let values = [ RJson.to_json_string_opt "typ" t.typ; Some ("alg", Jwa.alg_to_json t.alg); RJson.to_json_string_opt "kid" t.kid; U_Opt.map Jwk.to_pub_json t.jwk |> U_Opt.map (fun jwk -> ("jwk", jwk)); RJson.to_json_string_opt "x5t" t.x5t; RJson.to_json_string_opt "x5t#256" t.x5t256; RJson.to_json_string_opt "cty" t.cty; t.enc |> U_Opt.map Jwa.enc_to_string |> U_Opt.map (fun enc -> ("enc", `String enc)); ] in `Assoc (U_List.filter_map (fun x -> x) values @ t.extra) let of_string header_str = U_Base64.url_decode header_str |> U_Result.flat_map (fun decoded_header -> Yojson.Safe.from_string decoded_header |> of_json) let to_string header = to_json header |> Yojson.Safe.to_string |> U_Base64.url_encode_string
global_litmus.mli
(** Global locations for litmus *) type t = Addr of string | Pte of string | Phy of string val pp_old : t -> string val pp : t -> string val compare : t -> t -> int val as_addr : t -> string (* assert false if not an addr *) val tr_symbol : Constant.symbol -> t module Set : MySet.S with type elt = t module Map : MyMap.S with type key = t type displayed = string ConstrGen.rloc val dump_displayed : displayed -> string module DisplayedSet : MySet.S with type elt = displayed
(****************************************************************************) (* 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. *) (****************************************************************************)
test_mysql.ml
(** *) open Rdf open Graph let string_of_triple (sub, pred, obj) = Printf.sprintf "%s %s %s." (Term.string_of_term sub) (Iri.to_string pred) (Term.string_of_term obj) ;; let main () = let options = [ "storage", "mysql" ; "database", "testrdf"; "user", Sys.getenv "USER"; ] in let g = Graph.open_graph ~options (Iri.of_string "http://hello.fr") in let pred = Iri.of_string "http://dis-bonjour.org" in let obj = Term.term_of_literal_string "youpi" in let sub = Term.term_of_iri_string "http://coucou0.net" in for i = 0 to 10 do g.add_triple ~sub: (Term.term_of_iri_string (Printf.sprintf "http://coucou%d.net" i)) ~pred ~obj done; g.rem_triple ~sub: (Term.term_of_iri_string "http://coucou3.net") ~pred ~obj; let subjects = g.subjects_of ~pred ~obj in List.iter (fun term -> print_endline (Term.string_of_term term)) subjects; let b = g.exists_t (sub, pred, obj) in assert b; let b = g.exists ~sub ~obj () in assert b; let b = not (g.exists ~obj: (Term.term_of_iri_string "http://") ()) in assert b; let triples = g.find () in List.iter (fun t -> print_endline (string_of_triple t)) triples; let subjects = g.subjects () in List.iter (fun term -> print_endline (Term.string_of_term term)) subjects; let sub4 = Term.term_of_iri_string "http://coucou4.net" in g.transaction_start (); g.rem_triple ~sub: sub4 ~pred ~obj; assert (not (g.exists_t (sub4, pred, obj))); g.transaction_rollback (); assert (g.exists_t (sub4, pred, obj)); g.add_namespace (Iri.of_string "http://dis-bonjour.org") "bonjour" ; g.add_namespace (Iri.of_string "http://coucou1.net") "coucou1" ; print_endline (Ttl.to_string g); g.rem_namespace "coucou1"; g.rem_namespace "coucou2"; g.set_namespaces [ (Iri.of_string "http://coucou3.net", "coucou3"); (Iri.of_string "http://coucou4.net", "coucou4"); ]; print_endline (Ttl.to_string g); ;; let () = main();;
(*********************************************************************************) (* OCaml-RDF *) (* *) (* Copyright (C) 2012-2021 Institut National de Recherche en Informatique *) (* et en Automatique. All rights reserved. *) (* *) (* This program is free software; you can redistribute it and/or modify *) (* it under the terms of the GNU Lesser General Public License version *) (* 3 as published by the Free Software Foundation. *) (* *) (* This program is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU General Public License for more details. *) (* *) (* You should have received a copy of the GNU General Public License *) (* along with this program; if not, write to the Free Software *) (* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA *) (* 02111-1307 USA *) (* *) (* Contact: Maxence.Guesdon@inria.fr *) (* *) (*********************************************************************************)
bar.ml
int64.mli
(** 64-bit integers. *) open! Import include Int_intf.S with type t = int64 module O : sig (*_ Declared as externals so that the compiler skips the caml_apply_X wrapping even when compiling without cross library inlining. *) external ( + ) : t -> t -> t = "%int64_add" external ( - ) : t -> t -> t = "%int64_sub" external ( * ) : t -> t -> t = "%int64_mul" external ( / ) : t -> t -> t = "%int64_div" external ( ~- ) : t -> t = "%int64_neg" val ( ** ) : t -> t -> t external ( = ) : t -> t -> bool = "%equal" external ( <> ) : t -> t -> bool = "%notequal" external ( < ) : t -> t -> bool = "%lessthan" external ( > ) : t -> t -> bool = "%greaterthan" external ( <= ) : t -> t -> bool = "%lessequal" external ( >= ) : t -> t -> bool = "%greaterequal" external ( land ) : t -> t -> t = "%int64_and" external ( lor ) : t -> t -> t = "%int64_or" external ( lxor ) : t -> t -> t = "%int64_xor" val lnot : t -> t val abs : t -> t external neg : t -> t = "%int64_neg" val zero : t val ( % ) : t -> t -> t val ( /% ) : t -> t -> t val ( // ) : t -> t -> float external ( lsl ) : t -> int -> t = "%int64_lsl" external ( asr ) : t -> int -> t = "%int64_asr" external ( lsr ) : t -> int -> t = "%int64_lsr" end include module type of O (** {2 Conversion functions} *) (*_ Declared as externals so that the compiler skips the caml_apply_X wrapping even when compiling without cross library inlining. *) external of_int : int -> t = "%int64_of_int" external of_int32 : int32 -> t = "%int64_of_int32" external of_int64 : t -> t = "%identity" val to_int : t -> int option val to_int32 : t -> int32 option val of_nativeint : nativeint -> t val to_nativeint : t -> nativeint option (** {3 Truncating conversions} These functions return the least-significant bits of the input. In cases where optional conversions return [Some x], truncating conversions return [x]. *) (*_ Declared as externals so that the compiler skips the caml_apply_X wrapping even when compiling without cross library inlining. *) external to_int_trunc : t -> int = "%int64_to_int" external to_int32_trunc : int64 -> int32 = "%int64_to_int32" external to_nativeint_trunc : int64 -> nativeint = "%int64_to_nativeint" (** {3 Low-level float conversions} *) val bits_of_float : float -> t val float_of_bits : t -> float (** {2 Byte swap operations} See {{!modtype:Int.Int_without_module_types}[Int]'s byte swap section} for a description of Base's approach to exposing byte swap primitives. As of writing, these operations do not sign extend unnecessarily on 64 bit machines, unlike their int32 counterparts, and hence, are more performant. See the {!Int32} module for more details of the overhead entailed by the int32 byteswap functions. *) val bswap16 : t -> t val bswap32 : t -> t val bswap48 : t -> t (*_ Declared as an external so that the compiler skips the caml_apply_X wrapping even when compiling without cross library inlining. *) external bswap64 : t -> t = "%bswap_int64"
(** 64-bit integers. *)
intersectionObserver.mli
(** The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport. https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API *) class type intersectionObserverEntry = object method target : Dom.node Js.t Js.readonly_prop method boundingClientRect : Dom_html.clientRect Js.t Js.readonly_prop method rootBounds : Dom_html.clientRect Js.t Js.opt Js.readonly_prop method intersectionRect : Dom_html.clientRect Js.t Js.readonly_prop method intersectionRatio : float Js.readonly_prop method isIntersecting : bool Js.t Js.readonly_prop method time : float Js.readonly_prop end class type intersectionObserverOptions = object method root : Dom.node Js.t Js.writeonly_prop method rootMargin : Js.js_string Js.t Js.writeonly_prop method threshold : float Js.js_array Js.t Js.writeonly_prop end class type intersectionObserver = object method root : Dom.node Js.t Js.opt Js.readonly_prop method rootMargin : Js.js_string Js.t Js.readonly_prop method thresholds : float Js.js_array Js.t Js.readonly_prop method observe : #Dom.node Js.t -> unit Js.meth method unobserve : #Dom.node Js.t -> unit Js.meth method disconnect : unit Js.meth method takeRecords : intersectionObserverEntry Js.t Js.js_array Js.meth end val empty_intersection_observer_options : unit -> intersectionObserverOptions Js.t val is_supported : unit -> bool val intersectionObserver : ( ( intersectionObserverEntry Js.t Js.js_array Js.t -> intersectionObserver Js.t -> unit) Js.callback -> intersectionObserverOptions Js.t -> intersectionObserver Js.t) Js.constr
(** The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport. https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API *)
test_paid_storage_increase.ml
(** Testing ------- Component: Protocol (increase_paid_storage) Invocation: dune exec \ src/proto_alpha/lib_protocol/test/integration/operations/main.exe \ -- test "^paid storage increase$" Subject: On increasing a paid amount of contract storage. *) open Protocol open Alpha_context let ten_tez = Test_tez.of_int 10 let dummy_script = "{parameter unit; storage unit; code { CAR ; NIL operation ; PAIR }}" let contract_originate block ?(script = dummy_script) ?(storage = Expr.from_string "Unit") account = let open Lwt_result_syntax in let code = Expr.from_string script in let script = Alpha_context.Script.{code = lazy_expr code; storage = lazy_expr storage} in let source_contract = account in let baker = Context.Contract.pkh account in let* op, dst = Op.contract_origination_hash (B block) source_contract ~fee:Tez.zero ~script in let* inc = Incremental.begin_construction ~policy:Block.(By_account baker) block in let* inc = Incremental.add_operation inc op in let+ b = Incremental.finalize_block inc in (b, dst) (** [test_balances] runs a simple [increase_paid_storage] and verifies that the source contract balance is correct and that the storage of the destination contract has been increased by the right amount. *) let test_balances ~amount = let open Lwt_result_syntax in let* b, source = Context.init1 () in let* b, destination = contract_originate b source in let* inc = Incremental.begin_construction b in let* balance_before_op = Context.Contract.balance (I inc) source in let contract_dst = Contract.Originated destination in let*! storage_before_op = Contract.Internal_for_tests.paid_storage_space (Incremental.alpha_ctxt inc) contract_dst in let* storage_before_op = Lwt.return (Environment.wrap_tzresult storage_before_op) in let* op = Op.increase_paid_storage ~fee:Tez.zero (I inc) ~source ~destination amount in let* inc = Incremental.add_operation inc op in (* check that after the block has been baked, the source was debited of all the burned tez *) let* {parametric = {cost_per_byte; _}; _} = Context.get_constants (I inc) in let burned_tez = Tez.mul_exn cost_per_byte (Z.to_int amount) in let* () = Assert.balance_was_debited ~loc:__LOC__ (I inc) source balance_before_op burned_tez in (* check that the storage has been increased by the right amount *) let*! storage = Contract.Internal_for_tests.paid_storage_space (Incremental.alpha_ctxt inc) contract_dst in let* storage = Lwt.return (Environment.wrap_tzresult storage) in let storage_minus_amount = Z.sub storage amount in Assert.equal_int ~loc:__LOC__ (Z.to_int storage_before_op) (Z.to_int storage_minus_amount) (******************************************************) (* Tests *) (******************************************************) (** Basic test. We test balances in simple cases. *) let test_balances_simple () = test_balances ~amount:(Z.of_int 100) (******************************************************) (* Errors *) (******************************************************) (** We test the operation when the amount given is null. *) let test_null_amount () = let open Lwt_result_syntax in let*! result = test_balances ~amount:Z.zero in Assert.proto_error ~loc:__LOC__ result (function | Fees_storage.Negative_storage_input -> true | _ -> false) (** We test the operation when the amount given is negative. *) let test_negative_amount () = let open Lwt_result_syntax in let amount = Z.of_int (-10) in let*! result = test_balances ~amount in Assert.proto_error ~loc:__LOC__ result (function | Fees_storage.Negative_storage_input -> true | _ -> false) (** We create an implicit account with not enough tez to pay for the storage increase. *) let test_no_tez_to_pay () = let open Lwt_result_syntax in let* b, (source, baker, receiver) = Context.init3 ~consensus_threshold:0 () in let* b, destination = contract_originate b source in let pkh_for_bake = Context.Contract.pkh baker in let* inc = Incremental.begin_construction ~policy:Block.(By_account pkh_for_bake) b in let* {parametric = {cost_per_byte; _}; _} = Context.get_constants (I inc) in let increase_amount = Z.div (Z.of_int 2_000_000) (Z.of_int64 (Tez.to_mutez cost_per_byte)) in let* balance = Context.Contract.balance (I inc) source in let*? tez_to_substract = Test_tez.(balance -? Tez.one) in let* op = Op.transaction (I inc) ~fee:Tez.zero source receiver tez_to_substract in let* inc = Incremental.add_operation inc op in let* b = Incremental.finalize_block inc in let* inc = Incremental.begin_construction ~policy:Block.(By_account pkh_for_bake) b in let* op = Op.increase_paid_storage (I inc) ~source ~destination increase_amount in let*! inc = Incremental.add_operation inc op in Assert.proto_error ~loc:__LOC__ inc (function | Fees_storage.Cannot_pay_storage_fee -> true | _ -> false) (** To test when there is no smart contract at the address given. *) let test_no_contract () = let open Lwt_result_syntax in let* b, source = Context.init1 () in let* inc = Incremental.begin_construction b in let destination = Contract_helpers.fake_KT1 in let* op = Op.increase_paid_storage (I inc) ~source ~destination Z.zero in let*! inc = Incremental.add_operation inc op in Assert.proto_error ~loc:__LOC__ inc (function | Raw_context.Storage_error (Missing_key (_, Raw_context.Get)) -> true | _ -> false) (** To test if the increase in storage is effective. *) let test_effectiveness () = let open Lwt_result_syntax in let* b, (source, _contract_source) = Context.init2 ~consensus_threshold:0 () in let script = "{parameter unit; storage int; code { CDR ; PUSH int 65536 ; MUL ; NIL \ operation ; PAIR }}" in let storage = Tezos_micheline.Micheline.strip_locations (Expr_common.int Z.one) in let* b, destination = contract_originate ~script ~storage b source in let* inc = Incremental.begin_construction b in (* We ensure that the transaction can't be made with a 0 burn cap. *) let contract_dst = Contract.Originated destination in let* op = Op.transaction ~storage_limit:Z.zero ~fee:Tez.zero (I inc) source contract_dst Tez.zero in let*! inc_test = Incremental.add_operation inc op in let* () = Assert.proto_error ~loc:__LOC__ inc_test (function | Fees.Operation_quota_exceeded -> true | _ -> false) in let* b = Incremental.finalize_block inc in let* inc = Incremental.begin_construction b in let* op = Op.increase_paid_storage (I inc) ~fee:Tez.zero ~source ~destination (Z.of_int 10) in let* inc = Incremental.add_operation inc op in let* b = Incremental.finalize_block inc in let* inc = Incremental.begin_construction b in (* We test the same transaction to see if increase_paid_storage worked. *) let* op = Op.transaction ~storage_limit:Z.zero ~fee:Tez.zero (I inc) source contract_dst Tez.zero in let+ _inc = Incremental.add_operation inc op in () let tests = [ Tztest.tztest "balances simple" `Quick test_balances_simple; Tztest.tztest "null amount" `Quick test_null_amount; Tztest.tztest "negative amount" `Quick test_negative_amount; Tztest.tztest "not enough tez to pay" `Quick test_no_tez_to_pay; Tztest.tztest "no contract to bump its paid storage" `Quick test_no_contract; Tztest.tztest "effectiveness" `Quick test_effectiveness; ]
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2022 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
dune
pg_ts_config.h
#ifndef PG_TS_CONFIG_H #define PG_TS_CONFIG_H #include "catalog/genbki.h" #include "catalog/pg_ts_config_d.h" /* ---------------- * pg_ts_config definition. cpp turns this into * typedef struct FormData_pg_ts_config * ---------------- */ CATALOG(pg_ts_config,3602,TSConfigRelationId) { /* oid */ Oid oid; /* name of configuration */ NameData cfgname; /* name space */ Oid cfgnamespace BKI_DEFAULT(PGNSP); /* owner */ Oid cfgowner BKI_DEFAULT(PGUID); /* OID of parser */ Oid cfgparser BKI_LOOKUP(pg_ts_parser); } FormData_pg_ts_config; typedef FormData_pg_ts_config *Form_pg_ts_config; #endif /* PG_TS_CONFIG_H */
/*------------------------------------------------------------------------- * * pg_ts_config.h * definition of the "text search configuration" system catalog * (pg_ts_config) * * * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * src/include/catalog/pg_ts_config.h * * NOTES * The Catalog.pm module reads this file and derives schema * information. * *------------------------------------------------------------------------- */
queue.mli
include Queue_intf.Queue (** @inline *)
include Queue_intf.Queue (** @inline *)
equality_witness.mli
(** This module provides support for type equalities and runtime type identifiers. For two types [a] and [b], [(a, b) eq] is a witness that [a = b]. This is a standard generalized algebraic datatype on top of which type-level programming techniques can be implemented. Given a type [a], an inhabitant of [a t] is a dynamic identifier for [a]. Identifiers can be compared for equality. They are also equipped with a hash function. WARNING: the hash function changes at every run. Therefore, the result of the hash function should never be stored. Notice that dynamic identifiers are not unique: two identifiers for [a] can have distinct hash and can be physically distinct. Hence, only [eq] can decide if two type identifiers correspond to the same type. *) (** A proof witness that two types are equal. *) type (_, _) eq = Refl : ('a, 'a) eq (** A dynamic representation for ['a]. *) type 'a t (** [make ()] is a dynamic representation for ['a]. A fresh identifier is returned each time [make ()] is evaluated. *) val make : unit -> 'a t (** [eq ida idb] returns a proof that [a = b] if [ida] and [idb] identify the same type. *) val eq : 'a t -> 'b t -> ('a, 'b) eq option (** [hash id] returns a hash for [id]. *) val hash : 'a t -> int
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
irTransform.mli
type state = { context: Context.t; primitive_vars: Utility.IntSet.t; datatype: Types.datatype } type result = Result of { state: state; program: Ir.program } val context : state -> Context.t val return : state -> Ir.program -> result val with_type : Types.datatype -> state -> state module type S = sig val name : string val program : state -> Ir.program -> result end class virtual ir_transformer: object('self) method virtual program : Ir.program -> Ir.program * Types.datatype * 'self end module Make(T : sig val name : string val obj : Types.typing_environment -> ir_transformer end) : S
voting_period_storage.mli
val init : Raw_context.t -> Voting_period_repr.t -> Raw_context.t tzresult Lwt.t (** Sets the initial period to [{voting_period = root; kind = Proposal; start_position}]. *) val init_first_period : Raw_context.t -> start_position:Int32.t -> Raw_context.t tzresult Lwt.t (** Increment the index by one and set the kind to Proposal. *) val reset : Raw_context.t -> Raw_context.t tzresult Lwt.t (** Increment the index by one and set the kind to its successor. *) val succ : Raw_context.t -> Raw_context.t tzresult Lwt.t val get_current : Raw_context.t -> Voting_period_repr.t tzresult Lwt.t val get_current_kind : Raw_context.t -> Voting_period_repr.kind tzresult Lwt.t (** Returns true if the context level is the last of current voting period. *) val is_last_block : Raw_context.t -> bool tzresult Lwt.t (* Given the issue explained in voting_period_storage.ml this function behaves currectly during the validation of a block but returns inconsistent info if called after the finalization of the block. For this reason when used by the RPC `votes/current_period_kind` gives an unintuitive result: after the validation of the last block of a voting period (e.g. proposal), it returns the kind of the next period (e.g. exploration). To fix this, at least part of the current vote finalization should be moved at the beginning of the block validation. For retro-compatibility, we keep this function but we provide two new fixed functions to reply correctly to RPCs [get_rpc_fixed_current_info] and [get_rpc_fixed_succ_info]. *) val get_current_info : Raw_context.t -> Voting_period_repr.info tzresult Lwt.t (* In order to avoid the problem of `get_current_info` explained above, this function provides the corrent behavior for the new RPC `votes/current_period`. *) val get_rpc_fixed_current_info : Raw_context.t -> Voting_period_repr.info tzresult Lwt.t (* In order to avoid the problem of `get_current_info` explained above, this function provides the corrent behavior for the new RPC `votes/successor_period`. *) val get_rpc_fixed_succ_info : Raw_context.t -> Voting_period_repr.info tzresult Lwt.t
(*****************************************************************************) (* *) (* Open Source License *) (* 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. *) (* *) (*****************************************************************************)
dune
(test (name test) (package progress) (libraries progress alcotest astring fmt mtime))
theory_dense_diff_logic.h
#pragma once #include "smt/theory_arith.h" #include "smt/params/theory_arith_params.h" #include "ast/arith_decl_plugin.h" #include "smt/arith_eq_adapter.h" #include "smt/theory_opt.h" namespace smt { struct theory_dense_diff_logic_statistics { unsigned m_num_assertions; unsigned m_num_propagations; void reset() { m_num_assertions = 0; m_num_propagations = 0; } theory_dense_diff_logic_statistics() { reset(); } }; template<typename Ext> class theory_dense_diff_logic : public theory, public theory_opt, private Ext { public: theory_dense_diff_logic_statistics m_stats; private: typedef typename Ext::inf_numeral numeral; class atom { typedef typename Ext::inf_numeral numeral; bool_var m_bvar; theory_var m_source; theory_var m_target; numeral m_offset; public: atom(bool_var bv, theory_var source, theory_var target, numeral const & offset): m_bvar(bv), m_source(source), m_target(target), m_offset(offset) { } bool_var get_bool_var() const { return m_bvar; } theory_var get_source() const { return m_source; } theory_var get_target() const { return m_target; } numeral const & get_offset() const { return m_offset; } }; typedef ptr_vector<atom> atoms; typedef ptr_vector<atom> bool_var2atom; struct edge { theory_var m_source; theory_var m_target; numeral m_offset; literal m_justification; edge():m_source(null_theory_var), m_target(null_theory_var), m_justification(null_literal) {} edge(theory_var s, theory_var t, numeral const & offset, literal js): m_source(s), m_target(t), m_offset(offset), m_justification(js) { } }; typedef int edge_id; typedef vector<edge> edges; static const edge_id null_edge_id = -1; static const edge_id self_edge_id = 0; struct cell { edge_id m_edge_id; numeral m_distance; atoms m_occs; cell(): m_edge_id(null_edge_id) { } }; struct cell_trail { unsigned short m_source; unsigned short m_target; edge_id m_old_edge_id; numeral m_old_distance; cell_trail(unsigned short s, unsigned short t, edge_id old_edge_id, numeral const & old_distance): m_source(s), m_target(t), m_old_edge_id(old_edge_id), m_old_distance(old_distance) {} }; typedef vector<cell> row; typedef vector<row> matrix; struct scope { unsigned m_atoms_lim; unsigned m_edges_lim; unsigned m_cell_trail_lim; }; theory_arith_params & m_params; arith_util m_autil; arith_eq_adapter m_arith_eq_adapter; atoms m_atoms; atoms m_bv2atoms; edges m_edges; // list of asserted edges matrix m_matrix; bool_vector m_is_int; vector<cell_trail> m_cell_trail; svector<scope> m_scopes; bool m_non_diff_logic_exprs; // For optimization purpose typedef vector <std::pair<theory_var, rational> > objective_term; vector<objective_term> m_objectives; vector<rational> m_objective_consts; vector<expr_ref_vector> m_objective_assignments; struct f_target { theory_var m_target; numeral m_new_distance; }; typedef std::pair<theory_var, theory_var> var_pair; typedef vector<f_target> f_targets; literal_vector m_tmp_literals; svector<var_pair> m_tmp_pairs; f_targets m_f_targets; vector<numeral> m_assignment; struct var_value_hash; friend struct var_value_hash; struct var_value_hash { theory_dense_diff_logic & m_th; var_value_hash(theory_dense_diff_logic & th):m_th(th) {} unsigned operator()(theory_var v) const { return m_th.m_assignment[v].hash(); } }; struct var_value_eq; friend struct var_value_eq; struct var_value_eq { theory_dense_diff_logic & m_th; var_value_eq(theory_dense_diff_logic & th):m_th(th) {} bool operator()(theory_var v1, theory_var v2) const { return m_th.m_assignment[v1] == m_th.m_assignment[v2]; } }; typedef int_hashtable<var_value_hash, var_value_eq> var_value_table; var_value_table m_var_value_table; // ----------------------------------- // // Auxiliary // // ----------------------------------- bool is_int(theory_var v) const { return m_is_int[v]; } bool is_real(theory_var v) const { return !is_int(v); } numeral const & get_epsilon(theory_var v) const { return is_real(v) ? this->m_real_epsilon : this->m_int_epsilon; } bool is_times_minus_one(expr * n, app * & r) const { expr * _r; if (m_autil.is_times_minus_one(n, _r)) { r = to_app(_r); return true; } return false; } app * mk_zero_for(expr * n); theory_var mk_var(enode * n) override; theory_var internalize_term_core(app * n); void found_non_diff_logic_expr(expr * n); bool is_connected(theory_var source, theory_var target) const { return m_matrix[source][target].m_edge_id != null_edge_id; } void mk_clause(literal l1, literal l2); void mk_clause(literal l1, literal l2, literal l3); void add_edge(theory_var source, theory_var target, numeral const & offset, literal l); void update_cells(); void propagate_using_cell(theory_var source, theory_var target); void get_antecedents(theory_var source, theory_var target, literal_vector & result); void assign_literal(literal l, theory_var source, theory_var target); void restore_cells(unsigned old_size); void del_atoms(unsigned old_size); void del_vars(unsigned old_num_vars); void init_model(); bool internalize_objective(expr * n, rational const& m, rational& r, objective_term & objective); expr_ref mk_ineq(theory_var v, inf_eps const& val, bool is_strict); #ifdef Z3DEBUG bool check_vector_sizes() const; bool check_matrix() const; #endif public: numeral const & get_distance(theory_var source, theory_var target) const { SASSERT(is_connected(source, target)); return m_matrix[source][target].m_distance; } // ----------------------------------- // // Internalization // // ----------------------------------- bool internalize_atom(app * n, bool gate_ctx) override; bool internalize_term(app * term) override; void internalize_eq_eh(app * atom, bool_var v) override; void apply_sort_cnstr(enode * n, sort * s) override; void assign_eh(bool_var v, bool is_true) override; void new_eq_eh(theory_var v1, theory_var v2) override; bool use_diseqs() const override; void new_diseq_eh(theory_var v1, theory_var v2) override; void conflict_resolution_eh(app * atom, bool_var v) override; void push_scope_eh() override; void pop_scope_eh(unsigned num_scopes) override; void restart_eh() override; void init_search_eh() override; final_check_status final_check_eh() override; bool can_propagate() override; void propagate() override; void flush_eh() override; void reset_eh() override; void display(std::ostream & out) const override; virtual void display_atom(std::ostream & out, atom * a) const; void collect_statistics(::statistics & st) const override; // ----------------------------------- // // Model generation // // ----------------------------------- arith_factory * m_factory; rational m_epsilon; // void update_epsilon(const inf_numeral & l, const inf_numeral & u); void compute_epsilon(); void fix_zero(); void init_model(model_generator & m) override; model_value_proc * mk_value(enode * n, model_generator & mg) override; // ----------------------------------- // // Optimization // // ----------------------------------- inf_eps_rational<inf_rational> maximize(theory_var v, expr_ref& blocker, bool& has_shared) override; inf_eps_rational<inf_rational> value(theory_var v) override; theory_var add_objective(app* term) override; virtual expr_ref mk_gt(theory_var v, inf_eps const& val); expr_ref mk_ge(generic_model_converter& fm, theory_var v, inf_eps const& val); // ----------------------------------- // // Main // // ----------------------------------- public: theory_dense_diff_logic(context& ctx); ~theory_dense_diff_logic() override { reset_eh(); } theory * mk_fresh(context * new_ctx) override; char const * get_name() const override { return "difference-logic"; } /** \brief See comment in theory::mk_eq_atom */ app * mk_eq_atom(expr * lhs, expr * rhs) override { return m_autil.mk_eq(lhs, rhs); } }; typedef theory_dense_diff_logic<mi_ext> theory_dense_mi; typedef theory_dense_diff_logic<i_ext> theory_dense_i; typedef theory_dense_diff_logic<smi_ext> theory_dense_smi; typedef theory_dense_diff_logic<si_ext> theory_dense_si; };
/*++ Copyright (c) 2006 Microsoft Corporation Module Name: theory_dense_diff_logic.h Abstract: <abstract> Author: Leonardo de Moura (leonardo) 2008-05-16. Revision History: TODO: eager equality propagation --*/
pg_query_internal.h
#ifndef PG_QUERY_INTERNAL_H #define PG_QUERY_INTERNAL_H #include "postgres.h" #include "utils/memutils.h" #include "nodes/pg_list.h" #define STDERR_BUFFER_LEN 4096 #define DEBUG typedef struct { List *tree; char* stderr_buffer; PgQueryError* error; } PgQueryInternalParsetreeAndError; PgQueryInternalParsetreeAndError pg_query_raw_parse(const char* input); void pg_query_free_error(PgQueryError *error); MemoryContext pg_query_enter_memory_context(); void pg_query_exit_memory_context(MemoryContext ctx); #endif
identifiable.mli
(** Uniform interface for common data structures over various things. {b Warning:} this module is unstable and part of {{!Compiler_libs}compiler-libs}. *) module type Thing = sig type t include Hashtbl.HashedType with type t := t include Map.OrderedType with type t := t val output : out_channel -> t -> unit val print : Format.formatter -> t -> unit end module Pair : functor (A : Thing) (B : Thing) -> Thing with type t = A.t * B.t module type Set = sig module T : Set.OrderedType include Set.S with type elt = T.t and type t = Set.Make (T).t val output : out_channel -> t -> unit val print : Format.formatter -> t -> unit val to_string : t -> string val of_list : elt list -> t val map : (elt -> elt) -> t -> t end module type Map = sig module T : Map.OrderedType include Map.S with type key = T.t and type 'a t = 'a Map.Make (T).t val of_list : (key * 'a) list -> 'a t (** [disjoint_union m1 m2] contains all bindings from [m1] and [m2]. If some binding is present in both and the associated value is not equal, a Fatal_error is raised *) val disjoint_union : ?eq:('a -> 'a -> bool) -> ?print:(Format.formatter -> 'a -> unit) -> 'a t -> 'a t -> 'a t (** [union_right m1 m2] contains all bindings from [m1] and [m2]. If some binding is present in both, the one from [m2] is taken *) val union_right : 'a t -> 'a t -> 'a t (** [union_left m1 m2 = union_right m2 m1] *) val union_left : 'a t -> 'a t -> 'a t val union_merge : ('a -> 'a -> 'a) -> 'a t -> 'a t -> 'a t val rename : key t -> key -> key val map_keys : (key -> key) -> 'a t -> 'a t val keys : 'a t -> Set.Make(T).t val data : 'a t -> 'a list val of_set : (key -> 'a) -> Set.Make(T).t -> 'a t val transpose_keys_and_data : key t -> key t val transpose_keys_and_data_set : key t -> Set.Make(T).t t val print : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit end module type Tbl = sig module T : sig type t include Map.OrderedType with type t := t include Hashtbl.HashedType with type t := t end include Hashtbl.S with type key = T.t and type 'a t = 'a Hashtbl.Make (T).t val to_list : 'a t -> (T.t * 'a) list val of_list : (T.t * 'a) list -> 'a t val to_map : 'a t -> 'a Map.Make(T).t val of_map : 'a Map.Make(T).t -> 'a t val memoize : 'a t -> (key -> 'a) -> key -> 'a val map : 'a t -> ('a -> 'b) -> 'b t end module type S = sig type t module T : Thing with type t = t include Thing with type t := T.t module Set : Set with module T := T module Map : Map with module T := T module Tbl : Tbl with module T := T end module Make (T : Thing) : S with type t := T.t
(**************************************************************************) (* *) (* OCaml *) (* *) (* Pierre Chambart, OCamlPro *) (* Mark Shinwell and Leo White, Jane Street Europe *) (* *) (* Copyright 2013--2016 OCamlPro SAS *) (* Copyright 2014--2016 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. *) (* *) (**************************************************************************)
script_repr.mli
type location = Micheline.canonical_location type annot = Micheline.annot type expr = Michelson_v1_primitives.prim Micheline.canonical type error += Lazy_script_decode (* `Permanent *) type lazy_expr = expr Data_encoding.lazy_t type node = (location, Michelson_v1_primitives.prim) Micheline.node val location_encoding : location Data_encoding.t val expr_encoding : expr Data_encoding.t val lazy_expr_encoding : lazy_expr Data_encoding.t val lazy_expr : expr -> lazy_expr type t = {code : lazy_expr; storage : lazy_expr} val encoding : t Data_encoding.encoding val deserialized_cost : expr -> Gas_limit_repr.cost val serialized_cost : bytes -> Gas_limit_repr.cost val traversal_cost : node -> Gas_limit_repr.cost val int_node_cost : Z.t -> Gas_limit_repr.cost val int_node_cost_of_numbits : int -> Gas_limit_repr.cost val string_node_cost : string -> Gas_limit_repr.cost val string_node_cost_of_length : int -> Gas_limit_repr.cost val bytes_node_cost : bytes -> Gas_limit_repr.cost val bytes_node_cost_of_length : int -> Gas_limit_repr.cost val prim_node_cost_nonrec : expr list -> annot -> Gas_limit_repr.cost val seq_node_cost_nonrec : expr list -> Gas_limit_repr.cost val seq_node_cost_nonrec_of_length : int -> Gas_limit_repr.cost val force_decode : lazy_expr -> (expr * Gas_limit_repr.cost) tzresult val force_bytes : lazy_expr -> (bytes * Gas_limit_repr.cost) tzresult val minimal_deserialize_cost : lazy_expr -> Gas_limit_repr.cost val unit_parameter : lazy_expr val is_unit_parameter : lazy_expr -> bool val strip_annotations : node -> node val micheline_nodes : node -> int val strip_locations_cost : node -> Gas_limit_repr.cost
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
execution_parameters.mli
(** Parameters that influence rule execution *) (** Such as: - should targets be set read-only? - should aliases be expanded when sandboxing rules? These often depend on the version of the Dune language used, which is written in the [dune-project] file. Depending on the execution parameters rather than the whole [dune-project] file means that when some part of the [dune-project] file changes and this part does not have an effect on rule execution, we can skip a bunch of work by not trying to re-execute all the rules. *) type t val equal : t -> t -> bool val hash : t -> int val to_dyn : t -> Dyn.t module Action_output_on_success : sig (** How to deal with the output (stdout/stderr) of actions when they succeed. *) type t = | Print (** Print it to the terminal. *) | Swallow (** Completely ignore it. There is no way for the user to access it but the output of Dune is clean. *) | Must_be_empty (** Require it to be empty. Treat the action as failed if it is not. *) val all : (string * t) list val equal : t -> t -> bool val hash : t -> int val to_dyn : t -> Dyn.t end (** {1 Constructors} *) val builtin_default : t val set_dune_version : Dune_lang.Syntax.Version.t -> t -> t val set_action_stdout_on_success : Action_output_on_success.t -> t -> t val set_action_stderr_on_success : Action_output_on_success.t -> t -> t val set_expand_aliases_in_sandbox : bool -> t -> t val add_workspace_root_to_build_path_prefix_map : t -> bool (** As configured by [init] *) val default : t Memo.t (** {1 Accessors} *) val dune_version : t -> Dune_lang.Syntax.Version.t val should_remove_write_permissions_on_generated_files : t -> bool val expand_aliases_in_sandbox : t -> bool val action_stdout_on_success : t -> Action_output_on_success.t val action_stderr_on_success : t -> Action_output_on_success.t (** {1 Initialisation} *) val init : t Memo.t -> unit
(** Parameters that influence rule execution *)
test_helpers.mli
val fixture : string -> Cstruct.t (** Reads a file in [tests/keys] *)
resource_types.mli
(** resource.proto Types *) (** {2 Types} *) type resource = { attributes : Common_types.key_value list; dropped_attributes_count : int32; } (** {2 Default values} *) val default_resource : ?attributes:Common_types.key_value list -> ?dropped_attributes_count:int32 -> unit -> resource (** [default_resource ()] is the default value for type [resource] *)
(** resource.proto Types *)
dynlink_platform_intf.ml
#2 "otherlibs/dynlink/dynlink_platform_intf.ml" (**************************************************************************) (* *) (* OCaml *) (* *) (* Xavier Leroy, projet Cristal, INRIA Rocquencourt *) (* Mark Shinwell and Leo White, Jane Street Europe *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* Copyright 2017--2018 Jane Street Group LLC *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (** Interface for platform-specific dynlink providers. Note that this file needs to be a valid .mli file. *) [@@@ocaml.warning "+a-4-30-40-41-42"] module type S = sig type handle module Unit_header : sig type t val name : t -> string val crc : t -> Digest.t option val interface_imports : t -> (string * Digest.t option) list val implementation_imports : t -> (string * Digest.t option) list val defined_symbols : t -> string list val unsafe_module : t -> bool end val init : unit -> unit val is_native : bool val adapt_filename : Dynlink_types.filename -> Dynlink_types.filename val num_globals_inited : unit -> int val fold_initial_units : init:'a -> f:('a -> comp_unit:string -> interface:Digest.t option -> implementation:(Digest.t option * Dynlink_types.implem_state) option -> defined_symbols:string list -> 'a) -> 'a val load : filename:Dynlink_types.filename -> priv:bool -> handle * (Unit_header.t list) val run_shared_startup : handle -> unit val run : handle -> unit_header:Unit_header.t -> priv:bool -> unit val finish : handle -> unit end
raw_level_repr.mli
(** The shell's notion of a level: an integer indicating the number of blocks since genesis: genesis is 0, all other blocks have increasing levels from there. *) type t type raw_level = t val encoding : raw_level Data_encoding.t val rpc_arg : raw_level RPC_arg.arg val pp : Format.formatter -> raw_level -> unit include Compare.S with type t := raw_level val to_int32 : raw_level -> int32 val of_int32_exn : int32 -> raw_level val of_int32 : int32 -> raw_level tzresult val diff : raw_level -> raw_level -> int32 val root : raw_level val succ : raw_level -> raw_level val pred : raw_level -> raw_level option module Index : Storage_description.INDEX with type t = raw_level
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
pp.ml
Ppxlib.Driver.standalone ()
lib_relocated.ml
module Elsewhere : sig module Foo : module type of Repr type t [@@deriving repr { lib = Some "Foo" }] end = struct module Foo = Repr module Irmin = struct end type t = unit * unit [@@deriving repr { lib = Some "Foo" }] end module Locally_avaliable : sig type 'a ty type t [@@deriving repr { lib = None }] end = struct let pair, unit = Repr.(pair, unit) type 'a ty = 'a Repr.ty module Irmin = struct end type t = unit * unit [@@deriving repr { lib = None }] end
recursive_module_evaluation_errors.ml
(* TEST * expect *) module rec A: sig val x: int end = struct let x = B.x end and B:sig val x: int end = struct let x = E.y end and C:sig val x: int end = struct let x = B.x end and D:sig val x: int end = struct let x = C.x end and E:sig val x: int val y:int end = struct let x = D.x let y = 0 end [%%expect {| Line 2, characters 27-49: 2 | and B:sig val x: int end = struct let x = E.y end ^^^^^^^^^^^^^^^^^^^^^^ Error: Cannot safely evaluate the definition of the following cycle of recursively-defined modules: B -> E -> D -> C -> B. There are no safe modules in this cycle (see manual section 8.2). Line 2, characters 10-20: 2 | and B:sig val x: int end = struct let x = E.y end ^^^^^^^^^^ Module B defines an unsafe value, x . Line 5, characters 10-20: 5 | and E:sig val x: int val y:int end = struct let x = D.x let y = 0 end ^^^^^^^^^^ Module E defines an unsafe value, x . Line 4, characters 10-20: 4 | and D:sig val x: int end = struct let x = C.x end ^^^^^^^^^^ Module D defines an unsafe value, x . Line 3, characters 10-20: 3 | and C:sig val x: int end = struct let x = B.x end ^^^^^^^^^^ Module C defines an unsafe value, x . |}] type t = .. module rec A: sig type t += A end = struct type t += A = B.A end and B:sig type t += A end = struct type t += A = A.A end [%%expect {| type t = .. Line 2, characters 36-64: 2 | module rec A: sig type t += A end = struct type t += A = B.A end ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Error: Cannot safely evaluate the definition of the following cycle of recursively-defined modules: A -> B -> A. There are no safe modules in this cycle (see manual section 8.2). Line 2, characters 28-29: 2 | module rec A: sig type t += A end = struct type t += A = B.A end ^ Module A defines an unsafe extension constructor, A . Line 3, characters 20-21: 3 | and B:sig type t += A end = struct type t += A = A.A end ^ Module B defines an unsafe extension constructor, A . |}] module rec A: sig module F: functor(X:sig end) -> sig end val f: unit -> unit end = struct module F(X:sig end) = struct end let f () = B.value end and B: sig val value: unit end = struct let value = A.f () end [%%expect {| Line 4, characters 6-72: 4 | ......struct 5 | module F(X:sig end) = struct end 6 | let f () = B.value 7 | end Error: Cannot safely evaluate the definition of the following cycle of recursively-defined modules: A -> B -> A. There are no safe modules in this cycle (see manual section 8.2). Line 2, characters 2-41: 2 | module F: functor(X:sig end) -> sig end ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Module A defines an unsafe functor, F . Line 8, characters 11-26: 8 | and B: sig val value: unit end = struct let value = A.f () end ^^^^^^^^^^^^^^^ Module B defines an unsafe value, value . |}] module F(X: sig module type t module M: t end) = struct module rec A: sig module M: X.t val f: unit -> unit end = struct module M = X.M let f () = B.value end and B: sig val value: unit end = struct let value = A.f () end end [%%expect {| Line 5, characters 8-62: 5 | ........struct 6 | module M = X.M 7 | let f () = B.value 8 | end Error: Cannot safely evaluate the definition of the following cycle of recursively-defined modules: A -> B -> A. There are no safe modules in this cycle (see manual section 8.2). Line 3, characters 4-17: 3 | module M: X.t ^^^^^^^^^^^^^ Module A defines an unsafe module, M . Line 9, characters 13-28: 9 | and B: sig val value: unit end = struct let value = A.f () end ^^^^^^^^^^^^^^^ Module B defines an unsafe value, value . |}] module rec M: sig val f: unit -> int end = struct let f () = N.x end and N:sig val x: int end = struct let x = M.f () end;; [%%expect {| Exception: Undefined_recursive_module ("", 1, 43). |}]
(* TEST * expect *)
native_io.mli
open Fmlib module IO: Io.SIG
mul_KS.c
#include "fq_poly.h" #ifdef T #undef T #endif #define T fq #define CAP_T FQ #include "fq_poly_templates/mul_KS.c" #undef CAP_T #undef T
/* Copyright (C) 2008, 2009 William Hart Copyright (C) 2010, 2012 Sebastian Pancratz Copyright (C) 2013 Mike Hansen This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
CCRingBuffer.ml
(* This file is free software, part of containers. See file "license" for more details. *) (* Copyright (C) 2015 Simon Cruanes, Carmelo Piccione *) (** Generic Circular Buffer for IO, with bulk operations. The bulk operations (e.g. based on {!Array.blit} or {!Bytes.blit}) are more efficient than item-by-item copy. See https://en.wikipedia.org/wiki/Circular_buffer for an overview. *) module Array = struct (** The abstract type for arrays *) module type S = sig type elt (** The element type *) type t (** The type of an array instance *) val dummy : elt (** A dummy element used for empty slots in the array @since 2.4 *) val create : int -> t (** Make an array of the given size, filled with dummy elements *) val length : t -> int (** [length t] gets the total number of elements currently in [t] *) val get : t -> int -> elt (** [get t i] gets the element at position [i] *) val set : t -> int -> elt -> unit (** [set t i e] sets the element at position [i] to [e] *) val sub : t -> int -> int -> t (** [sub t i len] gets the subarray of [t] from position [i] to [i + len] *) val copy : t -> t (** [copy t] makes a fresh copy of the array [t] *) val blit : t -> int -> t -> int -> int -> unit (** [blit t s arr i len] copies [len] elements from [arr] starting at [i] to position [s] from [t] *) val iter : (elt -> unit) -> t -> unit (** [iter f t] iterates over the array [t] invoking [f] with the current element, in array order *) end module Byte : S with type elt = char and type t = Bytes.t = struct type elt = char let dummy = '\x00' include Bytes end module Make (Elt : sig type t val dummy : t end) : S with type elt = Elt.t and type t = Elt.t array = struct type elt = Elt.t type t = Elt.t array let dummy = Elt.dummy let create size = Array.make size Elt.dummy let length = Array.length let get = Array.get let set = Array.set let copy = Array.copy let blit = Array.blit let iter = Array.iter let sub = Array.sub end end module type S = sig module Array : Array.S (** The module type of Array for this ring buffer *) type t (** Defines the bounded ring buffer type *) exception Empty (** Raised in querying functions when the buffer is empty *) val create : int -> t (** [create size] creates a new bounded buffer with given size. The underlying array is allocated immediately and no further (large) allocation will happen from now on. @raise Invalid_argument if the arguments is [< 1] *) val copy : t -> t (** Make a fresh copy of the buffer. *) val capacity : t -> int (** Length of the inner buffer. *) val length : t -> int (** Number of elements currently stored in the buffer. *) val is_full : t -> bool (** true if pushing an element would erase another element. @since 1.3 *) val blit_from : t -> Array.t -> int -> int -> unit (** [blit_from buf from_buf o len] copies the slice [o, ... o + len - 1] from a input buffer [from_buf] to the end of the buffer. If the slice is too large for the buffer, only the last part of the array will be copied. @raise Invalid_argument if [o,len] is not a valid slice of [s] *) val blit_into : t -> Array.t -> int -> int -> int (** [blit_into buf to_buf o len] copies at most [len] elements from [buf] into [to_buf] starting at offset [o] in [s]. @return the number of elements actually copied ([min len (length buf)]). @raise Invalid_argument if [o,len] is not a valid slice of [s]. *) val append : t -> into:t -> unit (** [append b ~into] copies all data from [b] and adds it at the end of [into]. Erases data of [into] if there is not enough room. *) val to_list : t -> Array.elt list (** Extract the current content into a list *) val clear : t -> unit (** Clear the content of the buffer. Doesn't actually destroy the content. *) val is_empty : t -> bool (** Is the buffer empty (i.e. contains no elements)? *) val junk_front : t -> unit (** Drop the front element from [t]. @raise Empty if the buffer is already empty. *) val junk_back : t -> unit (** Drop the back element from [t]. @raise Empty if the buffer is already empty. *) val skip : t -> int -> unit (** [skip b len] removes [len] elements from the front of [b]. @raise Invalid_argument if [len > length b]. *) val iter : t -> f:(Array.elt -> unit) -> unit (** [iter b ~f] calls [f i t] for each element [t] in [buf] *) val iteri : t -> f:(int -> Array.elt -> unit) -> unit (** [iteri b ~f] calls [f i t] for each element [t] in [buf], with [i] being its relative index within [buf]. *) val get_front : t -> int -> Array.elt (** [get_front buf i] returns the [i]-th element of [buf] from the front, ie the one returned by [take_front buf] after [i-1] calls to [junk_front buf]. @raise Invalid_argument if the index is invalid (> [length buf]) *) val get_back : t -> int -> Array.elt (** [get_back buf i] returns the [i]-th element of [buf] from the back, ie the one returned by [take_back buf] after [i-1] calls to [junk_back buf]. @raise Invalid_argument if the index is invalid (> [length buf]) *) val push_back : t -> Array.elt -> unit (** Push value at the back of [t]. If [t.bounded=false], the buffer will grow as needed, otherwise the oldest elements are replaced first. *) val peek_front : t -> Array.elt option (** First value from front of [t], without modification. *) val peek_front_exn : t -> Array.elt (** First value from front of [t], without modification. @raise Empty if buffer is empty. @since 1.3 *) val peek_back : t -> Array.elt option (** Get the last value from back of [t], without modification. *) val peek_back_exn : t -> Array.elt (** Get the last value from back of [t], without modification. @raise Empty if buffer is empty. @since 1.3 *) val take_back : t -> Array.elt option (** Take and remove the last value from back of [t], if any *) val take_back_exn : t -> Array.elt (** Take and remove the last value from back of [t]. @raise Empty if buffer is already empty. *) val take_front : t -> Array.elt option (** Take and remove the first value from front of [t], if any *) val take_front_exn : t -> Array.elt (** Take and remove the first value from front of [t]. @raise Empty if buffer is already empty. *) val of_array : Array.t -> t (** Create a buffer from an initial array, but doesn't take ownership of it (stills allocates a new internal array) @since 0.11 *) val to_array : t -> Array.t (** Create an array from the elements, in order. @since 0.11 *) end module MakeFromArray (A : Array.S) : S with module Array = A = struct module Array = A type t = { mutable start: int; mutable stop: int; (* excluded *) buf: Array.t; } exception Empty let create size = if size < 1 then invalid_arg "CCRingBuffer.create"; { start = 0; stop = 0; buf = A.create (size + 1) (* keep room for extra slot *); } let copy b = { b with buf = A.copy b.buf } let capacity b = let len = A.length b.buf in match len with | 0 -> 0 | l -> l - 1 let length b = if b.stop >= b.start then b.stop - b.start else A.length b.buf - b.start + b.stop let is_full b = length b + 1 = Array.length b.buf let next_ b i = let j = i + 1 in if j = A.length b.buf then 0 else j let incr_start_ b = b.start <- next_ b b.start let incr_stop_ b = b.stop <- next_ b b.stop let push_back b e = A.set b.buf b.stop e; incr_stop_ b; if b.start = b.stop then incr_start_ b; (* overwritten one element *) () let blit_from b from_buf o len = if len = 0 then () else if o + len > A.length from_buf then invalid_arg "CCRingBuffer.blit_from" else for i = o to o + len - 1 do push_back b (A.get from_buf i) done let blit_into b to_buf o len = if o + len > A.length to_buf then invalid_arg "CCRingBuffer.blit_into"; if b.stop >= b.start then ( let n = min (b.stop - b.start) len in A.blit b.buf b.start to_buf o n; n ) else ( let len_end = A.length b.buf - b.start in A.blit b.buf b.start to_buf o (min len_end len); if len_end >= len then len (* done *) else ( let n = min b.stop (len - len_end) in A.blit b.buf 0 to_buf (o + len_end) n; n + len_end ) ) let is_empty b = b.start = b.stop let take_front_exn b = if b.start = b.stop then raise Empty; let c = A.get b.buf b.start in A.set b.buf b.start A.dummy; b.start <- next_ b b.start; c let take_front b = try Some (take_front_exn b) with Empty -> None let take_back_exn b = if b.start = b.stop then raise Empty; if b.stop = 0 then b.stop <- A.length b.buf - 1 else b.stop <- b.stop - 1; let c = A.get b.buf b.stop in A.set b.buf b.stop A.dummy; c let take_back b = try Some (take_back_exn b) with Empty -> None let junk_front b = if b.start = b.stop then raise Empty; A.set b.buf b.start A.dummy; if b.start + 1 = A.length b.buf then b.start <- 0 else b.start <- b.start + 1 let junk_back b = if b.start = b.stop then raise Empty; if b.stop = 0 then b.stop <- A.length b.buf - 1 else b.stop <- b.stop - 1; A.set b.buf b.stop A.dummy let skip b len = if len > length b then invalid_arg "CCRingBuffer.skip"; for _ = 1 to len do junk_front b done let clear b = skip b (length b) let iter b ~f = if b.stop >= b.start then for i = b.start to b.stop - 1 do f (A.get b.buf i) done else ( for i = b.start to A.length b.buf - 1 do f (A.get b.buf i) done; for i = 0 to b.stop - 1 do f (A.get b.buf i) done ) let iteri b ~f = if b.stop >= b.start then for i = b.start to b.stop - 1 do f i (A.get b.buf i) done else ( for i = b.start to A.length b.buf - 1 do f i (A.get b.buf i) done; for i = 0 to b.stop - 1 do f i (A.get b.buf i) done ) let get b i = if b.stop >= b.start then if i >= b.stop - b.start then invalid_arg "CCRingBuffer.get" else A.get b.buf (b.start + i) else ( let len_end = A.length b.buf - b.start in if i < len_end then A.get b.buf (b.start + i) else if i - len_end > b.stop then invalid_arg "CCRingBuffer.get" else A.get b.buf (i - len_end) ) let get_front b i = if is_empty b then invalid_arg "CCRingBuffer.get_front" else get b i let get_back b i = let offset = length b - i - 1 in if offset < 0 then invalid_arg "CCRingBuffer.get_back" else get b offset let to_list b = let len = length b in let rec build l i = if i < 0 then l else build (get_front b i :: l) (i - 1) in build [] (len - 1) (* TODO: more efficient version, with one or two blit *) let append b ~into = iter b ~f:(push_back into) let peek_front_exn b = if is_empty b then raise Empty else A.get b.buf b.start let peek_front b = try Some (peek_front_exn b) with Empty -> None let peek_back_exn b = if is_empty b then raise Empty else ( let i = if b.stop = 0 then A.length b.buf - 1 else b.stop - 1 in A.get b.buf i ) let peek_back b = try Some (peek_back_exn b) with Empty -> None let of_array a = let b = create (max (A.length a) 16) in blit_from b a 0 (A.length a); b let to_array b = let a = A.create (length b) in let n = blit_into b a 0 (length b) in assert (n = length b); a end module Byte = MakeFromArray (Array.Byte) module Make (Elt : sig type t val dummy : t end) = MakeFromArray (Array.Make (Elt))
(* This file is free software, part of containers. See file "license" for more details. *)
main.ml
let error message = prerr_endline message; exit 1 let () = if Array.length Sys.argv <> 3 then error "Usage: dune exec \ scripts/declare-new-protocol-unit-test/main.exe -- XXX YYYYYYYY"; let proto_version = Sys.argv.(1) in let proto_short_hash = Sys.argv.(2) in let new_proto_name = proto_version ^ "_" ^ proto_short_hash in let in_ch = open_in ".gitlab/ci/unittest.yml" in Fun.protect ~finally: (fun () -> close_in in_ch) @@ fun () -> let out_ch = open_out ".gitlab/ci/unittest2.yml" in Fun.protect ~finally: (fun () -> close_out out_ch) @@ fun () -> let output_line line = output_string out_ch line; output_char out_ch '\n' in let replace line = Re.replace_string (Re.compile (Re.str "alpha")) ~by: new_proto_name line in let rec read_and_write_the_rest () = match input_line in_ch with | exception End_of_file -> () | line -> output_line line; read_and_write_the_rest () in let rec continue_reading_unit_alpha unit_alpha_lines = match input_line in_ch with | exception End_of_file | "" -> (* Found the end of what we were looking for. *) (* Write unit:alpha: job, and the rest of the file. *) output_line ""; List.iter output_line (List.rev unit_alpha_lines); read_and_write_the_rest () | line -> (* Still parsing the unit:alpha: job, replace it as we go. *) output_line (replace line); continue_reading_unit_alpha (line :: unit_alpha_lines) in let rec find_unit_alpha () = match input_line in_ch with | exception End_of_file -> error "End of file reached before seeing unit:alpha: - check \ .gitlab/ci/unittest.yml" | "unit:alpha:" as line -> (* Found the job we were looking for, start replacing it. *) output_line (replace line); continue_reading_unit_alpha [ line ] | line -> output_line line; find_unit_alpha () in find_unit_alpha (); Sys.rename ".gitlab/ci/unittest2.yml" ".gitlab/ci/unittest.yml"
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
Test_JsFunctions.ml
open BsMocha.Mocha open BsChai.Expect.Expect open BsChai.Expect.Combos.End open! Functors ;; describe "Functions" (fun () -> describe "Traversable" (fun () -> describe "Array" (fun () -> describe "Scan" (fun () -> let scan_left, scan_right = let open ArrayF.Int.Functions.Scan in scan_left, scan_right in describe "scan_left" (fun () -> it "should scan from the left" (fun () -> expect (scan_left ( + ) 0 [|1; 2; 3|]) |> to_be [|1; 3; 6|]; expect (scan_left ( - ) 10 [|1; 2; 3|]) |> to_be [|9; 7; 4|])); describe "scan_right" (fun () -> it "should scan from the right (array)" (fun () -> expect (scan_right ( + ) 0 [|1; 2; 3|]) |> to_be [|6; 5; 3|]; expect (scan_right (Function.flip ( - )) 10 [|1; 2; 3|]) |> to_be [|4; 5; 7|])))); describe "List" (fun () -> describe "Scan" (fun () -> let scan_left, scan_right = let open ListF.Int.Functions.Scan in scan_left, scan_right in describe "scan_left" (fun () -> it "should scan from the left" (fun () -> expect (scan_left ( + ) 0 [1; 2; 3]) |> to_be [1; 3; 6]; expect (scan_left ( - ) 10 [1; 2; 3]) |> to_be [9; 7; 4])); describe "scan_right" (fun () -> it "should scan from the right (array)" (fun () -> expect (scan_right ( + ) 0 [1; 2; 3]) |> to_be [6; 5; 3]; expect (scan_right (Function.flip ( - )) 10 [1; 2; 3]) |> to_be [4; 5; 7]))))))
fasta_stdin.ml
open! Base open! Bio_io.Fasta let () = Exn.protectx In_channel.stdin ~finally:In_channel.close ~f:(fun ic -> In_channel.iteri_records ic ~f:(fun i r -> Stdio.printf "%d -- %s -- %s\n" i (Record.id r) (Record.seq r)))
dune
(library (name view) (libraries service sihl todo))
lib_parsing_ml.ml
open Common (*module V = Visitor_ml*) (*****************************************************************************) (* Filemames *) (*****************************************************************************) let find_source_files_of_dir_or_files xs = Common.files_of_dir_or_files_no_vcs_nofilter xs |> List.filter (fun filename -> match File_type.file_type_of_file filename with | File_type.PL (File_type.OCaml ("ml" | "mli")) -> true | _ -> false) |> Common.sort let find_ml_files_of_dir_or_files xs = Common.files_of_dir_or_files_no_vcs_nofilter xs |> List.filter (fun filename -> match File_type.file_type_of_file filename with | File_type.PL (File_type.OCaml "ml") -> true | _ -> false) |> Common.sort let find_cmt_files_of_dir_or_files xs = Common.files_of_dir_or_files_no_vcs_nofilter xs |> List.filter (fun filename -> match File_type.file_type_of_file filename with | File_type.Obj ("cmt" | "cmti") -> true | _ -> false) (* ocaml 4.07 stdlib now has those .p.cmt files that cause dupe errors *) |> Common.exclude (fun filename -> filename =~ ".*\\.p\\.cmt") (* sometimes there is just a .cmti and no corresponding .cmt because * people put the information only in a .mli *) |> (fun xs -> let hfiles = Hashtbl.create 101 in xs |> List.iter (fun file -> let d, b, e = Common2.dbe_of_filename file in Hashtbl.add hfiles (d, b) e); Common2.hkeys hfiles |> List.map (fun (d, b) -> let xs = Hashtbl.find_all hfiles (d, b) in match xs with | [ "cmt"; "cmti" ] | [ "cmti"; "cmt" ] | [ "cmt" ] -> Common2.filename_of_dbe (d, b, "cmt") | [ "cmti" ] -> Common2.filename_of_dbe (d, b, "cmti") | _ -> raise Impossible)) |> Common.sort (*****************************************************************************) (* Extract infos *) (*****************************************************************************) (* convert to generic AST if you need to get tokens! let extract_info_visitor recursor = let globals = ref [] in let hooks = { V.default_visitor with V.kinfo = (fun (_k, _) i -> Common.push i globals) } in begin let vout = V.mk_visitor hooks in recursor vout; List.rev !globals end let ii_of_any any = extract_info_visitor (fun visitor -> visitor any) *)
(* Yoann Padioleau * * Copyright (C) 2010 Facebook * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation, with the * special exception on linking described in file license.txt. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * license.txt for more details. *)
ml_of_installer_generator_lib.mli
val templatized_content : registration_statements:string -> target_abi:Dkml_install_api.Context.Abi_v2.t -> string -> string (** [templatized_content ~registration_statements ~target_abi content] replaces the exact text ["(* TEMPLATE: register () *)"] in [content] with [registration_statements], and replacing the whitespace-insensitive text ["failwith \"TEMPLATE: target_abi\""] in [content] with [target_abi]. *) val copy_with_templates : target_abi:Dkml_install_api.Context.Abi_v2.t -> components:string list -> output_file:Fpath.t -> string -> (unit, [> Rresult.R.msg ]) result (** [copy_with_templates ~target_abi ~components ~output_file content] copies [file] into the current directory while replacing the exact text ["(* TEMPLATE: register () *)"] with [component.register ()] invocations for all [components], and replacing the whitespace-insensitive text ["failwith \"TEMPLATE: target_abi\""] with the enumeration value of [target_abi] (ex. ["Linux_x86"]). *)
position.mli
(** Represents a position in a text file. *) type t (** Position in a text file. *) type range = t * t (* A range in a text file. *) (** Print in memory source files with error markers. *) module Print (PP: Pretty_printer.SIG): sig (** [print_source_lines lines range] Print the source file given as a sequence of lines with line numbers and highlight the region [range]. *) val print_source_lines: string Sequence.t -> range -> PP.t (** [print_source src range] Print the source file given as a string with line numbers and highlight the region [range]. *) val print_source: string -> range -> PP.t end (** Make a position with points to the start of a textfile. *) val start: t (** Get the line number. First line is line 0. *) val line: t -> int (** Get the column number. First column is column 0. *) val column: t -> int (** Advance the position by using the next character. If the next character is a newline, then the line number is increment and the column number is reset to 0. *) val next: char -> t -> t (** Advance the position to the start of the next line. *) val next_line: t -> t (** Advance the column position by 1. *) val next_column: t -> t
(** Represents a position in a text file. *)
dune
(executable (name ctoxml_bin) (public_name ctoxml) (package ctoxml) (libraries FrontC)) (cram (deps %{bin:ctoxml}))
per_item.mli
(** Module used to represent the [(per_xxx ...)] forms The main different between this module and a plain [Map] is that the [map] operation applies transformations only once per distinct value. *) open Import module Make (Key : Map.Key) : Per_item_intf.S with type key = Key.t
(** Module used to represent the [(per_xxx ...)] forms The main different between this module and a plain [Map] is that the [map] operation applies transformations only once per distinct value. *)
listDashboards.mli
open Types type input = ListDashboardsInput.t type output = ListDashboardsOutput.t type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
pcl_expressions.c
#include "pcl_expressions.h" /*---------------------------------------------------------------------*/ /* Global Variables */ /*---------------------------------------------------------------------*/ /*---------------------------------------------------------------------*/ /* Forward Declarations */ /*---------------------------------------------------------------------*/ /*---------------------------------------------------------------------*/ /* Internal Functions */ /*---------------------------------------------------------------------*/ /*---------------------------------------------------------------------*/ /* Exported Functions */ /*---------------------------------------------------------------------*/ /*----------------------------------------------------------------------- // // Function: PCLExprAlloc() // // Allocate an initialized PCL-expression-cell // // Global Variables: - // // Side Effects : Memory allocation // /----------------------------------------------------------------------*/ PCLExpr_p PCLExprAlloc(void) { PCLExpr_p handle = PCLExprCellAlloc(); handle->op = PCLOpNoOp; handle->arg_no = 0; handle->args = PDArrayAlloc(2,2); return handle; } /*----------------------------------------------------------------------- // // Function: PCLExprFree() // // Free a PCL-expr-cell. // // Global Variables: - // // Side Effects : Memory operations // /----------------------------------------------------------------------*/ void PCLExprFree(PCLExpr_p junk) { long i; PCLExpr_p expr; PCLId_p ident; PCL2Pos_p pos; assert(junk); for(i=0; i<junk->arg_no; i++) { if(junk->op==PCLOpQuote) { ident = PCLExprArg(junk,i); PCLIdFree(ident); } else if(junk->op==PCLOpInitial) { assert(PCLExprArg(junk,i)); ClauseInfoFree(PCLExprArg(junk,i)); } else { expr = PCLExprArg(junk,i); PCLExprFree(expr); } pos = PCLExprArgPos(junk,i); if(pos) { PCL2PosFree(pos); } } PDArrayFree(junk->args); PCLExprCellFree(junk); } /*----------------------------------------------------------------------- // // Function: PCLMiniExprFree() // // Free a PCL Mini-Expression. // // Global Variables: - // // Side Effects : Memory operations // /----------------------------------------------------------------------*/ void PCLMiniExprFree(PCLExpr_p junk) { long i; PCLExpr_p expr; PCL2Pos_p pos; assert(junk); for(i=0; i<junk->arg_no; i++) { if(junk->op==PCLOpQuote) { /* Do nothing - its' just a a long stored in the array */ } else if(junk->op==PCLOpInitial) { assert(PCLExprArg(junk,i)); ClauseInfoFree(PCLExprArg(junk,i)); } else { expr = PCLExprArg(junk,i); PCLMiniExprFree(expr); } pos = PCLExprArgPos(junk,i); if(pos) { PCL2PosFree(pos); } } PDArrayFree(junk->args); PCLExprCellFree(junk); } /*----------------------------------------------------------------------- // // Function: PCLExprParse() // // Parse a PCL-expression or Mini-expression // // Global Variables: - // // Side Effects : Input, memory allocation // /----------------------------------------------------------------------*/ PCLExpr_p PCLExprParse(Scanner_p in, bool mini) { PCLExpr_p handle=PCLExprAlloc(); long i, arg_no=0; ClauseInfo_p info = NULL; if(TestInpTok(in,PosInt)) { handle->op = PCLOpQuote; if(mini) { PCLExprArgInt(handle,0)=ParseInt(in); } else { PCLExprArg(handle,0)=PCLIdParse(in); } if(TestInpTok(in,OpenBracket)) { PCLExprArgPos(handle,0)=PCL2PosParse(in); } else { PCLExprArgPos(handle,0)=NULL; } handle->arg_no=1; } else if(TestInpId(in, "initial")) { handle->op = PCLOpInitial; NextToken(in); if(TestInpTok(in, OpenBracket)) { info = ClauseInfoAllocEmpty(); NextToken(in); info->source = DStrCopyCore(AktToken(in)->literal); AcceptInpTok(in, String); AcceptInpTok(in, Comma); info->name = DStrCopy(AktToken(in)->literal); AcceptInpTok(in, Name|PosInt|SQString); AcceptInpTok(in, CloseBracket); handle->arg_no = 1; PCLExprArg(handle,0) = info; } else { handle->arg_no = 0; } } else { CheckInpId(in, PCL_EVALGC"|"PCL_ER"|"PCL_PM"|"PCL_SPM"|"PCL_EF"|" PCL_SAT"|" PCL_CONDENSE"|"PCL_RW"|"PCL_SR"|"PCL_CSR"|"PCL_ACRES"|" PCL_CN"|"PCL_SPLIT"|"PCL_SC"|"PCL_SE"|"PCL_FS"|" PCL_NNF"|"PCL_ID"|"PCL_AD"|"PCL_SQ"|"PCL_VR"|" PCL_SK"|"PCL_DSTR"|"PCL_ANNOQ"|"PCL_EVANS"|"PCL_NC ); if(TestInpId(in, PCL_EVALGC)) { handle->op=PCLOpEvalGC; arg_no=1; } else if(TestInpId(in, PCL_ER)) { handle->op=PCLOpEResolution; arg_no=1; } else if(TestInpId(in, PCL_PM)) { handle->op=PCLOpParamod; arg_no=2; } else if(TestInpId(in, PCL_SPM)) { handle->op=PCLOpSimParamod; arg_no=2; } else if(TestInpId(in, PCL_EF)) { handle->op=PCLOpEFactoring; arg_no=1; } else if(TestInpId(in, PCL_SAT)) { handle->op=PCLOpSatCheck; arg_no=PCL_VAR_ARG; } else if(TestInpId(in, PCL_CONDENSE)) { handle->op=PCLOpCondense; arg_no=1; } else if(TestInpId(in, PCL_RW)) { handle->op=PCLOpRewrite; arg_no=2; } else if(TestInpId(in, PCL_SR)) { handle->op=PCLOpSimplifyReflect; arg_no=2; } else if(TestInpId(in, PCL_CSR)) { handle->op=PCLOpContextSimplifyReflect; arg_no=2; } else if(TestInpId(in, PCL_ACRES)) { handle->op=PCLOpACResolution; arg_no=PCL_VAR_ARG; } else if(TestInpId(in, PCL_CN)) { handle->op=PCLOpClauseNormalize; arg_no=1; } else if(TestInpId(in, PCL_SPLIT)) { handle->op=PCLOpSplitClause; arg_no=1; } else if(TestInpId(in, PCL_SC)) { handle->op=PCLOpFOFSplitConjunct; arg_no=1; } else if(TestInpId(in, PCL_SE)) { handle->op=PCLOpSplitEquiv; arg_no=1; } else if(TestInpId(in, PCL_FS)) { handle->op=PCLOpFOFSimplify; arg_no=1; } else if(TestInpId(in, PCL_NNF)) { handle->op=PCLOpFOFDeMorgan; arg_no=1; } else if(TestInpId(in, PCL_ID)) { handle->op=PCLOpIntroDef; arg_no=0; } else if(TestInpId(in, PCL_AD)) { handle->op=PCLOpApplyDef; arg_no=2; } else if(TestInpId(in, PCL_SQ)) { handle->op=PCLOpFOFDistributeQuantors; arg_no=1; } else if(TestInpId(in, PCL_VR)) { handle->op=PCLOpFOFVarRename; arg_no=1; } else if(TestInpId(in, PCL_SK)) { handle->op=PCLOpFOFSkolemize; arg_no=1; } else if(TestInpId(in, PCL_DSTR)) { handle->op=PCLOpFOFDistributeDisjunction; arg_no=1; } else if(TestInpId(in, PCL_ANNOQ)) { handle->op=PCLOpAnnotateQuestion; arg_no=1; } else if(TestInpId(in, PCL_EVANS)) { handle->op=PCLOpEvalAnswers; arg_no=1; } else if(TestInpId(in, PCL_NC)) { handle->op=PCLOpFOFAssumeNegation; arg_no=1; } NextToken(in); if(arg_no) { AcceptInpTok(in,OpenBracket); PCLExprArg(handle,0)=PCLExprParse(in, mini); if(TestInpTok(in,OpenBracket)) { PCLExprArgPos(handle,0)=PCL2PosParse(in); } else { PCLExprArgPos(handle,0)=NULL; } for(i=1; TestInpTok(in, Comma); i++) { AcceptInpTok(in, Comma); PCLExprArg(handle,i)=PCLExprParse(in, mini); if(TestInpTok(in,OpenBracket)) { PCLExprArgPos(handle,i)=PCL2PosParse(in); } else { PCLExprArgPos(handle,i)=NULL; } } if((arg_no!=PCL_VAR_ARG) && (arg_no!=i)) { AktTokenError(in, "Wrong number of arguments in PCL " "expression", false); } AcceptInpTok(in,CloseBracket); handle->arg_no=i; } else { handle->arg_no=0; } } return handle; } /*----------------------------------------------------------------------- // // Function: PCLExprPrint() // // Print a PCL expression. // // Global Variables: - // // Side Effects : Output // /----------------------------------------------------------------------*/ void PCLExprPrint(FILE* out, PCLExpr_p expr, bool mini) { long i; assert(expr); assert(expr->args); if(expr->op== PCLOpInitial) { if(expr->arg_no) { assert(expr->arg_no == 1); ClauseSourceInfoPrintPCL(out, PCLExprArg(expr,0)); } else { fprintf(out, "initial"); } return; } if(expr->op==PCLOpQuote) { assert(expr->arg_no==1); if(mini) { fprintf(out, "%ld", PCLExprArgInt(expr,0)); } else { PCLIdPrint(out, PCLExprArg(expr,0)); } if(PCLExprArgPos(expr,0)) { PCL2PosPrint(out, PCLExprArgPos(expr,0)); } return; } switch(expr->op) { case PCLOpIntroDef: fprintf(out, PCL_ID); assert(expr->arg_no==0); break; case PCLOpParamod: fprintf(out, PCL_PM); assert(expr->arg_no==2); break; case PCLOpSimParamod: fprintf(out, PCL_SPM); assert(expr->arg_no==2); break; case PCLOpEResolution: fprintf(out, PCL_ER); assert(expr->arg_no==1); break; case PCLOpEvalGC: fprintf(out, PCL_EVALGC); assert(expr->arg_no==1); break; case PCLOpEFactoring: fprintf(out, PCL_EF); assert(expr->arg_no==1); break; case PCLOpSatCheck: fprintf(out, PCL_SAT); assert(expr->arg_no>0); break; case PCLOpCondense: fprintf(out, PCL_CONDENSE); assert(expr->arg_no==1); break; case PCLOpSimplifyReflect: fprintf(out, PCL_SR); assert(expr->arg_no==2); break; case PCLOpContextSimplifyReflect: fprintf(out, PCL_CSR); assert(expr->arg_no==2); break; case PCLOpACResolution: fprintf(out, PCL_ACRES); assert(expr->arg_no>0); break; case PCLOpRewrite: fprintf(out, PCL_RW); assert(expr->arg_no==2); break; case PCLOpClauseNormalize: fprintf(out, PCL_CN); assert(expr->arg_no==1); break; case PCLOpApplyDef: fprintf(out, PCL_AD); assert(expr->arg_no==2); break; case PCLOpSplitClause: fprintf(out, PCL_SPLIT); assert(expr->arg_no==1); break; case PCLOpFOFSplitConjunct: fprintf(out, PCL_SC); assert(expr->arg_no==1); break; case PCLOpSplitEquiv: fprintf(out, PCL_SE); assert(expr->arg_no==1); break; case PCLOpFOFSimplify: fprintf(out, PCL_FS); assert(expr->arg_no==1); break; case PCLOpFOFDeMorgan: fprintf(out, PCL_NNF); assert(expr->arg_no==1); break; case PCLOpFOFDistributeQuantors: fprintf(out, PCL_SQ); assert(expr->arg_no==1); break; case PCLOpAnnotateQuestion: fprintf(out, PCL_ANNOQ); assert(expr->arg_no==1); break; case PCLOpEvalAnswers: fprintf(out, PCL_EVANS); assert(expr->arg_no==1); break; case PCLOpFOFDistributeDisjunction: fprintf(out, PCL_DSTR); assert(expr->arg_no==1); break; case PCLOpFOFVarRename: fprintf(out, PCL_VR); assert(expr->arg_no==1); break; case PCLOpFOFSkolemize: fprintf(out, PCL_SK); assert(expr->arg_no==1); break; case PCLOpFOFAssumeNegation: fprintf(out, PCL_NC); assert(expr->arg_no==1); break; default: assert(false && "Unknown PCL operator"); break; } if(expr->arg_no) { fputc('(',out); PCLExprPrint(out, PCLExprArg(expr,0), mini); if(PCLExprArgPos(expr,0)) { PCL2PosPrint(out, PCLExprArgPos(expr,0)); } for(i=1; i<expr->arg_no; i++) { fputc(',',out); PCLExprPrint(out, PCLExprArg(expr,i), mini); if(PCLExprArgPos(expr,i)) { PCL2PosPrint(out, PCLExprArgPos(expr,i)); } } fputc(')',out); } } /*----------------------------------------------------------------------- // // Function: PCLExprPrintTSTP() // // Print a PCL expression in TSTP format. // // Global Variables: - // // Side Effects : Output // /----------------------------------------------------------------------*/ void PCLExprPrintTSTP(FILE* out, PCLExpr_p expr, bool mini) { long i; bool needs_ans = false; char *status = ",[status(unknown)]", *status_thm = ",[status(thm)]", *status_cth = ",[status(cth)]", *status_esa = ",[status(esa)]"; assert(expr); assert(expr->args); switch(expr->op) { case PCLOpInitial: if(expr->arg_no) { assert(expr->arg_no == 1); ClauseSourceInfoPrintTSTP(out, PCLExprArg(expr,0)); } else { fprintf(out, "unknown()"); } return; case PCLOpQuote: assert(expr->arg_no==1); if(mini) { /* fprintf(out, "c_0_%ld", PCLExprArgInt(expr,0)); */ fprintf(out, "%ld", PCLExprArgInt(expr,0)); } else { PCLIdPrintTSTP(out, PCLExprArg(expr,0)); } return; case PCLOpIntroDef: fprintf(out, PCL_ID"(definition)"); return; default: break; } fprintf(out, "inference("); switch(expr->op) { case PCLOpParamod: fprintf(out, PCL_PM); status = status_thm; assert(expr->arg_no==2); break; case PCLOpSimParamod: fprintf(out, PCL_SPM); status = status_thm; assert(expr->arg_no==2); break; case PCLOpEResolution: fprintf(out, PCL_ER); status = status_thm; assert(expr->arg_no==1); break; case PCLOpEvalGC: fprintf(out, PCL_EVALGC); status = status_thm; assert(expr->arg_no==1); break; case PCLOpEFactoring: fprintf(out, PCL_EF); status = status_thm; assert(expr->arg_no==1); break; case PCLOpACResolution: fprintf(out, PCL_ACRES); status = status_thm; assert(expr->arg_no>0); break; case PCLOpSatCheck: fprintf(out, PCL_SAT); status = status_thm; assert(expr->arg_no>0); break; case PCLOpCondense: fprintf(out, PCL_CONDENSE); status = status_thm; assert(expr->arg_no==1); break; case PCLOpSimplifyReflect: fprintf(out, PCL_SR); status = status_thm; assert(expr->arg_no==2); break; case PCLOpContextSimplifyReflect: fprintf(out, PCL_CSR); status = status_thm; assert(expr->arg_no==2); break; case PCLOpRewrite: fprintf(out, PCL_RW); status = status_thm; assert(expr->arg_no==2); break; case PCLOpClauseNormalize: fprintf(out, PCL_CN); status = status_thm; assert(expr->arg_no==1); break; case PCLOpApplyDef: fprintf(out, PCL_AD); status = status_thm; assert(expr->arg_no==2); break; case PCLOpSplitClause: fprintf(out, TSTP_SPLIT_BASE ",["TSTP_SPLIT_BASE"(" TSTP_SPLIT_REFINED",[])]"); status = ""; assert(expr->arg_no==1); break; case PCLOpFOFSplitConjunct: fprintf(out, PCL_SC); status = status_thm; assert(expr->arg_no==1); break; case PCLOpSplitEquiv: fprintf(out, PCL_SE); status = status_thm; assert(expr->arg_no==1); break; case PCLOpFOFSimplify: fprintf(out, PCL_FS); status = status_thm; assert(expr->arg_no==1); break; case PCLOpFOFDeMorgan: fprintf(out, PCL_NNF); status = status_thm; assert(expr->arg_no==1); break; case PCLOpFOFDistributeQuantors: fprintf(out, PCL_SQ); status = status_thm; assert(expr->arg_no==1); break; case PCLOpAnnotateQuestion: fprintf(out, PCL_ANNOQ); status = status_thm; needs_ans = true; assert(expr->arg_no==1); break; case PCLOpEvalAnswers: fprintf(out, PCL_EVANS); status = status_thm; needs_ans = true; assert(expr->arg_no==1); break; case PCLOpFOFDistributeDisjunction: fprintf(out, PCL_DSTR); status = status_thm; assert(expr->arg_no==1); break; case PCLOpFOFVarRename: fprintf(out, PCL_VR); status = status_thm; assert(expr->arg_no==1); break; case PCLOpFOFSkolemize: fprintf(out, PCL_SK); status = status_esa; assert(expr->arg_no==1); break; case PCLOpFOFAssumeNegation: fprintf(out, PCL_NC); status = status_cth; assert(expr->arg_no==1); break; default: assert(false && "Unknown PCL operator"); break; } fprintf(out, "%s,[", status); PCLExprPrintTSTP(out, PCLExprArg(expr,0), mini); for(i=1; i<expr->arg_no; i++) { fputc(',',out); PCLExprPrintTSTP(out, PCLExprArg(expr,i), mini); } if(needs_ans) { fputs(",theory(answers)", out); } fputs("])",out); } /*----------------------------------------------------------------------- // // Function: PCLStepExtract() // // Given a PCL step "extra" string, return true if this should be // the root of a proof tree for extraction. Implemented here, // because it is used by both steps and ministeps. // // Global Variables: - // // Side Effects : - // /----------------------------------------------------------------------*/ bool PCLStepExtract(char* extra) { if(!extra) { return false; } /* printf("PCLStepExtract(%s)\n", extra); */ if((*extra == '"') || (*extra == '\'')) { extra++; } return (strncmp(extra,"proof",5)==0)|| (strncmp(extra,"final",5)==0)|| (strncmp(extra,"extract",7)==0); } /*---------------------------------------------------------------------*/ /* End of File */ /*---------------------------------------------------------------------*/
/*----------------------------------------------------------------------- File : pcl_expressions.c Author: Stephan Schulz Contents PCL2 Expressions Copyright 1998, 1999, 2018 by the author. This code is released under the GNU General Public Licence and the GNU Lesser General Public License. See the file COPYING in the main E directory for details.. Run "eprover -h" for contact information. Created: Wed Mar 29 00:29:18 GMT 2000 -----------------------------------------------------------------------*/
test_garbage_collection.ml
open Core open Import module S = Incr.Select let%expect_test "unused nodes are collected" [@tags "no-js"] = let var = Incr.Var.create 1 in let gen_incr = Staged.unstage (S.select_one (module Int) (Incr.Var.watch var)) in let incr0 = gen_incr 0 in Caml.Gc.finalise (fun _ -> printf "incr0 collected") incr0; let incr1 = gen_incr 1 in let o0 = Incr.observe incr0 in let o1 = Incr.observe incr1 in Incr.stabilize (); let get = Incr.Observer.value_exn in printf "%B %B" (get o0) (get o1); [%expect {| false true |}]; Incr.Var.set var 0; Incr.stabilize (); printf "%B %B" (get o0) (get o1); [%expect {| true false |}]; Incr.Observer.disallow_future_use o0; let incr0 = gen_incr 0 in let o0' = Incr.observe incr0 in Incr.stabilize (); printf "%B %B" (get o0') (get o1); [%expect {| true false |}]; Gc.full_major (); [%expect {| incr0 collected |}]
owl_ndarray_upsampling_stub.c
#include "owl_core.h" #include <string.h> #define OWL_ENABLE_TEMPLATE //////////////////// function templates starts //////////////////// #define FUN_NATIVE(dim) stub_float32_ndarray_upsampling ## _ ## dim ## _ ## native #define FUN_BYTE(dim) stub_float32_ndarray_upsampling ## _ ## dim ## _ ## bytecode #define TYPE float #include "owl_ndarray_upsampling_impl.h" #undef TYPE #undef FUN_BYTE #undef FUN_NATIVE #define FUN_NATIVE(dim) stub_float64_ndarray_upsampling ## _ ## dim ## _ ## native #define FUN_BYTE(dim) stub_float64_ndarray_upsampling ## _ ## dim ## _ ## bytecode #define TYPE double #include "owl_ndarray_upsampling_impl.h" #undef TYPE #undef FUN_BYTE #undef FUN_NATIVE #define FUN_NATIVE(dim) stub_complex32_ndarray_upsampling ## _ ## dim ## _ ## native #define FUN_BYTE(dim) stub_complex32_ndarray_upsampling ## _ ## dim ## _ ## bytecode #define TYPE _Complex float #include "owl_ndarray_upsampling_impl.h" #undef TYPE #undef FUN_BYTE #undef FUN_NATIVE #define FUN_NATIVE(dim) stub_complex64_ndarray_upsampling ## _ ## dim ## _ ## native #define FUN_BYTE(dim) stub_complex64_ndarray_upsampling ## _ ## dim ## _ ## bytecode #define TYPE _Complex double #include "owl_ndarray_upsampling_impl.h" #undef TYPE #undef FUN_BYTE #undef FUN_NATIVE //////////////////// function templates ends //////////////////// #undef OWL_ENABLE_TEMPLATE
/* * OWL - OCaml Scientific and Engineering Computing * Copyright (c) 2016-2020 Liang Wang <liang.wang@cl.cam.ac.uk> */
token.mli
(** The aim of this module is to manage operations involving tokens such as minting, transferring, and burning. Every constructor of the types [source], [container], or [sink] represents a kind of account that holds a given (or possibly infinite) amount of tokens. Tokens can be transferred from a [source] to a [sink]. To uniformly handle all cases, special constructors of sources and sinks may be used. For example, the source [`Minted] is used to express a transfer of minted tokens to a destination, and the sink [`Burned] is used to express the action of burning a given amount of tokens taken from a source. Thanks to uniformity, it is easier to track transfers of tokens throughout the protocol by running [grep -R "Token.transfer" src/proto_alpha]. *) (** [container] is the type of token holders with finite capacity, and whose assets are contained in the context. Let [d] be a delegate. Be aware that transferring to/from [`Delegate_balance d] will not update [d]'s stake, while transferring to/from [`Contract (Contract_repr.implicit_contract d)] will update [d]'s stake. *) type container = [ `Contract of Contract_repr.t | `Collected_commitments of Blinded_public_key_hash.t | `Delegate_balance of Signature.Public_key_hash.t | `Frozen_deposits of Signature.Public_key_hash.t | `Block_fees | `Frozen_bonds of Contract_repr.t * Bond_id_repr.t ] (** [infinite_source] defines types of tokens provides which are considered to be ** of infinite capacity. *) type infinite_source = [ `Invoice | `Bootstrap | `Initial_commitments | `Revelation_rewards | `Double_signing_evidence_rewards | `Endorsing_rewards | `Baking_rewards | `Baking_bonuses | `Minted | `Liquidity_baking_subsidies | `Tx_rollup_rejection_rewards ] (** [source] is the type of token providers. Token providers that are not containers are considered to have infinite capacity. *) type source = [infinite_source | container] type infinite_sink = [ `Storage_fees | `Double_signing_punishments | `Lost_endorsing_rewards of Signature.Public_key_hash.t * bool * bool | `Tx_rollup_rejection_punishments | `Burned ] (** [sink] is the type of token receivers. Token receivers that are not containers are considered to have infinite capacity. *) type sink = [infinite_sink | container] (** [allocated ctxt container] returns a new context because of possible access to carbonated data, and a boolean that is [true] when [balance ctxt container] is guaranteed not to fail, and [false] when [balance ctxt container] may fail. *) val allocated : Raw_context.t -> container -> (Raw_context.t * bool) tzresult Lwt.t (** [balance ctxt container] returns a new context because of an access to carbonated data, and the balance associated to the token holder. This function may fail if [allocated ctxt container] returns [false]. Returns an error with the message "get_balance" if [container] refers to an originated contract that is not allocated. Returns a {!Storage_Error Missing_key} error if [container] is of the form [`Delegate_balance pkh], where [pkh] refers to an implicit contract that is not allocated. *) val balance : Raw_context.t -> container -> (Raw_context.t * Tez_repr.t) tzresult Lwt.t (** [transfer_n ?origin ctxt sources dest] transfers [amount] Tez from [src] to [dest] for each [(src, amount)] pair in [sources], and returns a new context, and the list of corresponding balance updates. The function behaves as though [transfer src dest amount] was invoked for each pair [(src, amount)] in [sources], however a single balance update is generated for the total amount transferred to [dest]. When [sources] is an empty list, the function does nothing to the context, and returns an empty list of balance updates. *) val transfer_n : ?origin:Receipt_repr.update_origin -> Raw_context.t -> ([< source] * Tez_repr.t) list -> [< sink] -> (Raw_context.t * Receipt_repr.balance_updates) tzresult Lwt.t (** [transfer ?origin ctxt src dest amount] transfers [amount] Tez from source [src] to destination [dest], and returns a new context, and the list of corresponding balance updates tagged with [origin]. By default, [~origin] is set to [Receipt_repr.Block_application]. Returns {!Storage_Error Missing_key} if [src] refers to a contract that is not allocated. Returns a [Balance_too_low] error if [src] refers to a contract whose balance is less than [amount]. Returns a [Subtraction_underflow] error if [src] refers to a source that is not a contract and whose balance is less than [amount]. Returns a [Empty_implicit_delegated_contract] error if [src] is an implicit contract that delegates to a different contract, and whose balance is equal to [amount]. Returns a [Non_existing_contract] error if [dest] refers to an originated contract that is not allocated. Returns a [Non_existing_contract] error if [amount <> Tez_repr.zero], and [dest] refers to an originated contract that is not allocated. Returns a [Addition_overflow] error if [dest] refers to a sink whose balance is greater than [Int64.max - amount]. Returns a [Wrong_level] error if [src] or [dest] refer to a level that is not the current level. *) val transfer : ?origin:Receipt_repr.update_origin -> Raw_context.t -> [< source] -> [< sink] -> Tez_repr.t -> (Raw_context.t * Receipt_repr.balance_updates) tzresult Lwt.t
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2020-2021 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
compiler.ml
open List_utils open Parser_combinator open Parser open Binary open Ir open Wasm let read filename = let f = open_in filename and str = ref "" in (try while true do str := !str ^ input_line f ^ "\n" done; with _ -> ()); close_in f; !str let write f bytes = List.iter (output_byte f) bytes let adjust_size size bytes = let lack = size - List.length bytes in if lack = 0 then bytes else if lack > 0 then bytes @ make_list lack 0 else failwith "(adjust_arr_length) Invalid format" exception Duplicate_func of location let check_duplication = let rec inner checked = function | [] -> () | FuncDef (_, _, (loc, name), _, _) :: tail -> if List.mem name checked then raise @@ Duplicate_func loc else inner (name :: checked) tail in inner [] let hidden_functions = [ Func (* init *) { signature = { params = 0; results = 0} ; locals = 0 ; code = [65; 0; 65; 8; 54; 2; 0; 65; 4; 65; 0; 54; 2; 0; 65; 8; 65; 0; 54; 2; 0; 65; 12; 65; 202; 215; 2; 54; 2; 0] } ; Func (* malloc *) { signature = { params = 1; results = 1} ; locals = 4 ; code = [2; 64; 3; 64; 32; 1; 40; 2; 0; 33; 1; 32; 1; 65; 4; 106; 40; 2; 0; 32; 0; 107; 33; 4; 32; 4; 65; 0; 74; 4; 64; 32; 1; 32; 1; 65; 4; 106; 40; 2; 0; 106; 32; 0; 65; 8; 106; 107; 33; 3; 65; 4; 32; 3; 106; 32; 0; 54; 2; 0; 32; 1; 65; 4; 106; 32; 1; 65; 4; 106; 40; 2; 0; 32; 0; 65; 8; 106; 107; 54; 2; 0; 32; 3; 65; 8; 106; 15; 11; 32; 4; 69; 4; 64; 2; 64; 3; 64; 32; 2; 40; 2; 0; 33; 2; 32; 2; 40; 2; 0; 32; 1; 70; 4; 64; 32; 2; 32; 1; 40; 2; 0; 54; 2; 0; 32; 1; 15; 11; 32; 2; 40; 2; 0; 65; 0; 71; 13; 0; 11; 0; 11; 11; 32; 1; 40; 2; 0; 65; 0; 71; 13; 0; 11; 11; 0] } ; Func (* free *) { signature = { params = 1; results = 0} ; locals = 3 ; code = [32; 0; 65; 8; 107; 33; 1; 2; 64; 3; 64; 32; 2; 40; 2; 0; 33; 2; 32; 2; 32; 1; 74; 4; 64; 32; 3; 32; 1; 54; 2; 0; 32; 2; 32; 1; 32; 1; 65; 4; 106; 40; 2; 0; 106; 65; 8; 106; 70; 4; 64; 32; 1; 32; 2; 40; 2; 0; 54; 2; 0; 32; 1; 65; 4; 106; 32; 1; 65; 4; 106; 40; 2; 0; 65; 8; 106; 32; 2; 65; 4; 106; 40; 2; 0; 106; 54; 2; 0; 5; 32; 1; 32; 2; 54; 2; 0; 11; 15; 11; 32; 2; 33; 3; 32; 2; 40; 2; 0; 65; 0; 71; 13; 0; 11; 32; 3; 32; 1; 54; 2; 0; 11] } ; Func (* push *) { signature = { params = 1; results = 0} ; locals = 0 ; code = [35; 0; 32; 0; 54; 2; 0; 35; 0; 65; 4; 107; 36; 0] } ; Func (* pop *) { signature = { params = 0; results = 1} ; locals = 0 ; code = [35; 0; 65; 4; 106; 36; 0; 35; 0; 40; 2; 0] } ; Func (* top *) { signature = { params = 0; results = 1} ; locals = 0 ; code = [35; 0; 65; 4; 106; 40; 2; 0] } ] let names_of_stmts = List.map (function FuncDef (_, _, (_, name), _, _) -> name) let functions_of_stmts stmts = let names = names_of_stmts stmts in stmts |> List.map (function FuncDef (_, pub, ident, args, expr_ast) -> let max = ref (-1) in let code = (Ir.bin_of_insts (Ir.insts_of_expr_ast expr_ast names args) max (List.length args)) in if pub then ExportedFunc { export_name = snd ident ; signature = { params = List.length args; results = 1 } ; locals = !max + 1 + List.length args ; code } else Func { signature = { params = List.length args; results = 1 } ; locals = !max + 1 + List.length args ; code }) let compile src = let ast = program src in check_duplication ast; let out = open_out "out.wasm" in write out @@ bin_of_wasm { global_vars = [[65; 255; 243; 3] (* i32.const 63999 *) ] ; functions = hidden_functions @ functions_of_stmts ast ; memories = [ Mem { limits = false; initial = 1 } ] }; close_out out let syntax_error isREPL src loc = begin if isREPL = false then print_endline @@ List.nth (String.split_on_char '\n' src) loc.line; print_endline @@ String.make loc.chr ' ' ^ "^"; print_endline @@ string_of_loc loc ^ ": Syntax Error" end let duplicate_export isREPL src loc = begin if isREPL = false then print_endline @@ List.nth (String.split_on_char '\n' src) loc.line; print_endline @@ String.make loc.chr ' ' ^ "^"; print_endline @@ string_of_loc loc ^ ": Duplicate function" end let unbound_value isREPL src loc ident = begin if isREPL = false then print_endline @@ List.nth (String.split_on_char '\n' src) loc.line; print_endline @@ String.make loc.chr ' ' ^ "^"; print_endline @@ string_of_loc loc ^ ": Unbound value `" ^ ident ^ "`" end let () = if Array.length Sys.argv = 1 then print_string @@ " ____ __\n" ^ " / __ \\_______ _______/ /_ ___\n" ^ " / /_/ / ___/ / / / ___/ __ \\/ _ \\\n" ^ " / ____(__ ) /_/ / /__/ / / / __/\n" ^ "/_/ /____/\\__, /\\___/_/ /_/\\___/\n" ^ " /____/\n\n" ^ "A WASM friendly lightweight programming language\n" ^ "Version 0.0.1\n" else match Sys.argv.(1) with | "make" -> if Array.length Sys.argv >= 3 then let input = read @@ Sys.argv.(2) in try compile input with | Syntax_error loc -> begin syntax_error false input loc; exit (-1) end | Duplicate_func loc -> begin duplicate_export false input loc; exit (-1) end | Unbound_value (loc, ident) -> begin unbound_value false input loc ident; exit (-1) end else (print_endline "Source files were not provided"; exit (-1)) | str -> (print_endline @@ "Invalid subcommand: " ^ str; exit (-1))
unpack_list.ml
let () = let res = [1; 2] |> [%madcast: int list -> (int * int)] in assert (res = (1, 2))
t-1f1_integration.c
#include "arb_hypgeom.h" int main() { slong iter; flint_rand_t state; flint_printf("1f1_integration...."); fflush(stdout); flint_randinit(state); for (iter = 0; iter < 100 * arb_test_multiplier(); iter++) { arb_t a, b, z, r1, r2; slong prec1, prec2; int regularized; prec1 = 2 + n_randint(state, 80); prec2 = 2 + n_randint(state, 150); arb_init(a); arb_init(b); arb_init(z); arb_init(r1); arb_init(r2); regularized = n_randint(state, 2); arb_randtest_precise(a, state, 1 + n_randint(state, 200), 1 + n_randint(state, 8)); arb_randtest_precise(b, state, 1 + n_randint(state, 200), 1 + n_randint(state, 8)); arb_randtest_precise(z, state, 1 + n_randint(state, 200), 1 + n_randint(state, 8)); arb_randtest(r1, state, 1 + n_randint(state, 200), 1 + n_randint(state, 5)); arb_randtest(r2, state, 1 + n_randint(state, 200), 1 + n_randint(state, 5)); arb_add_ui(a, a, n_randint(state, 100), prec1 + 100); arb_add_ui(b, b, n_randint(state, 200), prec1 + 100); arb_add_ui(z, z, n_randint(state, 100), prec1 + 100); arb_hypgeom_1f1_integration(r1, a, b, z, regularized, prec1); if (arb_is_finite(r1)) { if (n_randint(state, 2)) arb_hypgeom_1f1(r2, a, b, z, regularized, prec2); else arb_hypgeom_1f1_integration(r2, a, b, z, regularized, prec2); if (!arb_overlaps(r1, r2)) { flint_printf("FAIL: overlap\n\n"); flint_printf("a = "); arb_printd(a, 30); flint_printf("\n\n"); flint_printf("b = "); arb_printd(b, 30); flint_printf("\n\n"); flint_printf("z = "); arb_printd(z, 30); flint_printf("\n\n"); flint_printf("r1 = "); arb_printd(r1, 30); flint_printf("\n\n"); flint_printf("r2 = "); arb_printd(r2, 30); flint_printf("\n\n"); flint_abort(); } } if (iter == 0) { prec1 = 333; arb_set_str(a, "1.2e7", prec1); arb_set_str(b, "1.3e8", prec1); arb_set_str(z, "1.4e8", prec1); arb_hypgeom_1f1_integration(r1, a, b, z, 0, prec1); arb_set_str(r2, "4.490048760185759949474587200300668633822146852907335040923195547203089703047764681072928822e+11143817 +/- 4.55e+11143726", prec1); if (!arb_overlaps(r1, r2) || arb_rel_accuracy_bits(r1) < arb_rel_accuracy_bits(r2) - 10) { flint_printf("FAIL: overlap (1)\n\n"); flint_printf("r1 = "); arb_printd(r1, 100); flint_printf("\n\n"); flint_printf("r2 = "); arb_printd(r2, 100); flint_printf("\n\n"); flint_abort(); } arb_set_str(a, "1.2e14", prec1); arb_set_str(b, "1.3e15", prec1); arb_set_str(z, "1.4e14", prec1); arb_hypgeom_1f1_integration(r1, a, b, z, 0, prec1); arb_set_str(r2, "7.52012593871057092343210829853229360099866571986384089587141298507823992233368715541e+5903762458197 +/- 5.51e+5903762458113", prec1); if (!arb_overlaps(r1, r2) || arb_rel_accuracy_bits(r1) < arb_rel_accuracy_bits(r2) - 10) { flint_printf("FAIL: overlap (2)\n\n"); flint_printf("r1 = "); arb_printd(r1, 100); flint_printf("\n\n"); flint_printf("r2 = "); arb_printd(r2, 100); flint_printf("\n\n"); flint_abort(); } } arb_clear(a); arb_clear(b); arb_clear(z); arb_clear(r1); arb_clear(r2); } flint_randclear(state); flint_cleanup(); flint_printf("PASS\n"); return EXIT_SUCCESS; }
/* Copyright (C) 2021 Fredrik Johansson This file is part of Arb. Arb is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <http://www.gnu.org/licenses/>. */
gpointer.ml
(**************************************************************************) (* Lablgtk *) (* *) (* This program is free software; you can redistribute it *) (* and/or modify it under the terms of the GNU Library General *) (* Public License as published by the Free Software Foundation *) (* version 2, with the exception described in file COPYING which *) (* comes with the library. *) (* *) (* 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 Library General Public License for more details. *) (* *) (* You should have received a copy of the GNU Library 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 *) (* *) (* *) (**************************************************************************) (* $Id$ *) open StdLabels (* marked pointers *) type 'a optaddr let optaddr : 'a option -> 'a optaddr = function None -> Obj.magic 0 | Some x -> Obj.magic x (* boxed pointers *) type boxed let boxed_null : boxed = Obj.magic Nativeint.zero external peek_string : ?pos:int -> ?len:int -> boxed -> string = "ml_string_at_pointer" external peek_int : boxed -> int = "ml_int_at_pointer" external poke_int : boxed -> int -> unit = "ml_set_int_at_pointer" external peek_nativeint : boxed -> nativeint = "ml_long_at_pointer" external poke_nativeint : boxed -> nativeint -> unit = "ml_set_long_at_pointer" type 'a optboxed let optboxed : 'a option -> 'a optboxed = function None -> Obj.magic boxed_null | Some obj -> Obj.magic obj let may_box ~f obj : 'a optboxed = match obj with None -> Obj.magic boxed_null | Some obj -> Obj.magic (f obj : 'a) (* Variant tables *) type 'a variant_table constraint 'a = [> ] external decode_variant : 'a variant_table -> int -> 'a = "ml_ml_lookup_from_c" external encode_variant : 'a variant_table -> 'a -> int = "ml_ml_lookup_to_c" let encode_flags tbl l = List.fold_left l ~init:0 ~f:(fun acc v -> acc lor (encode_variant tbl v)) let decode_flags tbl c = let l = ref [] in for i = 30 downto 0 do (* only 31-bits in ocaml usual integers *) let d = 1 lsl i in if c land d <> 0 then l := decode_variant tbl d :: !l done; !l (* Exceptions *) exception Null let _ = Callback.register_exception "null_pointer" Null (* Stable pointer *) type 'a stable external stable_copy : 'a -> 'a stable = "ml_stable_copy" (* Region pointers *) type region = { data: Obj.t; path: int array; offset:int; length: int } let length reg = reg.length let unsafe_create_region ~path ~get_length data = { data = Obj.repr data; path = path; offset = 0; length = get_length data } let sub ?(pos=0) ?len reg = let len = match len with Some x -> x | None -> reg.length - pos in if pos < 0 || pos > reg.length || pos + len > reg.length then invalid_arg "Gpointer.sub"; { reg with offset = reg.offset + pos; length = len } external unsafe_get_byte : region -> pos:int -> int = "ml_gpointer_get_char" external unsafe_set_byte : region -> pos:int -> int -> unit = "ml_gpointer_set_char" external unsafe_blit : src:region -> dst:region -> unit ="ml_gpointer_blit" (* handle with care, if allocation not static *) external get_addr : region -> nativeint = "ml_gpointer_get_addr" let get_byte reg ~pos = if pos >= reg.length then invalid_arg "Gpointer.get_char"; unsafe_get_byte reg ~pos let set_byte reg ~pos ch = if pos >= reg.length then invalid_arg "Gpointer.set_char"; unsafe_set_byte reg ~pos ch let blit ~src ~dst = if src.length <> dst.length then invalid_arg "Gpointer.blit"; unsafe_blit ~src ~dst (* Making a region from a string is easy *) let region_of_bytes = unsafe_create_region ~path:[||] ~get_length:Bytes.length let bytes_of_region reg = let s = Bytes.create reg.length in let reg' = region_of_bytes s in unsafe_blit reg reg'; s (* Access bigarrays breaking the abstraction... dirty *) type 'a bigarray = (int, Bigarray.int8_unsigned_elt, 'a) Bigarray.Array1.t let bigarray_size (arr : 'a bigarray) = let size = { data = Obj.repr arr; path = [|1+4|]; offset = 0; length = 0 } in Nativeint.to_int (get_addr size) let region_of_bigarray arr = unsafe_create_region ~path:[|1|] ~get_length:bigarray_size arr
(**************************************************************************) (* Lablgtk *) (* *) (* This program is free software; you can redistribute it *) (* and/or modify it under the terms of the GNU Library General *) (* Public License as published by the Free Software Foundation *) (* version 2, with the exception described in file COPYING which *) (* comes with the library. *) (* *) (* 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 Library General Public License for more details. *) (* *) (* You should have received a copy of the GNU Library General *) (* Public License along with this program; if not, write to the *) (* Free Software Foundation, Inc., 59 Temple Place, Suite 330, *) (* Boston, MA 02111-1307 USA *) (* *) (* *) (**************************************************************************)
dune
(library (name incremental) (public_name incremental) (libraries core_kernel.balanced_reducer core incremental_step_function core_kernel.thread_safe_queue core_kernel.timing_wheel core_kernel.uopt core_kernel.weak_hashtbl) (preprocess (pps ppx_jane)) (preprocessor_deps debug.mlh))
Relooper.h
/* This is an optimized C++ implemention of the Relooper algorithm originally developed as part of Emscripten. This implementation includes optimizations added since the original academic paper [1] was published about it. [1] Alon Zakai. 2011. Emscripten: an LLVM-to-JavaScript compiler. In Proceedings of the ACM international conference companion on Object oriented programming systems languages and applications companion (SPLASH '11). ACM, New York, NY, USA, 301-312. DOI=10.1145/2048147.2048224 http://doi.acm.org/10.1145/2048147.2048224 */ #include <assert.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <deque> #include <list> #include <map> #include <memory> #include <set> #include "support/insert_ordered.h" #include "wasm-builder.h" #include "wasm.h" namespace CFG { class RelooperBuilder : public wasm::Builder { wasm::Index labelHelper; public: RelooperBuilder(wasm::Module& wasm, wasm::Index labelHelper) : wasm::Builder(wasm), labelHelper(labelHelper) {} wasm::LocalGet* makeGetLabel() { return makeLocalGet(labelHelper, wasm::Type::i32); } wasm::LocalSet* makeSetLabel(wasm::Index value) { return makeLocalSet(labelHelper, makeConst(wasm::Literal(int32_t(value)))); } wasm::Binary* makeCheckLabel(wasm::Index value) { return makeBinary( wasm::EqInt32, makeGetLabel(), makeConst(wasm::Literal(int32_t(value)))); } // breaks are on blocks, as they can be specific, we make one wasm block per // basic block wasm::Break* makeBlockBreak(int id) { return wasm::Builder::makeBreak(getBlockBreakName(id)); } // continues are on shapes, as there is one per loop, and if we have more than // one going there, it is irreducible control flow anyhow wasm::Break* makeShapeContinue(int id) { return wasm::Builder::makeBreak(getShapeContinueName(id)); } wasm::Name getBlockBreakName(int id) { return wasm::Name(std::string("block$") + std::to_string(id) + "$break"); } wasm::Name getShapeContinueName(int id) { return wasm::Name(std::string("shape$") + std::to_string(id) + "$continue"); } }; struct Relooper; struct Block; struct Shape; // Info about a branching from one block to another struct Branch { enum FlowType { Direct = 0, // We will directly reach the right location through other // means, no need for continue or break Break = 1, Continue = 2 }; // If not NULL, this shape is the relevant one for purposes of getting to the // target block. We break or continue on it Shape* Ancestor = nullptr; // If Ancestor is not NULL, this says whether to break or continue Branch::FlowType Type; // A branch either has a condition expression if the block ends in ifs, or if // the block ends in a switch, then a list of indexes, which becomes the // indexes in the table of the switch. If not a switch, the condition can be // any expression (or nullptr for the branch taken when no other condition is // true) A condition must not have side effects, as the Relooper can reorder // or eliminate condition checking. This must not have side effects. wasm::Expression* Condition; // Switches are rare, so have just a pointer for their values. This contains // the values for which the branch will be taken, or for the default it is // simply not present. std::unique_ptr<std::vector<wasm::Index>> SwitchValues; // If provided, code that is run right before the branch is taken. This is // useful for phis. wasm::Expression* Code; Branch(wasm::Expression* ConditionInit, wasm::Expression* CodeInit = nullptr); Branch(std::vector<wasm::Index>&& ValuesInit, wasm::Expression* CodeInit = nullptr); // Emits code for branch wasm::Expression* Render(RelooperBuilder& Builder, Block* Target, bool SetLabel); }; using BlockSet = wasm::InsertOrderedSet<Block*>; using BlockBranchMap = wasm::InsertOrderedMap<Block*, Branch*>; // Represents a basic block of code - some instructions that end with a // control flow modifier (a branch, return or throw). struct Block { // Reference to the relooper containing this block. Relooper* relooper; // Branches become processed after we finish the shape relevant to them. For // example, when we recreate a loop, branches to the loop start become // continues and are now processed. When we calculate what shape to generate // from a set of blocks, we ignore processed branches. Blocks own the Branch // objects they use, and destroy them when done. BlockBranchMap BranchesOut; BlockSet BranchesIn; BlockBranchMap ProcessedBranchesOut; BlockSet ProcessedBranchesIn; Shape* Parent = nullptr; // The shape we are directly inside int Id = -1; // A unique identifier, defined when added to relooper // The code in this block. This can be arbitrary wasm code, including internal // control flow, it should just not branch to the outside wasm::Expression* Code; // If nullptr, then this block ends in ifs (or nothing). otherwise, this block // ends in a switch, done on this condition wasm::Expression* SwitchCondition; // If true, we are a multiple entry, so reaching us requires setting the label // variable bool IsCheckedMultipleEntry; Block(Relooper* relooper, wasm::Expression* CodeInit, wasm::Expression* SwitchConditionInit = nullptr); // Add a branch: if the condition holds we branch (or if null, we branch if // all others failed) Note that there can be only one branch from A to B (if // you need multiple conditions for the branch, create a more interesting // expression in the Condition). If a Block has no outgoing branches, the // contents in Code must contain a terminating instruction, as the relooper // doesn't know whether you want control flow to stop with an `unreachable` or // a `return` or something else (if you forget to do this, control flow may // continue into the block that happens to be emitted right after it). // Internally, adding a branch only adds the outgoing branch. The matching // incoming branch on the target is added by the Relooper itself as it works. void AddBranchTo(Block* Target, wasm::Expression* Condition, wasm::Expression* Code = nullptr); // Add a switch branch: if the switch condition is one of these values, we // branch (or if the list is empty, we are the default) Note that there can be // only one branch from A to B (if you need multiple values for the branch, // that's what the array and default are for). void AddSwitchBranchTo(Block* Target, std::vector<wasm::Index>&& Values, wasm::Expression* Code = nullptr); // Emit code for the block, including its contents and branchings out wasm::Expression* Render(RelooperBuilder& Builder, bool InLoop); }; // Represents a structured control flow shape, one of // // Simple: No control flow at all, just instructions in a single // basic block. // // Multiple: A shape with at least one entry. We may visit one of // the entries, or none, before continuing to the next // shape after this. // // Loop: An infinite loop. We assume the property that a loop // will always visit one of its entries, and so for example // we cannot have a loop containing a multiple and nothing // else (since we might not visit any of the multiple's // blocks). Multiple entries are possible for the block, // however, which is necessary for irreducible control // flow, of course. // struct SimpleShape; struct MultipleShape; struct LoopShape; struct Shape { // A unique identifier. Used to identify loops, labels are Lx where x is the // Id. Defined when added to relooper int Id = -1; // The shape that will appear in the code right after this one Shape* Next = nullptr; // The shape that control flow gets to naturally (if there is Next, then this // is Next) Shape* Natural; enum ShapeType { Simple, Multiple, Loop }; ShapeType Type; Shape(ShapeType TypeInit) : Type(TypeInit) {} virtual ~Shape() = default; virtual wasm::Expression* Render(RelooperBuilder& Builder, bool InLoop) = 0; static SimpleShape* IsSimple(Shape* It) { return It && It->Type == Simple ? (SimpleShape*)It : NULL; } static MultipleShape* IsMultiple(Shape* It) { return It && It->Type == Multiple ? (MultipleShape*)It : NULL; } static LoopShape* IsLoop(Shape* It) { return It && It->Type == Loop ? (LoopShape*)It : NULL; } }; struct SimpleShape : public Shape { Block* Inner = nullptr; SimpleShape() : Shape(Simple) {} wasm::Expression* Render(RelooperBuilder& Builder, bool InLoop) override; }; using IdShapeMap = std::map<int, Shape*>; struct MultipleShape : public Shape { IdShapeMap InnerMap; // entry block ID -> shape MultipleShape() : Shape(Multiple) {} wasm::Expression* Render(RelooperBuilder& Builder, bool InLoop) override; }; struct LoopShape : public Shape { Shape* Inner = nullptr; BlockSet Entries; // we must visit at least one of these LoopShape() : Shape(Loop) {} wasm::Expression* Render(RelooperBuilder& Builder, bool InLoop) override; }; // Implements the relooper algorithm for a function's blocks. // // Usage: // 1. Instantiate this struct. // 2. Create the blocks you have. Each should have its // branchings in specified (the branchings out will // be calculated by the relooper). // 3. Call Render(). // // Implementation details: The Relooper instance takes ownership of the blocks, // branches and shapes when created using the `AddBlock` etc. methods, and frees // them when done. struct Relooper { wasm::Module* Module; std::deque<std::unique_ptr<Block>> Blocks; std::deque<std::unique_ptr<Branch>> Branches; std::deque<std::unique_ptr<Shape>> Shapes; Shape* Root; bool MinSize; int BlockIdCounter; int ShapeIdCounter; Relooper(wasm::Module* ModuleInit); // Creates a new block associated with (and cleaned up along) this relooper. Block* AddBlock(wasm::Expression* CodeInit, wasm::Expression* SwitchConditionInit = nullptr); // Creates a new branch associated with (and cleaned up along) this relooper. Branch* AddBranch(wasm::Expression* ConditionInit, wasm::Expression* CodeInit); // Creates a new branch associated with (and cleaned up along) this relooper. Branch* AddBranch(std::vector<wasm::Index>&& ValuesInit, wasm::Expression* CodeInit = nullptr); // Creates a new simple shape associated with (and cleaned up along) this // relooper. SimpleShape* AddSimpleShape(); // Creates a new multiple shape associated with (and cleaned up along) this // relooper. MultipleShape* AddMultipleShape(); // Creates a new loop shape associated with (and cleaned up along) this // relooper. LoopShape* AddLoopShape(); // Calculates the shapes void Calculate(Block* Entry); // Renders the result. wasm::Expression* Render(RelooperBuilder& Builder); // Sets us to try to minimize size void SetMinSize(bool MinSize_) { MinSize = MinSize_; } }; using BlockBlockSetMap = wasm::InsertOrderedMap<Block*, BlockSet>; #ifdef RELOOPER_DEBUG struct Debugging { static void Dump(Block* Curr, const char* prefix = NULL); static void Dump(BlockSet& Blocks, const char* prefix = NULL); static void Dump(Shape* S, const char* prefix = NULL); }; #endif } // namespace CFG
/* * Copyright 2016 WebAssembly Community Group participants * * 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. */
hdr_histogram_perf.c
/** * hdr_histogram_perf.c * Written by Michael Barker and released to the public domain, * as explained at http://creativecommons.org/publicdomain/zero/1.0/ */ #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <hdr/hdr_histogram.h> #include <hdr/hdr_time.h> #include <string.h> #if defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) #if !defined(WIN32_LEAN_AND_MEAN) #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #define snprintf sprintf_s #endif static hdr_timespec diff(hdr_timespec start, hdr_timespec end) { hdr_timespec temp; if ((end.tv_nsec-start.tv_nsec) < 0) { temp.tv_sec = end.tv_sec - start.tv_sec - 1; temp.tv_nsec = 1000000000 + end.tv_nsec-start.tv_nsec; } else { temp.tv_sec = end.tv_sec - start.tv_sec; temp.tv_nsec = end.tv_nsec - start.tv_nsec; } return temp; } /* Formats the given double with 2 dps, and , thousand separators */ static char *format_double(double d) { int p; static char buffer[30]; snprintf(buffer, sizeof(buffer), "%0.2f", d); p = (int) strlen(buffer) - 6; while (p > 0) { memmove(&buffer[p + 1], &buffer[p], strlen(buffer) - p + 1); buffer[p] = ','; p = p - 3; } return buffer; } int main() { struct hdr_histogram* histogram; hdr_timespec t0, t1; int result, i; int64_t iterations; int64_t max_value = INT64_C(24) * 60 * 60 * 1000000; int64_t min_value = 1; result = hdr_init(min_value, max_value, 4, &histogram); if (result != 0) { fprintf(stderr, "Failed to allocate histogram: %d\n", result); return -1; } iterations = 400000000; for (i = 0; i < 100; i++) { int64_t j; hdr_timespec taken; double time_taken, ops_sec; hdr_gettime(&t0); for (j = 1; j < iterations; j++) { hdr_record_value(histogram, j); } hdr_gettime(&t1); taken = diff(t0, t1); time_taken = taken.tv_sec + taken.tv_nsec / 1000000000.0; ops_sec = (iterations - 1) / time_taken; printf("%s - %d, ops/sec: %s\n", "Iteration", i + 1, format_double(ops_sec)); } return 0; }
/** * hdr_histogram_perf.c * Written by Michael Barker and released to the public domain, * as explained at http://creativecommons.org/publicdomain/zero/1.0/ */
client_proto_context_commands.ml
open Protocol open Alpha_context open Tezos_micheline open Client_proto_context open Client_proto_contracts open Client_keys let report_michelson_errors ?(no_print_source = false) ~msg (cctxt : #Client_context.printer) = function | Error errs -> cctxt#warning "%a" (Michelson_v1_error_reporter.report_errors ~details:(not no_print_source) ~show_source:(not no_print_source) ?parsed:None) errs >>= fun () -> cctxt#error "%s" msg >>= fun () -> Lwt.return_none | Ok data -> Lwt.return_some data let data_parameter = Clic.parameter (fun _ data -> Lwt.return (Micheline_parser.no_parsing_error @@ Michelson_v1_parser.parse_expression data)) let non_negative_param = Clic.parameter (fun _ s -> match int_of_string_opt s with | Some i when i >= 0 -> return i | _ -> failwith "Parameter should be a non-negative integer literal") let group = { Clic.name = "context"; title = "Block contextual commands (see option -block)"; } let binary_description = {Clic.name = "description"; title = "Binary Description"} let commands () = let open Clic in [ command ~group ~desc:"Access the timestamp of the block." (args1 (switch ~doc:"output time in seconds" ~short:'s' ~long:"seconds" ())) (fixed ["get"; "timestamp"]) (fun seconds (cctxt : Alpha_client_context.full) -> Shell_services.Blocks.Header.shell_header cctxt ~block:cctxt#block () >>=? fun {timestamp = v} -> (if seconds then cctxt#message "%Ld" (Time.Protocol.to_seconds v) else cctxt#message "%s" (Time.Protocol.to_notation v)) >>= fun () -> return_unit); command ~group ~desc:"Lists all non empty contracts of the block." no_options (fixed ["list"; "contracts"]) (fun () (cctxt : Alpha_client_context.full) -> list_contract_labels cctxt ~chain:`Main ~block:cctxt#block >>=? fun contracts -> List.iter_s (fun (alias, hash, kind) -> cctxt#message "%s%s%s" hash kind alias) contracts >>= fun () -> return_unit); command ~group ~desc:"Get the balance of a contract." no_options (prefixes ["get"; "balance"; "for"] @@ ContractAlias.destination_param ~name:"src" ~desc:"source contract" @@ stop) (fun () (_, contract) (cctxt : Alpha_client_context.full) -> get_balance cctxt ~chain:`Main ~block:cctxt#block contract >>=? fun amount -> cctxt#answer "%a %s" Tez.pp amount Client_proto_args.tez_sym >>= fun () -> return_unit); command ~group ~desc:"Get the storage of a contract." no_options (prefixes ["get"; "script"; "storage"; "for"] @@ ContractAlias.destination_param ~name:"src" ~desc:"source contract" @@ stop) (fun () (_, contract) (cctxt : Alpha_client_context.full) -> get_storage cctxt ~chain:`Main ~block:cctxt#block contract >>=? function | None -> cctxt#error "This is not a smart contract." | Some storage -> cctxt#answer "%a" Michelson_v1_printer.print_expr_unwrapped storage >>= fun () -> return_unit); command ~group ~desc: "Get the value associated to a key in the big map storage of a \ contract." no_options (prefixes ["get"; "big"; "map"; "value"; "for"] @@ Clic.param ~name:"key" ~desc:"the key to look for" data_parameter @@ prefixes ["of"; "type"] @@ Clic.param ~name:"type" ~desc:"type of the key" data_parameter @@ prefix "in" @@ ContractAlias.destination_param ~name:"src" ~desc:"source contract" @@ stop) (fun () key key_type (_, contract) (cctxt : Alpha_client_context.full) -> get_big_map_value cctxt ~chain:`Main ~block:cctxt#block contract (key.expanded, key_type.expanded) >>=? function | None -> cctxt#error "No value associated to this key." | Some value -> cctxt#answer "%a" Michelson_v1_printer.print_expr_unwrapped value >>= fun () -> return_unit); command ~group ~desc:"Get the code of a contract." no_options (prefixes ["get"; "script"; "code"; "for"] @@ ContractAlias.destination_param ~name:"src" ~desc:"source contract" @@ stop) (fun () (_, contract) (cctxt : Alpha_client_context.full) -> get_script cctxt ~chain:`Main ~block:cctxt#block contract >>=? function | None -> cctxt#error "This is not a smart contract." | Some {code; storage = _} -> ( match Script_repr.force_decode code with | Error errs -> cctxt#error "%a" (Format.pp_print_list ~pp_sep:Format.pp_print_newline Environment.Error_monad.pp) errs | Ok (code, _) -> let {Michelson_v1_parser.source} = Michelson_v1_printer.unparse_toplevel code in cctxt#answer "%s" source >>= return)); command ~group ~desc:"Get the manager of a contract." no_options (prefixes ["get"; "manager"; "for"] @@ ContractAlias.destination_param ~name:"src" ~desc:"source contract" @@ stop) (fun () (_, contract) (cctxt : Alpha_client_context.full) -> Client_proto_contracts.get_manager cctxt ~chain:`Main ~block:cctxt#block contract >>=? fun manager -> Public_key_hash.rev_find cctxt manager >>=? fun mn -> Public_key_hash.to_source manager >>=? fun m -> cctxt#message "%s (%s)" m (match mn with None -> "unknown" | Some n -> "known as " ^ n) >>= fun () -> return_unit); command ~group ~desc:"Get the delegate of a contract." no_options (prefixes ["get"; "delegate"; "for"] @@ ContractAlias.destination_param ~name:"src" ~desc:"source contract" @@ stop) (fun () (_, contract) (cctxt : Alpha_client_context.full) -> Client_proto_contracts.get_delegate cctxt ~chain:`Main ~block:cctxt#block contract >>=? function | None -> cctxt#message "none" >>= fun () -> return_unit | Some delegate -> Public_key_hash.rev_find cctxt delegate >>=? fun mn -> Public_key_hash.to_source delegate >>=? fun m -> cctxt#message "%s (%s)" m (match mn with None -> "unknown" | Some n -> "known as " ^ n) >>= fun () -> return_unit); command ~desc:"Get receipt for past operation" (args1 (default_arg ~long:"check-previous" ~placeholder:"num_blocks" ~doc:"number of previous blocks to check" ~default:"10" non_negative_param)) (prefixes ["get"; "receipt"; "for"] @@ param ~name:"operation" ~desc:"Operation to be looked up" (parameter (fun _ x -> match Operation_hash.of_b58check_opt x with | None -> Error_monad.failwith "Invalid operation hash: '%s'" x | Some hash -> return hash)) @@ stop) (fun predecessors operation_hash (ctxt : Alpha_client_context.full) -> display_receipt_for_operation ctxt ~chain:`Main ~predecessors operation_hash >>=? fun _ -> return_unit); command ~group:binary_description ~desc:"Describe unsigned block header" no_options (fixed ["describe"; "unsigned"; "block"; "header"]) (fun () (cctxt : Alpha_client_context.full) -> cctxt#message "%a" Data_encoding.Binary_schema.pp (Data_encoding.Binary.describe Alpha_context.Block_header.unsigned_encoding) >>= fun () -> return_unit); command ~group:binary_description ~desc:"Describe unsigned operation" no_options (fixed ["describe"; "unsigned"; "operation"]) (fun () (cctxt : Alpha_client_context.full) -> cctxt#message "%a" Data_encoding.Binary_schema.pp (Data_encoding.Binary.describe Alpha_context.Operation.unsigned_encoding) >>= fun () -> return_unit); ]
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
encoded_word.ml
open Core open Angstrom module Let_syntax = struct let bind t ~f = t >>= f let map t ~f = t >>| f let both a b = lift2 Tuple2.create a b end let ws = take_while1 Char.is_whitespace let charset = choice (* The following might not be an exhaustive list. We can add to this as we encounter more cases. *) [ string_ci "US-ASCII" >>| const `Ascii ; string_ci "UTF-8" >>| const `Utf8 ; string_ci "ISO-8859-1" >>| const `Latin1 ; string_ci "ISO-8859-2" >>| const `Latin2 ; string_ci "GB2312" >>| const `GB2312 ] ;; let encoding : [ `Base64 | `Quoted_printable ] Angstrom.t = choice [ string_ci "B" >>| const `Base64; string_ci "Q" >>| const `Quoted_printable ] ;; let parser_ : string Angstrom.t = let%bind () = string "=?" >>| ignore and charset = charset and () = string "?" >>| ignore and encoding = encoding and () = string "?" >>| ignore and data = take_while (function | '?' -> false | c -> (not (Char.is_whitespace c)) && Char.is_print c) and () = string "?=" >>| ignore in let%bind data = match encoding with | `Quoted_printable -> (* RFC2047 deviates slightly from common quoted printable. In particular 4.2(2) - Underscore may be used to encode space, and 4.2(3)- underscore must be encoded. This substituion handles that decoding step. *) let data = String.substr_replace_all data ~pattern:"_" ~with_:" " in let data_bstr, _ = Quoted_printable_lexer.decode_quoted_printable (String.length data) (Lexing.from_string data) in return (Bigbuffer.contents data_bstr) | `Base64 -> (match Base64.decode data with | Ok data -> return data | Error (`Msg msg) -> fail msg) in match charset with | `Ascii | `Utf8 | `Latin1 | `Latin2 | `GB2312 -> return data ;; let parser_many : string Angstrom.t = many (choice [ (let%map hd = parser_ and tl = (* RFC2047 6.2 When displaying a particular header field that contains multiple 'encoded-word's, any 'linear-white-space' that separates a pair of adjacent 'encoded-word's is ignored. *) many (let%bind (_ : string) = option "" ws in parser_) in hd :: tl) ; (let%map c = choice [ take_while1 (function | '=' -> false | c -> not (Char.is_whitespace c)) ; string "=" (* Collapse Line breaks as per RFC822 - 3.1.1 Unfolding is accomplished by regarding CRLF immediately followed by an LWSP-char as equivalent to the LWSP-char. RFC822 - 3.1.3 Rules of (un)folding apply to these (unstructured) fields *) ; (let%bind (_ : string) = choice [ string "\r\n"; string "\n" ] in ws) (* The RFC is ambiguous on what should happen if there is a lone CRLF, so we ignore those, and treat these as regular white space. The RFC is also ambiguous on how to treat multiple consecutive whitespaces, so we do the conservative thing and leave them exactly as is. *) ; ws ] in [ c ]) ]) >>| List.concat >>| String.concat ~sep:"" ;; let decode str = Angstrom.parse_string ~consume:Prefix parser_many str |> Result.map_error ~f:Error.of_string ;;
git_unix.ml
open Lwt.Infix let ( >>? ) x f = let open Lwt.Infix in x >>= function Ok x -> f x | Error err -> Lwt.return_error err let ( <.> ) f g x = f (g x) (* XXX(dinosaure): NOTE! [Git_unix] wants to provide an implementation * which can fit into required modules by [Git.Store] __and__ the usual * layout of a non-bare Git repository. * * Nothing was done about performances - and provided implementations * are surely not the best. If someone wants a _fast_ implementation * of Git, this is the first entry-point. *) module Fold = struct let src = Logs.Src.create "git-unix.fold" ~doc:"logs git-unix's fold event" module Log = (val Logs.src_log src : Logs.LOG) let always x _ = x let rec contents ?(dotfiles = false) ?(rel = false) dir = let rec readdir dh acc = Lwt.catch (fun () -> Lwt_unix.readdir dh >>= Lwt.return_some) (fun _exn -> Lwt.return_none) >>= function | None -> Lwt.return acc | Some (".." | ".") -> readdir dh acc | Some f when dotfiles || not (f.[0] = '.') -> ( match Fpath.of_string f with | Ok f -> readdir dh ((if rel then f else Fpath.(dir // f)) :: acc) | Error (`Msg _) -> (* ignore *) readdir dh acc) | Some _ -> readdir dh acc in Lwt.catch (fun () -> Lwt_unix.opendir (Fpath.to_string dir) >>= fun dh -> readdir dh [] >>= fun res -> Lwt_unix.closedir dh >>= fun () -> Lwt.return res) (function | Unix.Unix_error (Unix.EINTR, _, _) -> contents ~dotfiles ~rel dir | Unix.Unix_error (err, _, _) -> let err = Fmt.str "directory contents %a: %s" Fpath.pp dir (Unix.error_message err) in Log.err (fun m -> m "%s" err); Lwt.return [] | exn -> Lwt.fail exn) let do_traverse_fun = function | `Any -> always true | `None -> always false | `Sat sat -> sat let rec exists path = Lwt.catch (fun () -> Lwt_unix.stat (Fpath.to_string path) >>= fun _ -> Lwt.return true) @@ function | Unix.Unix_error ((Unix.ENOENT | Unix.ENOTDIR), _, _) -> Lwt.return false | Unix.Unix_error (Unix.EINTR, _, _) -> exists path | exn -> Lwt.fail exn let rec file_exists path = Lwt.catch (fun () -> Lwt_unix.stat (Fpath.to_string path) >>= fun stat -> Lwt.return (stat.Unix.st_kind = Unix.S_REG)) @@ function | Unix.Unix_error (Unix.ENOENT, _, _) -> Lwt.return false | Unix.Unix_error (Unix.EINTR, _, _) -> file_exists path | exn -> Lwt.fail exn let rec dir_exists path = Lwt.catch (fun () -> Lwt_unix.stat (Fpath.to_string path) >>= fun stat -> Lwt.return (stat.Unix.st_kind = Unix.S_DIR)) @@ function | Unix.Unix_error (Unix.ENOENT, _, _) -> Lwt.return false | Unix.Unix_error (Unix.EINTR, _, _) -> dir_exists path | exn -> Lwt.fail exn let is_element_fun = function | `Any -> exists | `Files -> file_exists | `Dirs -> dir_exists | `Sat sat -> sat let readdir_fun = let readdir d = try Sys.readdir (Fpath.to_string d) with _exn -> [||] in Lwt.return <.> Array.to_list <.> readdir let fold ?(dotfiles = false) ?(elements = `Any) ?(traverse = `Any) f acc paths = let process () = let do_traverse = do_traverse_fun traverse in let is_element = is_element_fun elements in let is_dir = dir_exists in let readdir = readdir_fun in let process_path p (acc, to_traverse) = Lwt.both (is_element p) (is_dir p) >>= function | false, true when do_traverse p -> Lwt.return (acc, p :: to_traverse) | true, true when do_traverse p -> Lwt.both (f p acc) (Lwt.return (p :: to_traverse)) | true, _ -> Lwt.both (f p acc) (Lwt.return to_traverse) | _ -> Lwt.return (acc, to_traverse) in let dir_child d acc bname = if (not dotfiles) && bname.[0] = '.' then Lwt.return acc else process_path Fpath.(d / bname) acc in let rec loop acc = function | (d :: ds) :: up -> readdir d >>= fun childs -> Lwt_list.fold_left_s (dir_child d) (acc, []) childs >>= fun (acc, to_traverse) -> loop acc (to_traverse :: ds :: up) | [ [] ] -> Lwt.return acc | [] :: up -> loop acc up | _ -> assert false in let init acc p = let base = Fpath.(basename @@ normalize p) in if (not dotfiles) && base.[0] = '.' then Lwt.return acc else process_path p acc in Lwt_list.fold_left_s init (acc, []) paths >>= fun (acc, to_traverse) -> loop acc [ to_traverse ] in process () let fold ?dotfiles ?elements ?traverse f acc d = contents d >>= fold ?dotfiles ?elements ?traverse f acc end module Minor_heap (Digestif : Digestif.S) = struct let src = Logs.Src.create "git-unix.minor" ~doc:"logs git-unix's minor heap event" module Log = (val Logs.src_log src : Logs.LOG) type t = Fpath.t (* [.git/objects] *) type uid = Digestif.t type error = [ `Not_found of Digestif.t | `Msg of string ] let pp_error ppf = function | `Not_found uid -> Fmt.pf ppf "%a not found" Digestif.pp uid | `Msg err -> Fmt.string ppf err type +'a fiber = 'a Lwt.t let split uid = let hex = Digestif.to_hex uid in String.sub hex 0 2, String.sub hex 2 ((Digestif.digest_size * 2) - 2) let rec exists root uid = let hd, tl = split uid in let path = Fpath.(root / hd / tl) in let process () = Lwt_unix.stat (Fpath.to_string path) >>= fun _ -> Lwt.return true in let error = function | Unix.Unix_error (Unix.EACCES, _, _) -> Lwt.return false | Unix.Unix_error (Unix.ENOENT, _, _) -> Lwt.return false | Unix.Unix_error (Unix.EINTR, _, _) -> exists root uid | exn -> Lwt.fail exn in Lwt.catch process error let rec length root uid = let hd, tl = split uid in let path = Fpath.(root / hd / tl) in let process () = Lwt_unix.LargeFile.stat (Fpath.to_string path) >>= fun stat -> Lwt.return_ok stat.Unix.LargeFile.st_size in let error = function | Unix.Unix_error (Unix.EACCES, _, _) -> Lwt.return_error (`Not_found uid) | Unix.Unix_error (Unix.ENOENT, _, _) -> Lwt.return_error (`Not_found uid) | Unix.Unix_error (Unix.EINTR, _, _) -> length root uid | exn -> Lwt.fail exn in Lwt.catch process error let rec map root uid ~pos len = if pos < 0L || len < 0 then invalid_arg "Minor_heap.map: invalid bounds"; let hd, tl = split uid in let path = Fpath.(root / hd / tl) in let rec process () = Lwt_unix.LargeFile.stat (Fpath.to_string path) >>= fun stat -> try let len = if Int64.add pos (Int64.of_int len) > stat.Lwt_unix.LargeFile.st_size then Int64.to_int (Int64.sub stat.Lwt_unix.LargeFile.st_size pos) else len in let fd = Unix.openfile (Fpath.to_string path) Unix.[ O_RDONLY ] 0o400 in let rs = Unix.map_file fd ~pos Bigarray.char Bigarray.c_layout false [| len |] in Unix.close fd; Lwt.return (Bigarray.array1_of_genarray rs) with | Unix.Unix_error (Unix.EACCES, _, _) | Unix.Unix_error (Unix.ENOENT, _, _) -> Lwt.return Bigstringaf.empty | Unix.Unix_error (Unix.EINTR, _, _) -> process () in let error = function | Unix.Unix_error (Unix.EACCES, _, _) -> Lwt.return Bigstringaf.empty | Unix.Unix_error (Unix.ENOENT, _, _) -> Lwt.return Bigstringaf.empty | Unix.Unix_error (Unix.EINTR, _, _) -> map root uid ~pos len | exn -> Lwt.fail exn in Lwt.catch process error let append root uid payload = (* XXX(dinosaure): [irmin] expects an atomicity about the creation of [uid]. * This does not mean an atomicty about the creation and the filling of [uid]! * This assumption requires an atomicity about [mkdir / openfile]. * * A problem /can/ occur when we use [Lwt_unix.mkdir] which can /yield/. In such * case, [uid] still does not exist. However, [irmin] expects, at least, the existence * of it (whatever if we wrote entirely, partially or nothing). * * We should optimize this function but we need to keep this assumption - * which was not really clear. * * More precisely, a data-race condition exists when [irmin] wants to save 2 times the * same object from 2 different fibers. One can create the given object partially and * the other can try to read it, if such case appear, the second considers the object * as an non-existent object (but the second fiber is may be used to update a reference). * Finally, we assert the requirement of the atomicity about [append{v}]. However, the * bug discovered is really strange (replication of the bug can be done with [irmin-unix], * test [GIT.021]) *) Log.debug (fun m -> m "Minor.append %a" Digestif.pp uid); let hd, tl = split uid in let path = Fpath.(root / hd / tl) in let fiber () = let open Rresult in Bos.OS.Dir.create Fpath.(root / hd) >>= fun _ -> Bos.OS.File.write path (Bigstringaf.to_string payload) in Lwt.return (fiber ()) let f emitter (tmp, payloads) = let rec go pos = function | [] -> emitter None; Rresult.R.ok () | src :: rest as payloads -> let len = min (Bytes.length tmp) (Bigstringaf.length src - pos) in Bigstringaf.blit_to_bytes src ~src_off:pos tmp ~dst_off:0 ~len; emitter (Some (tmp, 0, len)); let pos = pos + len in if pos = Bigstringaf.length src then go 0 rest else go pos payloads in go 0 payloads let appendv root uid payloads = Log.debug (fun m -> m "Minor.appendv %a" Digestif.pp uid); let hd, tl = split uid in let path = Fpath.(root / hd / tl) in let fiber () = let open Rresult in Bos.OS.Dir.create Fpath.(root / hd) >>= fun _ -> Bos.OS.File.with_output path f (Bytes.create De.io_buffer_size, payloads) in Lwt.return (Rresult.R.join (fiber ())) let list root = let f x r = match List.rev (Fpath.segs x) with | tl :: hd :: _ -> let uid = Digestif.of_hex (hd ^ tl) in Lwt.return (uid :: r) | _ -> Lwt.return r in let elements path = match List.rev (Fpath.segs path) with | tl :: hd :: _ -> ( match Digestif.of_hex (hd ^ tl) with | _ -> Fold.file_exists path | exception _ -> Lwt.return false) | _ -> Lwt.return false in Fold.fold ~dotfiles:false ~elements:(`Sat elements) f [] root let reset root = list root >>= fun lst -> let rec f uid = let hd, tl = split uid in let path = Fpath.(root / hd / tl) in Lwt.catch (fun () -> Lwt_unix.unlink (Fpath.to_string path)) (function | Unix.Unix_error (Unix.EINTR, _, _) -> f uid | Unix.Unix_error (Unix.ENOENT, _, _) -> Lwt.return_unit | exn -> Lwt.fail exn) in Lwt_list.iter_p f lst >>= Lwt.return_ok end module Major_heap = struct let src = Logs.Src.create "git-unix.major" ~doc:"logs git-unix's major heap event" module Log = (val Logs.src_log src : Logs.LOG) type t = Fpath.t (* [.git/objects/pack] *) type uid = Fpath.t type 'a rd = < rd : unit ; .. > as 'a type 'a wr = < wr : unit ; .. > as 'a type 'a mode = | Rd : < rd : unit > mode | Wr : < wr : unit > mode | RdWr : < rd : unit ; wr : unit > mode type 'a fd = Lwt_unix.file_descr type error = [ `Not_found of uid ] type +'a fiber = 'a Lwt.t let pp_error : error Fmt.t = fun ppf -> function | `Not_found uid -> Fmt.pf ppf "%a not found" Fpath.pp uid (* XXX(dinosaure): currently, [Major_heap] has a read and a write access due to [append] which is only call by [Store.Sync]. We should provide 2 [Major_heap]: - one used by [Store] which is read-only - the second used by [Store.Sync] which is write-only A [mode] is better (to avoid duplicate) and safe. *) let create : type a. ?trunc:bool -> mode:a mode -> t -> uid -> (a fd, error) result Lwt.t = fun ?(trunc = true) ~mode root path -> let path = Fpath.(root // path) in let flags, perm = match mode with | Rd -> Unix.[ O_RDONLY ], 0o400 | Wr -> Unix.[ O_WRONLY; O_CREAT; O_APPEND ], 0o600 | RdWr -> Unix.[ O_RDWR; O_CREAT; O_APPEND ], 0o600 in let flags = if trunc then Unix.O_TRUNC :: flags else flags in let rec process () = Lwt_unix.openfile (Fpath.to_string path) flags perm >>= fun fd -> Lwt.return_ok fd and error = function | Unix.Unix_error (Unix.ENOENT, _, _) | Unix.Unix_error (Unix.EACCES, _, _) -> Printexc.print_backtrace stdout; flush stdout; Log.err (fun m -> m "%a does not exists." Fpath.pp path); Lwt.return_error (`Not_found path) | Unix.Unix_error (Unix.EINTR, _, _) -> Lwt.catch process error | exn -> Lwt.fail exn in Lwt.catch process error let map : t -> [> `Rd ] fd -> pos:int64 -> int -> Bigstringaf.t = fun _ fd ~pos len -> let fd = Lwt_unix.unix_file_descr fd in let payload = Unix.map_file fd ~pos Bigarray.char Bigarray.c_layout false [| len |] in Bigarray.array1_of_genarray payload let close _ fd = let rec process () = Lwt_unix.close fd >>= fun () -> Lwt.return_ok () and error = function | Unix.Unix_error (Unix.EINTR, _, _) -> Lwt.catch process error | exn -> Lwt.fail exn in Lwt.catch process error let length fd = let rec process () = Lwt_unix.LargeFile.fstat fd >>= fun st -> Lwt.return st.Unix.LargeFile.st_size and error = function | Unix.Unix_error (Unix.EINTR, _, _) -> Lwt.catch process error | exn -> Lwt.fail exn in Lwt.catch process error let list root = let res = let open Rresult in Bos.OS.Dir.contents ~dotfiles:false ~rel:true root >>| List.filter (Fpath.has_ext "pack") in match res with | Ok lst -> Lwt.return lst | Error (`Msg err) -> Log.warn (fun m -> m "Major.list: %s" err); Lwt.return [] let reset root = list root >>= fun lst -> let rec f path = Lwt.catch (fun () -> Lwt_unix.unlink Fpath.(to_string (root // path)) >>= fun () -> Lwt_unix.unlink Fpath.(to_string (root // set_ext "idx" path))) (function | Unix.Unix_error (Unix.EINTR, _, _) -> f path | exn -> Log.warn (fun m -> m "Got an error while deleting %a: %s" Fpath.pp path (Printexc.to_string exn)); Lwt.return_unit) in Lwt_list.iter_p f lst >>= Lwt.return_ok let move root ~src ~dst = let src = Fpath.(root // src) in let dst = Fpath.(root // dst) in Lwt_unix.rename (Fpath.to_string src) (Fpath.to_string dst) >>= fun () -> Lwt.return_ok () let append : t -> [> `Wr ] fd -> string -> unit fiber = fun _ fd str -> let rec go (off, len) = Lwt_unix.write_string fd str off len >>= fun len' -> if len = len' then Lwt.return () else go (off + len', len - len') in go (0, String.length str) end module Unix = struct include Unix let mkdir ?(path = true) ?(mode = 0o755) dir = let rec exists dir = Lwt.catch (fun () -> Lwt_unix.stat (Fpath.to_string dir) >>= fun stat -> Lwt.return_ok (stat.Unix.st_kind = Unix.S_DIR)) (function | Unix.Unix_error (Unix.ENOENT, _, _) -> Lwt.return_ok false | Unix.Unix_error (Unix.EINTR, _, _) -> exists dir | exn -> Lwt.fail exn) in let rec mkdir d mode = Lwt.catch (fun () -> Lwt_unix.mkdir (Fpath.to_string d) mode >>= Lwt.return_ok) (function | Unix.Unix_error (Unix.EEXIST, _, _) -> Lwt.return_ok () | Unix.Unix_error (Unix.EINTR, _, _) -> mkdir d mode | Unix.Unix_error (e, _, _) -> if d = dir then Lwt.return_error @@ Rresult.R.msgf "create directory %a: %s" Fpath.pp d (Unix.error_message e) else Lwt.return_error @@ Rresult.R.msgf "create directory %a: %a: %s" Fpath.pp dir Fpath.pp d (Unix.error_message e) | exn -> Lwt.fail exn) in exists dir >>? function | true -> Lwt.return_ok false | false -> ( match path with | false -> mkdir dir mode >>? fun () -> Lwt.return_ok false | true -> let rec dirs_to_create p acc = exists p >>? function | true -> Lwt.return_ok acc | false -> dirs_to_create (Fpath.parent p) (p :: acc) in let rec create_them dirs () = match dirs with | dir :: dirs -> mkdir dir mode >>? create_them dirs | [] -> Lwt.return_ok () in dirs_to_create dir [] >>? fun dirs -> create_them dirs () >>? fun () -> Lwt.return_ok true) end module Reference_heap = struct let src = Logs.Src.create "git-unix.reference" ~doc:"logs git-unix's reference heap event" module Log = (val Logs.src_log src : Logs.LOG) type +'a fiber = 'a (* XXX(dinosaure): ensure the atomicity. *) type t = Fpath.t (* [.git] *) type error = [ `Not_found of Git.Reference.t | `Msg of string ] let pp_error ppf = function | `Not_found refname -> Fmt.pf ppf "%a not found" Git.Reference.pp refname | `Msg err -> Fmt.string ppf err let safely_unlink filename = let rec unlink filename = try Unix.unlink filename with | Unix.Unix_error (Unix.ENOENT, _, _) -> () | Unix.Unix_error (Unix.EINTR, _, _) -> unlink filename | Unix.Unix_error (err, _, _) -> Fmt.failwith "unlink %s: %s" filename (Unix.error_message err) in unlink filename let atomic_wr root refname str = Log.debug (fun m -> m "Writing %a: %S." Git.Reference.pp refname str); let path = List.fold_left Fpath.add_seg root (Git.Reference.segs refname) in let base, _ = Fpath.split_base path in let open Rresult in Bos.OS.Dir.create ~path:true base >>= fun _ -> Bos.OS.Dir.exists path >>= fun res -> (if res then Bos.OS.Dir.delete ~must_exist:false ~recurse:true path else R.ok ()) >>= fun () -> Bos.OS.File.tmp "git-reference-%s" >>= fun src -> Bos.OS.File.write src str >>= fun () -> let fd = Unix.openfile (Fpath.to_string src) Unix.[ O_WRONLY ] 0o644 in Unix.close fd; (* XXX(dinosaure): on Windows, [rename] requires that [path] does not * exist! *) if Sys.os_type = "Win32" then safely_unlink (Fpath.to_string path); Unix.rename (Fpath.to_string src) (Fpath.to_string path); R.ok () let atomic_rd root refname = Log.debug (fun m -> m "Reading %a." Git.Reference.pp refname); let path = List.fold_left Fpath.add_seg root (Git.Reference.segs refname) in let open Rresult in Bos.OS.File.exists path >>= function | true -> let fd = Unix.openfile (Fpath.to_string path) Unix.[ O_RDONLY ] 0o644 in let { Unix.st_size; _ } = Unix.fstat fd in let rs = Bytes.create st_size in let ln = Unix.read fd rs 0 st_size in assert (ln = st_size); Unix.close fd; R.ok (Bytes.unsafe_to_string rs) | false -> R.error (`Not_found refname) let atomic_rm root refname = Log.debug (fun m -> m "Deleting %a." Git.Reference.pp refname); let path = List.fold_left Fpath.add_seg root (Git.Reference.segs refname) in Bos.OS.File.delete path let list root = let f x r = match Fpath.rem_prefix root x with | Some x -> ( Log.debug (fun l -> l "%a exists into the store." Fpath.pp x); match Git.Reference.of_string (Fpath.to_string x) with | Ok x -> x :: r | Error _ -> r) | None -> assert false (* XXX(dinosaure): see [elements]. *) in let elements path = match Option.map Fpath.segs (Fpath.rem_prefix root path) with | Some ("objects" :: _) -> Ok false | Some [ "HEAD" ] -> Bos.OS.File.exists path | Some ("refs" :: _) -> Bos.OS.File.exists path | _ -> Ok false in Log.debug (fun l -> l "Listing references into %a." Fpath.pp root); match Bos.OS.Dir.fold_contents ~dotfiles:false ~elements:(`Sat elements) f [] root with | Ok lst -> lst | Error (`Msg err) -> Log.warn (fun m -> m "error when we listing references: %s" err); [] let reset root = let open Rresult in let lst = list root in let f refname = let path = List.fold_left Fpath.add_seg root (Git.Reference.segs refname) in match Bos.OS.Path.delete path with | Ok () -> () | Error (`Msg err) -> Log.warn (fun m -> m "error when we deleting %a: %s" Fpath.pp path err) in List.iter f lst; R.ok () end module Make (Digestif : Digestif.S) = struct module Mn = Minor_heap (Digestif) include Git.Store.Make (Digestif) (Mn) (Major_heap) (Reference_heap) let major_uid = { Git.Store.pck_major_uid_of_uid = (fun _root uid -> Fpath.v (Fmt.str "pack-%s.pack" (Digestif.to_hex uid))); Git.Store.idx_major_uid_of_uid = (fun _root uid -> Fpath.v (Fmt.str "pack-%s.idx" (Digestif.to_hex uid))); Git.Store.uid_of_major_uid = (fun path -> let str = Fpath.basename (Fpath.rem_ext path) in match Astring.String.cut ~sep:"pack-" str with | Some ("", uid) -> Digestif.of_hex uid | _ -> Fmt.invalid_arg "Invalid major uniq ID: %a" Fpath.pp path); } let update_head refs = match Reference_heap.atomic_rd refs Git.Reference.head with | Error (`Not_found _) -> Reference_heap.atomic_wr refs Git.Reference.head (Fmt.str "ref: %a\n" Git.Reference.pp Git.Reference.master) |> Lwt.return | Ok _ -> Lwt.return_ok () | Error (`Msg _ as err) -> Lwt.return_error err let v ?dotgit root = let dotgit = match dotgit with Some v -> v | None -> Fpath.(root / ".git") in let packed = Packed_refs.load ~of_hex:Hash.of_hex dotgit in let minor = Fpath.(dotgit / "objects") in let major = Fpath.(dotgit / "objects" / "pack") in let temp = Fpath.(dotgit / "tmp") in let refs = dotgit in Bos.OS.Dir.set_default_tmp temp; Unix.mkdir ~path:true refs >>? fun _ -> Unix.mkdir ~path:true temp >>? fun _ -> Unix.mkdir ~path:true Fpath.(refs / "refs" / "heads") >>? fun _ -> Unix.mkdir ~path:true Fpath.(refs / "refs" / "tags") >>? fun _ -> update_head refs >>? fun _ -> Unix.mkdir ~path:true minor >>? fun _ -> Unix.mkdir ~path:true major >>? fun _ -> let open Lwt.Infix in (* TODO(dinosaure): [stat] directories. *) v ~dotgit ~minor ~major ~major_uid ~refs ~packed root >>= fun x -> Lwt.return_ok x end module Store = Make (Digestif.SHA1) let ctx = Git_unix_mimic.ctx module Sync (Git_store : Git.S) = struct let src = Logs.Src.create "git-unix.sync" ~doc:"logs git-unix's sync event" module Log = (val Logs.src_log src : Logs.LOG) include Git.Sync.Make (Git_store.Hash) (Major_heap) (Major_heap) (Git_store) let random_gen = lazy (Random.State.make_self_init ()) let random_path pat = let rand = Random.State.bits (Lazy.force random_gen) land 0xFFFFFF in Fpath.v (Fmt.str pat (Fmt.str "%06x" rand)) let failwithf fmt = Fmt.kstr (fun err -> Lwt.fail (Failure err)) fmt let create_tmp_path mode dir pat = let rec loop count = if count < 0 then failwithf "Create a temporary file %s in %a: too many failing attempts" (Fmt.str pat "XXXXXX") Fpath.pp dir else let file = random_path pat in let sfile = Fpath.to_string Fpath.(dir // file) in let open_flags = Unix.[ O_WRONLY; O_CREAT; O_EXCL; O_SHARE_DELETE ] in let process () = Lwt_unix.openfile sfile open_flags mode >>= fun fd -> Lwt.return (file, fd) in let error = function | Unix.Unix_error (Unix.EEXIST, _, _) -> loop (pred count) | Unix.Unix_error (Unix.EINTR, _, _) -> loop count | exn -> Lwt.fail exn in Lwt.catch process error in loop 10000 let tmp ?(mode = 0o600) dir pat = create_tmp_path mode dir pat >>= fun (file, fd) -> Lwt_unix.close fd >>= fun () -> Lwt.return file let stream_of_file ?(chunk = De.io_buffer_size) path = let stream, emitter = Lwt_stream.create () in let fill () = Lwt_unix.openfile (Fpath.to_string path) Unix.[ O_RDONLY ] 0o644 >>= fun fd -> let rec go () = let tmp = Bytes.create chunk in Lwt.catch (fun () -> Lwt_unix.read fd tmp 0 chunk >>= function | 0 -> emitter None; Lwt_unix.close fd | len -> emitter (Some (Bytes.sub_string tmp 0 len)); go ()) (fun _exn -> emitter None; Lwt_unix.close fd) in go () in Lwt.async fill; fun () -> Lwt_stream.get stream let fetch ?(push_stdout = ignore) ?(push_stderr = ignore) ?threads ~ctx edn store ?version ?capabilities ?deepen want = let dotgit = Git_store.dotgit store in let temp = Fpath.(dotgit / "tmp") in tmp temp "pack-%s.pack" >>= fun src -> tmp temp "pack-%s.pack" >>= fun dst -> tmp temp "pack-%s.idx" >>= fun idx -> let create_idx_stream () = stream_of_file Fpath.(temp // idx) in let create_pack_stream () = stream_of_file Fpath.(temp // dst) in fetch ~push_stdout ~push_stderr ?threads ~ctx edn store ?version ?capabilities ?deepen want ~src ~dst ~idx ~create_idx_stream ~create_pack_stream temp temp let push ~ctx edn store ?version ?capabilities cmds = push ~ctx edn store ?version ?capabilities cmds end
(* * Copyright (c) 2013-2017 Thomas Gazagnaire <thomas@gazagnaire.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
limit.ml
type 'a t = 'a option let unknown = None let known x = Some x let of_option = Fun.id let is_unknown = Option.is_none let join (type a) ~where eq (l1 : a t) (l2 : a t) = match (l1, l2) with | None, None -> Result.return_none | Some x, None | None, Some x -> Result.return_some x | Some x, Some y -> if eq x y then Result.return_some x else error_with "Limit.join: error (%s)" where let%expect_test "join" = let pp_print_err fmt = function | Result.Error _ -> Format.pp_print_string fmt "error" | Ok x -> Format.( pp_print_option ~none:(fun fmt () -> pp_print_string fmt "None") pp_print_bool) fmt x in let print x = Format.fprintf Format.std_formatter "%a" pp_print_err x in print (join ~where:__LOC__ Bool.equal (Some true) (Some true)) ; [%expect {| true |}] ; print (join ~where:__LOC__ Bool.equal None None) ; [%expect {| None |}] ; print (join ~where:__LOC__ Bool.equal None (Some true)) ; [%expect {| true |}] ; print (join ~where:__LOC__ Bool.equal (Some true) None) ; [%expect {| true |}] ; print (join ~where:__LOC__ Bool.equal (Some true) (Some false)) ; [%expect {| error |}] let get ~when_unknown = function | None -> error_with "Limit.get: %s" when_unknown | Some x -> ok x let%expect_test "get" = let pp_print_err fmt = function | Result.Error _ -> Format.fprintf fmt "error" | Ok b -> Format.pp_print_bool fmt b in let print x = Format.fprintf Format.std_formatter "%a" pp_print_err x in print (get ~when_unknown:"" (Some true)) ; [%expect {| true |}] ; print (get ~when_unknown:"" None) ; [%expect {| error |}] let fold ~unknown ~known x = match x with None -> unknown | Some x -> known x let value ~when_unknown = function None -> when_unknown | Some x -> x
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
Skip_target.mli
(* This is using the skip_list.txt of pfff Skip_code.ml *) val exclude_files_in_skip_lists : Common.filename list -> Common.filename list * Output_from_core_t.skipped_target list (* This is using Flag_semgrep.max_target_bytes *) val exclude_big_files : Common.filename list -> Common.filename list * Output_from_core_t.skipped_target list (* Detecting and filtering minified files (for Javascript) *) val exclude_minified_files : Common.filename list -> Common.filename list * Output_from_core_t.skipped_target list
(* This is using the skip_list.txt of pfff Skip_code.ml *) val exclude_files_in_skip_lists :
sched.mli
module Task_ = Task module Sched_req_ = Sched_req type sched_id = int type task_store = Task_.task_data Task_id_map.t type task_store_diff = Task_.task_data Task_id_map_utils.diff type task_inst_store = Task_.task_inst_data Task_inst_id_map.t type task_inst_store_diff = Task_.task_inst_data Task_inst_id_map_utils.diff type task_seg_store = Task_.task_seg_size Task_seg_id_map.t type task_seg_store_diff = Task_.task_seg_size Task_seg_id_map_utils.diff type sched_req_store = Sched_req_.sched_req_data Sched_req_id_map.t type sched_req_store_diff = Sched_req_.sched_req_data Sched_req_id_map_utils.diff type sched_req_record_store = Sched_req_.sched_req_record_data Sched_req_id_map.t type sched_req_record_store_diff = Sched_req_.sched_req_record_data Sched_req_id_map_utils.diff type task_seg_place_map = Task_seg_id_set.t Int64_map.t type task_seg_place_map_diff = Int64_map_utils.Task_seg_id_bucketed.diff_bucketed type task_related_status = [ `Uncompleted | `Completed | `Discarded ] type sched_req_status = [ `Pending | `Discarded | `Recorded ] type store = { task_uncompleted_store : task_store; task_completed_store : task_store; task_discarded_store : task_store; task_inst_uncompleted_store : task_inst_store; task_inst_completed_store : task_inst_store; task_inst_discarded_store : task_inst_store; task_seg_uncompleted_store : task_seg_store; task_seg_completed_store : task_seg_store; task_seg_discarded_store : task_seg_store; user_id_to_task_ids : Int64_set.t User_id_map.t; task_id_to_task_inst_ids : Int64_set.t Task_id_map.t; task_inst_id_to_task_seg_ids : Int64_int64_option_set.t Task_inst_id_map.t; sched_req_ids : Int64_set.t; sched_req_pending_store : sched_req_store; sched_req_discarded_store : sched_req_store; sched_req_record_store : sched_req_record_store; quota : int64 Task_inst_id_map.t; task_seg_id_to_progress : Task_.progress Task_seg_id_map.t; task_inst_id_to_progress : Task_.progress Task_inst_id_map.t; } type store_diff = { task_uncompleted_store_diff : task_store_diff; task_completed_store_diff : task_store_diff; task_discarded_store_diff : task_store_diff; task_inst_uncompleted_store_diff : task_inst_store_diff; task_inst_completed_store_diff : task_inst_store_diff; task_inst_discarded_store_diff : task_inst_store_diff; task_seg_uncompleted_store_diff : task_seg_store_diff; task_seg_completed_store_diff : task_seg_store_diff; task_seg_discarded_store_diff : task_seg_store_diff; user_id_to_task_ids_diff : User_id_map_utils.Int64_bucketed.diff_bucketed; task_id_to_task_inst_ids_diff : Task_id_map_utils.Int64_bucketed.diff_bucketed; task_inst_id_to_task_seg_ids_diff : Task_inst_id_map_utils.Int64_int64_option_bucketed.diff_bucketed; sched_req_ids_diff : Int64_set_utils.diff; sched_req_pending_store_diff : sched_req_store_diff; sched_req_discarded_store_diff : sched_req_store_diff; sched_req_record_store_diff : sched_req_record_store_diff; quota_diff : int64 Task_inst_id_map_utils.diff; task_seg_id_to_progress_diff : Task_.progress Task_seg_id_map_utils.diff; task_inst_id_to_progress_diff : Task_.progress Task_inst_id_map_utils.diff; } type agenda = { indexed_by_task_seg_id : (int64 * int64) Task_seg_id_map.t; indexed_by_start : task_seg_place_map; indexed_by_end_exc : task_seg_place_map; } type agenda_diff = { indexed_by_task_seg_id_diff : (int64 * int64) Task_seg_id_map_utils.diff; indexed_by_start_diff : task_seg_place_map_diff; indexed_by_end_exc_diff : task_seg_place_map_diff; } type sched_data = { store : store; agenda : agenda; } type sched_data_diff = { store_diff : store_diff; agenda_diff : agenda_diff; } type sched = sched_id * sched_data type sched_diff = sched_id * sched_id * sched_data_diff val sched_data_empty : sched_data val empty : sched module Quota : sig val update_quota : int64 Task_inst_id_map.t -> sched -> sched val add_quota : int64 Task_inst_id_map.t -> sched -> sched end module Task : sig module Status : sig val get_task_status : Task_.task_id -> sched -> task_related_status option end module Add : sig val add_task : parent_user_id:Task_.user_id -> Task_.task_data -> Task_.task_inst_data list -> sched -> Task_.task * Task_.task_inst list * sched end module To_seq : sig val task_seq_uncompleted : sched -> Task_.task Seq.t val task_seq_completed : sched -> Task_.task Seq.t val task_seq_discarded : sched -> Task_.task Seq.t val task_seq_all : sched -> Task_.task Seq.t end module Find : sig val find_task_uncompleted_opt : Task_.task_id -> sched -> Task_.task_data option val find_task_completed_opt : Task_.task_id -> sched -> Task_.task_data option val find_task_discarded_opt : Task_.task_id -> sched -> Task_.task_data option val find_task_any_opt : Task_.task_id -> sched -> Task_.task_data option val find_task_any_with_status_opt : Task_.task_id -> sched -> (Task_.task_data * task_related_status) option end module Remove : sig val remove_task_uncompleted : ?remove_children_task_insts:bool -> ?remove_children_task_segs:bool -> Task_.task_id -> sched -> sched val remove_task_completed : ?remove_children_task_insts:bool -> ?remove_children_task_segs:bool -> Task_.task_id -> sched -> sched val remove_task_discarded : ?remove_children_task_insts:bool -> ?remove_children_task_segs:bool -> Task_.task_id -> sched -> sched val remove_task_all : ?remove_children_task_insts:bool -> ?remove_children_task_segs:bool -> Task_.task_id -> sched -> sched end module Move : sig val move_task_to_completed : Task_.task_id -> sched -> sched val move_task_to_uncompleted : Task_.task_id -> sched -> sched val move_task_to_discarded : Task_.task_id -> sched -> sched end end module Task_inst : sig module Status : sig val get_task_inst_status : Task_.task_inst_id -> sched -> task_related_status option end module Add : sig val add_task_inst : parent_task_id:Task_.task_id -> Task_.task_inst_data -> sched -> Task_.task_inst * sched val add_task_inst_list : parent_task_id:Task_.task_id -> Task_.task_inst_data list -> sched -> Task_.task_inst list * sched end module To_seq : sig val task_inst_seq_uncompleted : sched -> Task_.task_inst Seq.t val task_inst_seq_completed : sched -> Task_.task_inst Seq.t val task_inst_seq_discarded : sched -> Task_.task_inst Seq.t val task_inst_seq_all : sched -> Task_.task_inst Seq.t end module Find : sig val find_task_inst_uncompleted_opt : Task_.task_inst_id -> sched -> Task_.task_inst_data option val find_task_inst_completed_opt : Task_.task_inst_id -> sched -> Task_.task_inst_data option val find_task_inst_discarded_opt : Task_.task_inst_id -> sched -> Task_.task_inst_data option val find_task_inst_any_opt : Task_.task_inst_id -> sched -> Task_.task_inst_data option val find_task_inst_any_with_status_opt : Task_.task_inst_id -> sched -> (Task_.task_inst_data * task_related_status) option val find_task_inst_ids_by_task_id : Task_.task_id -> sched -> Task_.task_inst_id Seq.t val find_task_inst_seq_uncompleted_by_task_id : Task_.task_id -> sched -> Task_.task_inst Seq.t val find_task_inst_seq_completed_by_task_id : Task_.task_id -> sched -> Task_.task_inst Seq.t val find_task_inst_seq_discarded_by_task_id : Task_.task_id -> sched -> Task_.task_inst Seq.t val find_task_inst_seq_any_by_task_id : Task_.task_id -> sched -> Task_.task_inst Seq.t val find_task_inst_seq_any_with_status_by_task_id : Task_.task_id -> sched -> (Task_.task_inst * task_related_status) Seq.t end module Remove : sig val remove_task_inst_uncompleted : ?remove_children_task_segs:bool -> Task_.task_inst_id -> sched -> sched val remove_task_inst_completed : ?remove_children_task_segs:bool -> Task_.task_inst_id -> sched -> sched val remove_task_inst_discarded : ?remove_children_task_segs:bool -> Task_.task_inst_id -> sched -> sched val remove_task_inst_all : ?remove_children_task_segs:bool -> Task_.task_inst_id -> sched -> sched (* val remove_task_inst_uncompleted_strict : * ?remove_children_task_segs:bool -> * Task_.task_inst_id -> * sched -> * (sched, unit) result * * val remove_task_inst_completed_strict : * ?remove_children_task_segs:bool -> * Task_.task_inst_id -> * sched -> * (sched, unit) result * * val remove_task_inst_discarded_strict : * ?remove_children_task_segs:bool -> * Task_.task_inst_id -> * sched -> * (sched, unit) result *) val remove_task_inst_uncompleted_seq : ?remove_children_task_segs:bool -> Task_.task_inst_id Seq.t -> sched -> sched val remove_task_inst_completed_seq : ?remove_children_task_segs:bool -> Task_.task_inst_id Seq.t -> sched -> sched val remove_task_inst_discarded_seq : ?remove_children_task_segs:bool -> Task_.task_inst_id Seq.t -> sched -> sched end module Move : sig val move_task_inst_to_completed : Task_.task_inst_id -> sched -> sched val move_task_inst_to_uncompleted : Task_.task_inst_id -> sched -> sched val move_task_inst_to_discarded : Task_.task_inst_id -> sched -> sched end end module Task_seg : sig module Status : sig val get_task_seg_status : Task_.task_seg_id -> sched -> task_related_status option end module Add : sig val add_task_seg : parent_task_inst_id:Task_.task_inst_id -> Task_.task_seg_size -> sched -> Task_.task_seg * sched val add_task_seg_via_task_seg_alloc_req : Task_.task_seg_alloc_req -> sched -> Task_.task_seg * sched val add_task_segs_via_task_seg_alloc_req_list : Task_.task_seg_alloc_req list -> sched -> Task_.task_seg list * sched val add_task_seg_via_task_seg_place : Task_.task_seg_place -> sched -> sched val add_task_segs_via_task_seg_place_list : Task_.task_seg_place list -> sched -> sched val add_task_segs_via_task_seg_place_seq : Task_.task_seg_place Seq.t -> sched -> sched end module To_seq : sig val task_seg_seq_uncompleted : sched -> Task_.task_seg Seq.t val task_seg_seq_completed : sched -> Task_.task_seg Seq.t val task_seg_seq_discarded : sched -> Task_.task_seg Seq.t val task_seg_seq_all : sched -> Task_.task_seg Seq.t end module Find : sig val find_task_seg_uncompleted_opt : Task_.task_seg_id -> sched -> Task_.task_seg_size option val find_task_seg_completed_opt : Task_.task_seg_id -> sched -> Task_.task_seg_size option val find_task_seg_discarded_opt : Task_.task_seg_id -> sched -> Task_.task_seg_size option val find_task_seg_any_opt : Task_.task_seg_id -> sched -> Task_.task_seg_size option val find_task_seg_any_with_status_opt : Task_.task_seg_id -> sched -> (Task_.task_seg_size * task_related_status) option val find_task_seg_ids_by_task_inst_id : Task_.task_inst_id -> sched -> Task_.task_seg_id Seq.t val find_task_seg_seq_uncompleted_by_task_inst_id : Task_.task_inst_id -> sched -> Task_.task_seg Seq.t val find_task_seg_seq_completed_by_task_inst_id : Task_.task_inst_id -> sched -> Task_.task_seg Seq.t val find_task_seg_seq_discarded_by_task_inst_id : Task_.task_inst_id -> sched -> Task_.task_seg Seq.t val find_task_seg_seq_any_by_task_inst_id : Task_.task_inst_id -> sched -> Task_.task_seg Seq.t val find_task_seg_seq_any_with_status_by_task_inst_id : Task_.task_inst_id -> sched -> (Task_.task_seg * task_related_status) Seq.t val find_task_seg_ids_by_task_id : Task_.task_id -> sched -> Task_.task_seg_id Seq.t val find_task_seg_seq_uncompleted_by_task_id : Task_.task_id -> sched -> Task_.task_seg Seq.t val find_task_seg_seq_completed_by_task_id : Task_.task_id -> sched -> Task_.task_seg Seq.t val find_task_seg_seq_discarded_by_task_id : Task_.task_id -> sched -> Task_.task_seg Seq.t val find_task_seg_seq_any_by_task_id : Task_.task_id -> sched -> Task_.task_seg Seq.t val find_task_seg_seq_any_with_status_by_task_id : Task_.task_id -> sched -> (Task_.task_seg * task_related_status) Seq.t end module Remove : sig val remove_task_seg_uncompleted : Task_.task_seg_id -> sched -> sched val remove_task_seg_completed : Task_.task_seg_id -> sched -> sched val remove_task_seg_discarded : Task_.task_seg_id -> sched -> sched val remove_task_seg_all : Task_.task_seg_id -> sched -> sched val remove_task_seg_uncompleted_seq : Task_.task_seg_id Seq.t -> sched -> sched val remove_task_seg_completed_seq : Task_.task_seg_id Seq.t -> sched -> sched val remove_task_seg_discarded_seq : Task_.task_seg_id Seq.t -> sched -> sched end module Move : sig val move_task_seg_to_completed : Task_.task_seg_id -> sched -> sched val move_task_seg_to_uncompleted : Task_.task_seg_id -> sched -> sched val move_task_seg_to_discarded : Task_.task_seg_id -> sched -> sched end end module Progress : sig module Add : sig val add_task_seg_progress_chunk : Task_.task_seg_id -> int64 * int64 -> sched -> sched val add_task_seg_progress_chunk : Task_.task_seg_id -> int64 * int64 -> sched -> sched val add_task_inst_progress_chunk : Task_.task_inst_id -> int64 * int64 -> sched -> sched end module Find : sig val find_task_seg_progress : Task_.task_seg_id -> sched -> Task_.progress option val find_task_seg_progress_chunk_set : Task_.task_seg_id -> sched -> Int64_int64_set.t val find_task_seg_progress_chunk_seq : Task_.task_seg_id -> sched -> (int64 * int64) Seq.t val find_task_seg_progress : Task_.task_seg_id -> sched -> Task_.progress option val find_task_seg_progress_seq_by_task_inst_id : Task_.task_inst_id -> sched -> Task_.progress Seq.t val find_task_seg_progress_seq_by_task_id : Task_.task_id -> sched -> Task_.progress Seq.t val find_task_seg_progress_chunk_set : Task_.task_seg_id -> sched -> Int64_int64_set.t val find_task_seg_progress_chunk_seq : Task_.task_seg_id -> sched -> (int64 * int64) Seq.t val find_task_seg_progress_chunk_seq_by_task_inst_id : Task_.task_inst_id -> sched -> (int64 * int64) Seq.t val find_task_seg_progress_chunk_seq_by_task_id : Task_.task_id -> sched -> (int64 * int64) Seq.t val find_task_inst_progress : Task_.task_inst_id -> sched -> Task_.progress option val find_task_inst_progress_seq_by_task_id : Task_.task_id -> sched -> Task_.progress Seq.t val find_task_inst_progress_chunk_set : Task_.task_inst_id -> sched -> Int64_int64_set.t val find_task_inst_progress_chunk_seq : Task_.task_inst_id -> sched -> (int64 * int64) Seq.t val find_task_inst_progress_chunk_seq_by_task_id : Task_.task_id -> sched -> (int64 * int64) Seq.t end module Remove : sig val remove_task_seg_progress_chunk : Task_.task_seg_id -> int64 * int64 -> sched -> sched val remove_task_seg_progress_chunk : Task_.task_seg_id -> int64 * int64 -> sched -> sched val remove_task_inst_progress_chunk : Task_.task_inst_id -> int64 * int64 -> sched -> sched end end module Agenda : sig module Add : sig val add_task_seg_place : Task_.task_seg_place -> sched -> sched val add_task_seg_place_list : Task_.task_seg_place list -> sched -> sched val add_task_seg_place_seq : Task_.task_seg_place Seq.t -> sched -> sched end module Range : sig val task_seg_id_set : start:int64 option -> end_exc:int64 option -> include_task_seg_place_starting_within_time_slot:bool -> include_task_seg_place_ending_within_time_slot:bool -> sched -> Task_seg_id_set.t val task_seg_place_set : start:int64 option -> end_exc:int64 option -> include_task_seg_place_starting_within_time_slot:bool -> include_task_seg_place_ending_within_time_slot:bool -> sched -> Task_seg_place_set.t end module Filter : sig val filter_task_seg_place_seq : ?start:int64 -> ?end_exc:int64 -> ?include_task_seg_place_starting_within_time_slot:bool -> ?include_task_seg_place_ending_within_time_slot:bool -> (Task_.task_seg_place -> bool) -> sched -> Task_.task_seg_place Seq.t end module To_seq : sig val task_seg_place_uncompleted : ?start:int64 -> ?end_exc:int64 -> ?include_task_seg_place_starting_within_time_slot:bool -> ?include_task_seg_place_ending_within_time_slot:bool -> sched -> Task_.task_seg_place Seq.t val task_seg_place_completed : ?start:int64 -> ?end_exc:int64 -> ?include_task_seg_place_starting_within_time_slot:bool -> ?include_task_seg_place_ending_within_time_slot:bool -> sched -> Task_.task_seg_place Seq.t val task_seg_place_discarded : ?start:int64 -> ?end_exc:int64 -> ?include_task_seg_place_starting_within_time_slot:bool -> ?include_task_seg_place_ending_within_time_slot:bool -> sched -> Task_.task_seg_place Seq.t val task_seg_place_all : ?start:int64 -> ?end_exc:int64 -> ?include_task_seg_place_starting_within_time_slot:bool -> ?include_task_seg_place_ending_within_time_slot:bool -> sched -> Task_.task_seg_place Seq.t end module Find : sig val find_task_seg_place_seq_by_task_id : Task_.task_id -> sched -> Task_.task_seg_place Seq.t val find_task_seg_place_seq_by_task_inst_id : Task_.task_inst_id -> sched -> Task_.task_seg_place Seq.t val find_task_seg_place_opt_by_task_seg_id : Task_.task_seg_id -> sched -> Task_.task_seg_place option end module Remove : sig val remove_task_seg_place : Task_.task_seg_place -> sched -> sched val remove_task_seg_place_seq : Task_.task_seg_place Seq.t -> sched -> sched val remove_task_seg_place_by_task_id : Task_.task_id -> sched -> sched val remove_task_seg_place_by_task_inst_id : Task_.task_inst_id -> sched -> sched val remove_task_seg_place_by_task_seg_id : Task_.task_seg_id -> sched -> sched end module Time_slot : sig val get_occupied_time_slots : ?exclude_parallelizable_task_seg_places:bool -> ?start:int64 -> ?end_exc:int64 -> sched -> (int64 * int64) Seq.t val get_occupied_time_slots_with_task_seg_place_count : ?exclude_parallelizable_task_seg_places:bool -> ?start:int64 -> ?end_exc:int64 -> sched -> ((int64 * int64) * int) Seq.t val get_occupied_time_slots_up_to_task_seg_place_count : ?exclude_parallelizable_task_seg_places:bool -> ?start:int64 -> ?end_exc:int64 -> up_to_task_seg_place_count_inc:int -> sched -> (int64 * int64) Seq.t val get_free_time_slots : ?include_parallelizable_task_seg_places:bool -> start:int64 -> end_exc:int64 -> sched -> (int64 * int64) Seq.t val get_free_or_occupied_time_slots_up_to_task_seg_place_count : ?include_parallelizable_task_seg_places:bool -> start:int64 -> end_exc:int64 -> up_to_task_seg_place_count_inc:int -> sched -> (int64 * int64) Seq.t val task_seg_place_count_in_time_slot : start:int64 -> end_exc:int64 -> sched -> int end end module Sched_req : sig module Status : sig val get_sched_req_status : Sched_req_.sched_req_id -> sched -> sched_req_status option end module Add : sig val add_sched_req_data : Sched_req_.sched_req_data -> sched -> (Sched_req_.sched_req * sched, unit) result val add_sched_req_data_list : Sched_req_.sched_req_data list -> sched -> (Sched_req_.sched_req list * sched, unit) result end module Partition : sig type 'a partition_based_on_time_point = { before : 'a Sched_req_id_map.t; after : 'a Sched_req_id_map.t; crossing : 'a Sched_req_id_map.t; } type 'a partition_based_on_time_slot = { fully_within : 'a Sched_req_id_map.t; starting_within : 'a Sched_req_id_map.t; ending_within : 'a Sched_req_id_map.t; outside : 'a Sched_req_id_map.t; } module Pending : sig val partition_based_on_time_point : int64 -> sched -> Sched_req_.sched_req_data partition_based_on_time_point val partition_based_on_time_slot : start:int64 -> end_exc:int64 -> sched -> Sched_req_.sched_req_data partition_based_on_time_slot end module Record : sig val partition_based_on_time_point : int64 -> sched -> Sched_req_.sched_req_record_data partition_based_on_time_point val partition_based_on_time_slot : start:int64 -> end_exc:int64 -> sched -> Sched_req_.sched_req_record_data partition_based_on_time_slot end end module To_seq : sig module Pending : sig val pending_sched_req_seq : ?start:int64 -> ?end_exc:int64 -> ?include_sched_req_starting_within_time_slot:bool -> ?include_sched_req_ending_within_time_slot:bool -> sched -> Sched_req_.sched_req Seq.t end module Record : sig val sched_req_record_seq : ?start:int64 -> ?end_exc:int64 -> ?include_sched_req_record_starting_within_time_slot:bool -> ?include_sched_req_record_ending_within_time_slot:bool -> sched -> Sched_req_.sched_req_record Seq.t end end module Filter : sig module Pending : sig val filter_pending_sched_req_seq : ?start:int64 -> ?end_exc:int64 -> ?include_sched_req_starting_within_time_slot:bool -> ?include_sched_req_ending_within_time_slot:bool -> (Sched_req_.sched_req -> bool) -> sched -> Sched_req_.sched_req Seq.t end module Record : sig val filter_sched_req_record_seq : ?start:int64 -> ?end_exc:int64 -> ?include_sched_req_record_starting_within_time_slot:bool -> ?include_sched_req_record_ending_within_time_slot:bool -> (Sched_req_.sched_req_record -> bool) -> sched -> Sched_req_.sched_req_record Seq.t end end module Find : sig module Pending : sig val find_pending_sched_req : Sched_req_.sched_req_id -> sched -> Sched_req_.sched_req_data option val find_pending_sched_req_by_task_id : Task_.task_id -> sched -> Sched_req_.sched_req Seq.t val find_pending_sched_req_by_task_inst_id : Task_.task_inst_id -> sched -> Sched_req_.sched_req Seq.t end module Record : sig val find_sched_req_record : Sched_req_.sched_req_id -> sched -> Sched_req_.sched_req_record_data option val find_sched_req_record_by_task_id : Task_.task_id -> sched -> Sched_req_.sched_req_record Seq.t val find_sched_req_record_by_task_inst_id : Task_.task_inst_id -> sched -> Sched_req_.sched_req_record Seq.t val find_sched_req_record_by_task_seg_id : Task_.task_seg_id -> sched -> Sched_req_.sched_req_record Seq.t end end module Remove : sig module Pending : sig val remove_pending_sched_req : Sched_req_.sched_req_id -> sched -> sched val remove_pending_sched_req_if_contains_matching_task_seg_alloc_req : (Task_.task_seg_alloc_req -> bool) -> sched -> sched val remove_pending_sched_req_data_unit_if_contains_matching_task_seg_alloc_req : (Task_.task_seg_alloc_req -> bool) -> sched -> sched val remove_pending_sched_req_by_task_id : Task_.task_id -> sched -> sched val remove_pending_sched_req_by_task_inst_id : Task_.task_inst_id -> sched -> sched val remove_pending_sched_req_by_task_seg_id : Task_.task_seg_id -> sched -> sched val remove_pending_sched_req_data_unit_by_task_id : Task_.task_id -> sched -> sched val remove_pending_sched_req_data_unit_by_task_inst_id : Task_.task_inst_id -> sched -> sched val remove_pending_sched_req_data_unit_by_task_seg_id : Task_.task_seg_id -> sched -> sched end module Record : sig val remove_sched_req_record : Sched_req_.sched_req_id -> sched -> sched val remove_sched_req_record_if_contains_matching_task_seg : (Task_.task_seg -> bool) -> sched -> sched val remove_sched_req_record_data_unit_if_contains_matching_task_seg : (Task_.task_seg -> bool) -> sched -> sched val remove_sched_req_record_by_task_id : Task_.task_id -> sched -> sched val remove_sched_req_record_by_task_inst_id : Task_.task_inst_id -> sched -> sched val remove_sched_req_record_by_task_seg_id : Task_.task_seg_id -> sched -> sched val remove_sched_req_record_data_unit_by_task_id : Task_.task_id -> sched -> sched val remove_sched_req_record_data_unit_by_task_inst_id : Task_.task_inst_id -> sched -> sched val remove_sched_req_record_data_unit_by_task_seg_id : Task_.task_seg_id -> sched -> sched end end module Discard : sig val discard_pending_sched_req : Sched_req_.sched_req_id -> sched -> sched end module Allocate_task_segs : sig val allocate_task_segs_for_pending_sched_reqs : start:int64 -> end_exc:int64 -> include_sched_reqs_starting_within_time_slot:bool -> include_sched_reqs_ending_within_time_slot:bool -> up_to_sched_req_id_inc:Sched_req_.sched_req_id option -> sched -> Sched_req_.sched_req_record list * sched end end module Recur : sig val instantiate : start:int64 -> end_exc:int64 -> sched -> sched end module Overdue : sig val get_overdue_task_seg_places : deadline:int64 -> sched -> Task_.task_seg_place Seq.t val get_overdue_task_segs : deadline:int64 -> sched -> Task_.task_seg Seq.t val add_sched_reqs_for_overdue_task_segs : start:int64 -> end_exc:int64 -> sched -> sched end module Serialize : sig val pack_task_uncompleted_store : task_store -> Sched_t.task list val pack_task_completed_store : task_store -> Sched_t.task list val pack_task_discarded_store : task_store -> Sched_t.task list val pack_task_inst_uncompleted_store : task_inst_store -> Sched_t.task_inst list val pack_task_inst_completed_store : task_inst_store -> Sched_t.task_inst list val pack_task_inst_discarded_store : task_inst_store -> Sched_t.task_inst list val pack_task_seg_uncompleted_store : task_seg_store -> Sched_t.task_seg list val pack_task_seg_completed_store : task_seg_store -> Sched_t.task_seg list val pack_task_seg_discarded_store : task_seg_store -> Sched_t.task_seg list val pack_sched_req_pending_store : sched_req_store -> Sched_req_t.sched_req list val pack_sched_req_record_store : sched_req_record_store -> Sched_req_t.sched_req_record list val pack_quota : int64 Task_inst_id_map.t -> (Task_t.task_inst_id * (int32 * int32)) list val pack_user_id_to_task_ids : Int64_set.t User_id_map.t -> (Task_t.user_id * (int32 * int32) list) list val pack_task_id_to_task_inst_ids : Int64_set.t Task_id_map.t -> (Task_t.task_id * (int32 * int32) list) list val pack_task_inst_id_to_task_seg_ids : Int64_int64_option_set.t Task_inst_id_map.t -> (Task_t.task_inst_id * ((int32 * int32) * (int32 * int32) option) list) list val pack_task_seg_id_to_progress : Task_.progress Task_seg_id_map.t -> (Task_t.task_seg_id * Task_t.progress) list val pack_task_inst_id_to_progress : Task_.progress Task_inst_id_map.t -> (Task_t.task_inst_id * Task_t.progress) list val pack_indexed_by_task_seg_id : (int64 * int64) Task_seg_id_map.t -> (Task_t.task_seg_id * ((int32 * int32) * (int32 * int32))) list val pack_indexed_by_start : task_seg_place_map -> ((int32 * int32) * Task_t.task_seg_id list) list val pack_indexed_by_end_exc : task_seg_place_map -> ((int32 * int32) * Task_t.task_seg_id list) list val pack_sched_req_ids : Int64_set.t -> (int32 * int32) list val pack_sched : sched -> Sched_t.sched val pack_sched_diff : sched_diff -> Sched_t.sched_diff val json_string_of_sched : sched -> string val json_string_of_sched_diff : sched_diff -> string end module Deserialize : sig val unpack_task_uncompleted_list : Sched_t.task list -> task_store val unpack_task_completed_list : Sched_t.task list -> task_store val unpack_task_discarded_list : Sched_t.task list -> task_store val unpack_task_inst_uncompleted_list : Sched_t.task_inst list -> task_inst_store val unpack_task_inst_completed_list : Sched_t.task_inst list -> task_inst_store val unpack_task_inst_discarded_list : Sched_t.task_inst list -> task_inst_store val unpack_task_seg_uncompleted_list : Sched_t.task_seg list -> task_seg_store val unpack_task_seg_completed_list : Sched_t.task_seg list -> task_seg_store val unpack_task_seg_discarded_list : Sched_t.task_seg list -> task_seg_store val unpack_sched_req_pending_list : Sched_req_t.sched_req list -> sched_req_store val unpack_sched_req_record_list : Sched_req_t.sched_req_record list -> sched_req_record_store val unpack_quota : (Task_t.task_inst_id * (int32 * int32)) list -> int64 Task_inst_id_map.t val unpack_user_id_to_task_ids : (Task_t.user_id * (int32 * int32) list) list -> Int64_set.t User_id_map.t val unpack_task_id_to_task_inst_ids : (Task_t.task_id * (int32 * int32) list) list -> Int64_set.t Task_id_map.t val unpack_task_inst_id_to_task_seg_ids : (Task_t.task_inst_id * ((int32 * int32) * (int32 * int32) option) list) list -> Int64_int64_option_set.t Task_inst_id_map.t val unpack_task_seg_id_to_progress : (Task_t.task_seg_id * Task_t.progress) list -> Task_.progress Task_seg_id_map.t val unpack_task_inst_id_to_progress : (Task_t.task_inst_id * Task_t.progress) list -> Task_.progress Task_inst_id_map.t val unpack_indexed_by_task_seg_id : (Task_t.task_seg_id * ((int32 * int32) * (int32 * int32))) list -> (int64 * int64) Task_seg_id_map.t val unpack_indexed_by_end_exc : ((int32 * int32) * Task_t.task_seg_id list) list -> task_seg_place_map val unpack_indexed_by_start : ((int32 * int32) * Task_t.task_seg_id list) list -> task_seg_place_map val unpack_sched_req_ids : (int32 * int32) list -> Int64_set.t val unpack_sched : Sched_t.sched -> sched val unpack_sched_diff : Sched_t.sched_diff -> sched_diff val sched_of_json_string : string -> sched val sched_diff_of_json_string : string -> sched_diff end module Equal : sig val sched_data_equal : sched_data -> sched_data -> bool val sched_equal : sched -> sched -> bool end module Diff : sig val diff_sched_data : old:sched_data -> sched_data -> sched_data_diff val diff_sched : old:sched -> sched -> sched_diff val add_diff_sched_data : sched_data_diff -> sched_data -> sched_data val add_diff_sched : sched_diff -> sched -> sched val sub_diff_sched_data : sched_data_diff -> sched_data -> sched_data val sub_diff_sched : sched_diff -> sched -> sched end module To_string : sig val string_of_task_related_status : task_related_status -> string val debug_string_of_sched : ?indent_level:int -> ?buffer:Buffer.t -> sched -> string end module Print : sig val debug_print_sched : ?indent_level:int -> sched -> unit end
tty_ioctl.c
#define EXTUNIX_WANT_TTY_IOCTL #include "config.h" #if defined(EXTUNIX_HAVE_TTY_IOCTL) /* FIXME implement separate interface for tcsetattr/tcgetattr */ CAMLprim value caml_extunix_crtscts(value mlfd) { CAMLparam1(mlfd); struct termios t; int r, fd = Int_val(mlfd); r = tcgetattr(fd, &t); if (0 == r) { t.c_cflag |= CRTSCTS; r = tcsetattr(fd, TCSANOW, &t); } if (0 != r) uerror("crtscts",Nothing); CAMLreturn(Val_unit); } #define TTY_IOCTL_INT(cmd) \ CAMLprim value caml_extunix_ioctl_##cmd(value v_fd, value v_arg) \ { \ CAMLparam2(v_fd, v_arg); \ int arg = Int_val(v_arg); \ int r = ioctl(Int_val(v_fd), cmd, &arg); \ if (r < 0) uerror("ioctl",caml_copy_string(#cmd)); \ CAMLreturn(Val_unit); \ } CAMLprim value caml_extunix_ioctl_TIOCMGET(value v_fd) { CAMLparam1(v_fd); int arg = 0; int r = ioctl(Int_val(v_fd), TIOCMGET, &arg); if (r < 0) uerror("ioctl",caml_copy_string("TIOCMGET")); CAMLreturn(Val_int(arg)); } TTY_IOCTL_INT(TIOCMSET) TTY_IOCTL_INT(TIOCMBIC) TTY_IOCTL_INT(TIOCMBIS) #endif
/* * Copyright : (c) 2010, Stéphane Glondu <steph@glondu.net> */
main_fzf.ml
open Core open Async let main ~filename = Sys.command ("cat " ^ Sys.quote filename ^ {| | fzf --multi --no-sort --reverse --exact --ansi --preview-window=down:70% \ --preview "printf '%s' {} | sexp pp -color" |} ) >>= exit ;; let command = let open Command.Let_syntax in Command.async_or_error ~summary:"select one or more inputs sexps with [fzf --multi]" [%map_open let filename = anon (maybe_with_default "-" ("FILENAME" %: Filename_unix.arg_type)) in fun () -> main ~filename] ;;
fprint.c
#include "mag.h" #include "arf.h" void mag_fprint(FILE * file, const mag_t x) { flint_fprintf(file, "("); if (mag_is_zero(x)) flint_fprintf(file, "0"); else if (mag_is_inf(x)) flint_fprintf(file, "inf"); else { fmpz_t t; fmpz_init(t); fmpz_sub_ui(t, MAG_EXPREF(x), MAG_BITS); flint_fprintf(file, "%wu * 2^", MAG_MAN(x)); fmpz_fprint(file, t); fmpz_clear(t); } flint_fprintf(file, ")"); } void mag_fprintd(FILE * file, const mag_t x, slong d) { arf_t t; arf_init(t); arf_set_mag(t, x); arf_fprintd(file, t, d); arf_clear(t); }
/* Copyright (C) 2014 Fredrik Johansson Copyright (C) 2015 Arb authors This file is part of Arb. Arb is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <http://www.gnu.org/licenses/>. */
dune
(test (name test_btc) (modules Test_btc) (package ledgerwallet-btc) (libraries alcotest ledgerwallet-btc)) (test (name test_tezos) (modules Test_tezos) (package ledgerwallet-tezos) (libraries alcotest ledgerwallet-tezos secp256k1 uecc)) (test (name test_zil) (modules Test_zil) (package ledgerwallet-zil) (libraries hex alcotest ledgerwallet-zil)) (test (name test_ssh_agent) (modules Test_ssh_agent) (package ledgerwallet-ssh-agent) (libraries hex alcotest ledgerwallet-ssh-agent))
dbus.without.ml
(** Dummy module that is used if D-BUS support isn't available. *) open Support open Common let session ?switch:_ () = return (`Error "0install was compiled without D-BUS support") let system ?switch:_ () = return (`Error "0install was compiled without D-BUS support") let no_dbus _ = Safe_exn.failf "No D-BUS!" (* Always call [session] first. If you get None, don't use Notification. *) module Notification = struct let get_server_information = no_dbus let notify ?app_name:_ ?id:_ ?icon:_ ?summary:_ ?body:_ ?actions:_ ?hints:_ ?timeout:_ = no_dbus end (* Always call [system] first. If you get None, don't use Nm_manager. *) module Nm_manager = struct let daemon = no_dbus type state = [ `Unknown | `Asleep | `Connecting | `Connected | `Disconnected ] let state _daemon : state Lwt.t = no_dbus () end module OBus_property = struct let get = no_dbus let monitor ?switch:_ = no_dbus let make ?monitor:_ _desc = no_dbus end module OBus_bus = struct exception Service_unknown of string let system ?switch:_ = no_dbus let request_name _bus = no_dbus end module OBus_object = struct let make_interface_unsafe _name _annotations _methods _signals = no_dbus let method_info _info = no_dbus let property_r_info _info _ : unit = no_dbus () let signal_info = no_dbus let make ~interfaces:_ = no_dbus let attach _obj = no_dbus let export _connection = no_dbus let remove _connection = no_dbus end module OBus_error = struct exception Unknown_object of string end module OBus_peer = struct type t = { connection : unit; name : unit; } let make ~connection:_ ~name:_ = no_dbus () end module OBus_path = struct type t = string let of_string = no_dbus end module OBus_proxy = struct type t = { peer : OBus_peer.t; path : OBus_path.t; } let make ~peer:_ ~path:_ = no_dbus () end module OBus_value = struct module C = struct exception Signature_mismatch let array _ = () let dict _ _ = () let string = () let variant = () let cast_single _ = failwith "cast_single" let basic_boolean = () let basic_uint32 = () let basic_uint64 = () let basic_string = () let basic_object_path = () type 'a sequence = 'a list end module V = struct let string_of_single _ = "" end type 'a arguments = unit let arg0 = () let arg1 _ = () let arg2 _ _ = () let arg3 _ _ _ = () let arg6 _ _ _ _ _ _ = () end module OBus_member = struct module Method = struct type ('a, 'b) t = { interface : string; member : string; i_args : 'a OBus_value.arguments; o_args : 'b OBus_value.arguments; annotations : (string * string) list; } end module Property = struct type ('a, 'access) t = { interface : string; member : string; typ : unit; access : unit; annotations : (string * string) list; } let readable = () end module Signal = struct type 'a t = { interface : string; member : string; args : unit; annotations : (string * string) list; } end end module OBus_method = struct let call _info _proxy = no_dbus end module OBus_signal = struct let connect ?switch:_ = no_dbus let make _signal = no_dbus let emit _info _obj ?peer:_ = no_dbus end let have_dbus = false
(* Copyright (C) 2013, Thomas Leonard * See the README file for details, or visit http://0install.net. *)
stdlib_ext.ml
type 'a pp = Format.formatter -> 'a -> unit let ( >> ) f g x = g (f x) let tap f x = f x; x let trace fmt x = Fmt.epr fmt x; x module type Eq = sig type t val equal : t -> t -> bool end module type Comparable_infix = sig type t val ( = ) : t -> t -> bool val ( <= ) : t -> t -> bool val ( >= ) : t -> t -> bool val ( < ) : t -> t -> bool val ( > ) : t -> t -> bool end module Poly = struct let ( = ) = Stdlib.( = ) let ( <= ) = Stdlib.( <= ) let ( >= ) = Stdlib.( >= ) let ( < ) = Stdlib.( < ) let ( > ) = Stdlib.( > ) end include Stdlib.StdLabels include Stdlib.MoreLabels (** Shadow polymorphic operators in the Stdlib. *) include struct let min : int -> int -> int = min let max : int -> int -> int = max let compare : int -> int -> int = compare include (Poly : Comparable_infix with type t := int) end module Int = struct include Int include (Poly : Comparable_infix with type t := t) let float_div a b = to_float a /. to_float b end module Int32 = struct include Int32 include (Poly : Comparable_infix with type t := t) let float_div a b = to_float a /. to_float b end module Int63 = struct include Optint.Int63 include (Poly : Comparable_infix with type t := t) let float_div a b = to_float a /. to_float b end type int63 = Int63.t module Int64 = struct include Int64 include (Poly : Comparable_infix with type t := t) let float_div a b = to_float a /. to_float b end module Float = struct include Float include (Poly : Comparable_infix with type t := t) let float_div = ( /. ) let to_float x = x let of_float x = x end module Option = struct include Option let ( || ) a b = match a with Some _ -> a | None -> b end module Result = struct let get_or_invalid_arg = function | Ok x -> x | Error (`Msg s) -> invalid_arg s let errorf fmt = Format.kasprintf (fun s -> Error (`Msg s)) fmt end module List = struct include List let rec intersperse ~sep = function | ([] | [ _ ]) as l -> l | h1 :: (_ :: _ as tl) -> h1 :: sep :: intersperse ~sep tl end module Staged : sig type 'a t type ('a, 'b) endo := 'a t -> 'b t external map : f:('a -> 'b) -> ('a, 'b) endo = "%identity" external inj : 'a -> 'a t = "%identity" external prj : 'a t -> 'a = "%identity" module Syntax : sig val ( let$ ) : 'a t -> ('a -> 'b) -> 'b t val ( and$ ) : 'a t -> 'b t -> ('a * 'b) t end end = struct type 'a t = 'a type ('a, 'b) endo = 'a t -> 'b t external map : f:('a -> 'b) -> ('a, 'b) endo = "%identity" external inj : 'a -> 'a t = "%identity" external prj : 'a t -> 'a = "%identity" module Syntax = struct let ( let$ ) x f = f x let ( and$ ) a b = (a, b) end end module Unique_id () : sig type t val create : unit -> t val equal : t -> t -> bool val pp : t pp end = struct let allocated = ref 0 type t = int let create () = let v = !allocated in incr allocated; v let equal = Int.equal let pp = Fmt.int end module Sta_dyn : sig type 'a t = Static of 'a | Dynamic of (unit -> 'a) val get : 'a t -> 'a val lift : ('a -> 'a -> 'a) -> 'a t -> 'a t -> 'a t val pp : 'a pp -> 'a t pp end = struct type 'a t = Static of 'a | Dynamic of (unit -> 'a) let get = function Static x -> x | Dynamic f -> f () let lift add x y = let ( ++ ) = add in match (x, y) with | Static x, Static y -> Static (x ++ y) | Dynamic f, Static x | Static x, Dynamic f -> Dynamic (fun () -> x ++ f ()) | Dynamic f, Dynamic g -> Dynamic (fun () -> f () ++ g ()) let pp pp_elt ppf = function | Static x -> Fmt.pf ppf "Static %a" pp_elt x | Dynamic f -> Fmt.pf ppf "Dynamic %a" pp_elt (f ()) end (*———————————————————————————————————————————————————————————————————————————— Copyright (c) 2020–2021 Craig Ferguson <me@craigfe.io> 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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ————————————————————————————————————————————————————————————————————————————*)
(*———————————————————————————————————————————————————————————————————————————— Copyright (c) 2020–2021 Craig Ferguson <me@craigfe.io> Distributed under the MIT license. See terms at the end of this file. ————————————————————————————————————————————————————————————————————————————*)
dune
(library (name bistring_unix_test) (libraries bigbuffer_blocking bigstring_unix core_thread filename_unix quickcheck_deprecated) (preprocess (pps ppx_jane)))
dune
(executables (names main) (libraries bonsai_web bonsai_time_example) (preprocess (pps ppx_jane)))
layout.ml
let toplevel name ~root = Filename.(concat root name) module V1_and_v2 = struct let pack = toplevel "store.pack" let branch = toplevel "store.branches" let dict = toplevel "store.dict" let all ~root = [ pack ~root; branch ~root; dict ~root ] end module V3 = struct let branch = toplevel "store.branches" let dict = toplevel "store.dict" let control = toplevel "store.control" let suffix ~generation = toplevel ("store." ^ string_of_int generation ^ ".suffix") (* TODO layered: Add prefix and mapping *) let all ~generation ~root = [ suffix ~generation ~root; branch ~root; dict ~root; control ~root ] end
(* * Copyright (c) 2018-2021 Tarides <contact@tarides.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
context.mli
(** A context holds heterogeneous value and is passed to the requests or responses. *) (** {2:keys Keys} *) (** The type for keys whose lookup value is of type ['a]. *) type 'a key = 'a Rock.Context.key (** {3 [Key]} *) module Key : sig (** {2:keys Keys} *) (** The type for key information. *) type 'a info = 'a Rock.Context.Key.info (** {3 [create]} *) (** [create i] is a new key with information [i]. *) val create : 'a info -> 'a key (** {3 [info]} *) (** [info k] is [k]'s information. *) val info : 'a key -> 'a info (** {2:exists Existential keys} Exisential keys allow to compare keys. This can be useful for functions like {!filter}. *) (** The type for existential keys. *) type t = Rock.Context.Key.t (** {3 [hide_type]} *) (** [hide_type k] is an existential key for [k]. *) val hide_type : 'a key -> t (** {3 [equal]} *) (** [equal k k'] is [true] iff [k] and [k'] are the same key. *) val equal : t -> t -> bool (** {3 [compare]} *) (** [compare k k'] is a total order on keys compatible with {!equal}. *) val compare : t -> t -> int end (** {2:maps Maps} *) (** The type for heterogeneous value maps. *) type t = Rock.Context.t (** {3 [empty]} *) (** [empty] is the empty map. *) val empty : t (** {3 [is_empty]} *) (** [is_empty m] is [true] iff [m] is empty. *) val is_empty : t -> bool (** {3 [mem]} *) (** [mem k m] is [true] iff [k] is bound in [m]. *) val mem : 'a key -> t -> bool (** {3 [add]} *) (** [add k v m] is [m] with [k] bound to [v]. *) val add : 'a key -> 'a -> t -> t (** {3 [singleton]} *) (** [singleton k v] is [add k v empty]. *) val singleton : 'a key -> 'a -> t (** {3 [rem]} *) (** [rem k m] is [m] with [k] unbound. *) val rem : 'a key -> t -> t (** {3 [find]} *) (** [find k m] is the value of [k]'s binding in [m], if any. *) val find : 'a key -> t -> 'a option (** {3 [find_exn]} *) (** [find_exn k m] is the value of [k]'s binding find_exn [m]. @raise Invalid_argument if [k] is not bound in [m]. *) val find_exn : 'a key -> t -> 'a (** {2:utilities Utilities} *) (** {3 [sexp_of_t]} *) (** [sexp_of_t t] converts the request [t] to an s-expression *) val sexp_of_t : t -> Sexplib0.Sexp.t (** {3 [pp_hum]} *) (** [pp_hum] formats the request [t] as a standard HTTP request *) val pp_hum : Format.formatter -> t -> unit [@@ocaml.toplevel_printer]
(** A context holds heterogeneous value and is passed to the requests or responses. *)
test.ml
let null = Unix.openfile "/dev/null" Unix.[ O_CLOEXEC ] 0o644 let () = at_exit (fun () -> try Unix.close null with _exn -> ()) let create_lock filename = let fd = Unix.openfile filename Unix.[ O_CREAT; O_RDWR ] 0o644 in ignore (Unix.lseek fd 0 Unix.SEEK_SET) ; fd let lock fd = Unix.lockf fd Unix.F_LOCK 0 let unlock fd = Unix.lockf fd Unix.F_ULOCK 0 (* XXX(dinosaure): this test wants to check with **true** parallelism * that our server and our client works together (at least). The true * parallelism is done by the clone()/fork() syscall - by this way, * we are not constrained by the global GC lock. * * locks ([lock.8080]/[lock.4343]) permit to launch safely clients * when, at least, servers are initialised. Then, we launch clients * [N] times on some specific endpoints: * - [/] * - [/large] * with TLS and without TLS. We see then (with a monotonic clock) * the time spent by such request and generate an histogram. If * one request fails, the test fails. Otherwise, we have a performance * report about our implementation. * * The test does not want to provide metrics about performance. It * gives this information but it's not real /benchmark/! *) let launch_server () = let lock0 = create_lock "lock.4343" in let lock1 = create_lock "lock.8080" in let pid0 = Unix.create_process_env "./simple_server.exe" [| "./simple_server.exe"; "--with-tls"; "server.pem"; "server.key"; "file.txt"; |] [||] null Unix.stdout null in let pid1 = Unix.create_process_env "./simple_server.exe" [| "./simple_server.exe"; "file.txt" |] [||] null Unix.stdout null in at_exit (fun () -> try Unix.close lock0 ; Unix.unlink "lock.4343" with _exn -> ()) ; at_exit (fun () -> try Unix.close lock1 ; Unix.unlink "lock.8080" with _exn -> ()) ; lock lock0 ; lock lock1 ; (lock0, lock1, pid0, pid1) let launch_clients c n uri = Format.printf "===== -c %d -n %d %a =====\n%!" c n Uri.pp uri ; let pid = Unix.create_process_env "./clients.exe" [| "./clients.exe"; "-c"; string_of_int c; "-n"; string_of_int n; Uri.to_string uri; |] [||] Unix.stdin Unix.stdout Unix.stderr in let _, _ = Unix.waitpid [] pid in Format.printf "\n%!" let concurrency = ref 50 let number = ref 200 let anonymous_argument _ = () let spec = [ ( "-c", Arg.Set_int concurrency, "Number of workers to run concurrently. Total number of requests cannot \ be smaller than the concurrency level. Default is 50." ); ("-n", Arg.Set_int number, "Number of requests to run. Default is 200."); ] let usage = Format.asprintf "%s [-c <number>] [-n <number>]" Sys.argv.(0) let () = Arg.parse spec anonymous_argument usage ; let lock0, lock1, pid0, pid1 = launch_server () in lock lock0 ; lock lock1 ; Unix.sleep 2 ; (* XXX(dinosaure): needed because [Paf.init/Stack.listen] does not ensure that * we listen **after**. Lwt can schedule it in an other way... see mirage/mirage-tcpip#438 *) launch_clients !concurrency !number (Uri.of_string "https://localhost:4343/") ; launch_clients !concurrency !number (Uri.of_string "https://localhost:4343/large") ; launch_clients !concurrency !number (Uri.of_string "http://localhost:8080/") ; launch_clients !concurrency !number (Uri.of_string "http://localhost:8080/large") ; Unix.kill pid0 Sys.sigint ; Unix.kill pid1 Sys.sigint ; unlock lock0 ; unlock lock1
portaudio_types.ml
include Stubs.Make(Stub_types)
missed_shadowing.ml
module W = struct end module M (W : sig end) : sig end = struct include W end module type X = sig end module N (X : X) : sig end = struct include X end
dune
(executables (names hypertree) (libraries js_of_ocaml-lwt) (modes byte) (preprocess (pps js_of_ocaml-ppx))) (rule (targets hypertree.js) (action (run %{bin:js_of_ocaml} --source-map %{dep:hypertree.bc} -o %{targets} --pretty --file %{dep:image_info.json} --file %{dep:messages.json} --file %{dep:tree.json}))) (alias (name default) (deps hypertree.js index.html (glob_files icons/*.{png,jpg}) (glob_files thumbnails/*.{png,jpg})))
dune
(rule (alias runtest) (enabled_if (>= %{ocaml_version} "4.09.0")) (deps (:test test.ml) (package ppxlib)) (action (chdir %{project_root} (progn (run expect-test %{test}) (diff? %{test} %{test}.corrected)))))
fmts.ml
(* Formatters *) open Tsdl let button_state_str = function | s when s = Sdl.pressed -> "pressed" | s when s = Sdl.released -> "released" | _ -> assert false let pp = Format.fprintf let pp = Format.fprintf let pp_int = Format.pp_print_int let pp_str = Format.pp_print_string let pp_ipair ppf (x, y) = pp ppf "(%d %d)" x y let pp_opt pp_v ppf v = match v with | None -> pp ppf "None" | Some v -> pp ppf "(Some %a)" pp_v v let rec pp_list ?(pp_sep = Format.pp_print_cut) pp_v ppf = function | [] -> () | v :: vs -> pp_v ppf v; if vs <> [] then (pp_sep ppf (); pp_list ~pp_sep pp_v ppf vs) let pp_unknown pp_v ppf v = match v with | None -> pp ppf "unknown" | Some v -> pp_v ppf v let pp_point ppf p = pp ppf "@[<1>(%d %d)>@]" (Sdl.Point.x p) (Sdl.Point.y p) let pp_rect ppf r = pp ppf "@[<1><rect (%d %d) (%d %d)>@]" (Sdl.Rect.x r) (Sdl.Rect.y r) (Sdl.Rect.w r) (Sdl.Rect.h r) let pp_color ppf c = pp ppf "@[<1><color %d %d %d %d>@]" (Sdl.Color.r c) (Sdl.Color.g c) (Sdl.Color.b c) (Sdl.Color.a c) let pp_render_info ppf i = pp ppf "@[<v>@[%s@]@,%a@,@[max tex size %dx%d@]@]" i.Sdl.ri_name (pp_list Format.pp_print_string) (List.map Sdl.get_pixel_format_name i.Sdl.ri_texture_formats) i.Sdl.ri_max_texture_width i.Sdl.ri_max_texture_height let pp_hz ppf v = pp ppf "%dHz" v let pp_display_mode ppf m = pp ppf "@[<1>format:%s@ %dx%d@ @@ %a@]" (Sdl.get_pixel_format_name m.Sdl.dm_format) m.Sdl.dm_w m.Sdl.dm_h (pp_unknown pp_hz) m.Sdl.dm_refresh_rate let pp_controller_axis_event ppf e = pp ppf "@[<1>controller_axis_event which:%ld@ axis:%d value:%d@]" Sdl.Event.(get e controller_axis_which) Sdl.Event.(get e controller_axis_axis) Sdl.Event.(get e controller_axis_value) let pp_controller_button_event ppf e = pp ppf "@[<1>controller_button_event which:%ld@ button:%d state:%s@]" Sdl.Event.(get e controller_button_which) Sdl.Event.(get e controller_button_button) (button_state_str Sdl.Event.(get e controller_button_state)) let pp_controller_device_event ppf e = pp ppf "@[<1>controller_device_event %s which:%ld@ @]" Sdl.Event.(if get e typ = controller_device_added then "add" else if get e typ = controller_device_remapped then "remap" else if get e typ = controller_device_removed then "rem" else assert false) Sdl.Event.(get e controller_device_which) let pp_dollar_gesture_event ppf e = pp ppf "@[<1>dollar_gesture_event touch_id:%Ld@ gesture_id:%Ld@ \ num_fingers:%d@ error:%g@ (%g,%g)@]" Sdl.Event.(get e dollar_gesture_touch_id) Sdl.Event.(get e dollar_gesture_gesture_id) Sdl.Event.(get e dollar_gesture_num_fingers) Sdl.Event.(get e dollar_gesture_error) Sdl.Event.(get e dollar_gesture_x) Sdl.Event.(get e dollar_gesture_y) let pp_drop_event ppf e = pp ppf "@[<1>drop_event file:%a@]" (pp_opt pp_str) Sdl.Event.(drop_file_file e) let pp_touch_finger_event ppf e = pp ppf "@[<1>touch_finger_event %s touch_id:%Ld@ finger_id:%Ld@ (%g,%g)@ \ rel:(%g,%g)@ pressure:%g" Sdl.Event.(if get e typ = finger_down then "down" else if get e typ = finger_motion then "motion" else if get e typ = finger_up then "up" else assert false) Sdl.Event.(get e touch_finger_touch_id) Sdl.Event.(get e touch_finger_finger_id) Sdl.Event.(get e touch_finger_x) Sdl.Event.(get e touch_finger_y) Sdl.Event.(get e touch_finger_dx) Sdl.Event.(get e touch_finger_dy) Sdl.Event.(get e touch_finger_pressure) let pp_joy_axis_event ppf e = pp ppf "@[<1>joy_axis_event which:%ld@ axis:%d value:%d@]" Sdl.Event.(get e joy_axis_which) Sdl.Event.(get e joy_axis_axis) Sdl.Event.(get e joy_axis_value) let pp_joy_ball_event ppf e = pp ppf "@[<1>joy_ball_event which:%ld@ ball:%d (%d,%d)@]" Sdl.Event.(get e joy_ball_which) Sdl.Event.(get e joy_ball_ball) Sdl.Event.(get e joy_ball_xrel) Sdl.Event.(get e joy_ball_yrel) let pp_joy_button_event ppf e = pp ppf "@[<1>joy_button_event which:%ld@ button:%d state:%s@]" Sdl.Event.(get e joy_button_which) Sdl.Event.(get e joy_button_button) (button_state_str Sdl.Event.(get e joy_button_state)) let pp_joy_device_event ppf e = pp ppf "@[<1>joy_device_event %s which:%ld@ @]" Sdl.Event.(if get e typ = joy_device_added then "add" else "rem") Sdl.Event.(get e joy_device_which) let pp_joy_hat_event ppf e = pp ppf "@[<1>joy_hat_event which:%ld@ hat:%d value:%d@]" Sdl.Event.(get e joy_hat_which) Sdl.Event.(get e joy_hat_hat) Sdl.Event.(get e joy_hat_value) let pp_keyboard_event ppf e = pp ppf "@[<1>keyboard_event@ window_id:%d@ state:%s@ repeat:%b@ \ scancode:%s@ keycode:%s@ keymod:%d@]" Sdl.Event.(get e keyboard_window_id) (button_state_str Sdl.Event.(get e keyboard_state)) Sdl.Event.(get e keyboard_repeat > 0) Sdl.(get_scancode_name Event.(get e keyboard_scancode)) Sdl.(get_key_name Event.(get e keyboard_keycode)) Sdl.Event.(get e keyboard_keymod) let pp_mouse_button_event ppf e = pp ppf "@[<1>mouse_button_event window_id:%d@ which:%ld@ button:%d@ \ state:%s@ (%d,%d)@]" Sdl.Event.(get e mouse_button_window_id) Sdl.Event.(get e mouse_button_which) Sdl.Event.(get e mouse_button_button) (button_state_str Sdl.Event.(get e mouse_button_state)) Sdl.Event.(get e mouse_button_x) Sdl.Event.(get e mouse_button_y) let pp_mouse_motion_event ppf e = pp ppf "@[<1>mouse_motion_event window_id:%d@ which:%ld@ state:%ld@ \ (%d,%d)@ rel:(%d,%d)@]" Sdl.Event.(get e mouse_motion_window_id) Sdl.Event.(get e mouse_motion_which) Sdl.Event.(get e mouse_motion_state) Sdl.Event.(get e mouse_motion_x) Sdl.Event.(get e mouse_motion_y) Sdl.Event.(get e mouse_motion_xrel) Sdl.Event.(get e mouse_motion_yrel) let pp_mouse_wheel_direction ppf x = if x = Sdl.Event.mouse_wheel_normal then pp ppf "normal" else if x = Sdl.Event.mouse_wheel_flipped then pp ppf "flipped" else assert false let pp_mouse_wheel_event ppf e = pp ppf "@[<1>mouse_wheel_event window_id:%d@ which:%ld@ (%d,%d) %a @]" Sdl.Event.(get e mouse_wheel_window_id) Sdl.Event.(get e mouse_wheel_which) Sdl.Event.(get e mouse_wheel_x) Sdl.Event.(get e mouse_wheel_y) pp_mouse_wheel_direction Sdl.Event.(get e mouse_wheel_direction) let pp_multi_gesture_event ppf e = pp ppf "@[<1>multi_gesture_event touch_id:%Ld@ dtheta:%f@ ddist:%f@ \ (%f,%f)@ num_fingers:%d@]" Sdl.Event.(get e multi_gesture_touch_id) Sdl.Event.(get e multi_gesture_dtheta) Sdl.Event.(get e multi_gesture_ddist) Sdl.Event.(get e multi_gesture_x) Sdl.Event.(get e multi_gesture_y) Sdl.Event.(get e multi_gesture_num_fingers) let pp_text_editing_event ppf e = pp ppf "@[<1>text_editing_event window_id:%d@ text:'%s'@ start:%d @len:%d@]" Sdl.Event.(get e text_editing_window_id) Sdl.Event.(get e text_editing_text) Sdl.Event.(get e text_editing_start) Sdl.Event.(get e text_editing_length) let pp_text_input_event ppf e = pp ppf "@[<1>text_input_event window_id:%d@ text:'%s'@]" Sdl.Event.(get e text_input_window_id) Sdl.Event.(get e text_input_text) let pp_user_event ppf e = pp ppf "@[<1>user_event window_id:%d code:%d@]" Sdl.Event.(get e user_window_id) Sdl.Event.(get e user_code) let pp_window_event ppf e = let event_id_str id = try List.assoc id [ Sdl.Event.window_event_shown, "window_event_shown"; Sdl.Event.window_event_hidden, "window_event_hidden"; Sdl.Event.window_event_exposed, "window_event_exposed"; Sdl.Event.window_event_moved, "window_event_moved"; Sdl.Event.window_event_resized, "window_event_resized"; Sdl.Event.window_event_size_changed, "window_event_size_changed"; Sdl.Event.window_event_minimized, "window_event_minimized"; Sdl.Event.window_event_maximized, "window_event_maximized"; Sdl.Event.window_event_restored, "window_event_restored"; Sdl.Event.window_event_enter, "window_event_enter"; Sdl.Event.window_event_leave, "window_event_leave"; Sdl.Event.window_event_focus_gained, "window_event_focus_gained"; Sdl.Event.window_event_focus_lost, "window_event_focus_lost"; Sdl.Event.window_event_close, "window_event_close"; ] with Not_found -> "unkown" in pp ppf "@[<1>window_event@ %s window_id:%d@ (%ld,%ld)@]" (event_id_str Sdl.Event.(get e window_event_id)) Sdl.Event.(get e window_window_id) Sdl.Event.(get e window_data1) Sdl.Event.(get e window_data2) let cst s ppf e = pp ppf "%s" s let event_pp e = try List.assoc (Sdl.Event.(get e typ)) [ Sdl.Event.app_did_enter_background, cst "app_did_enter_background"; Sdl.Event.app_did_enter_foreground, cst "app_did_enter_foreground"; Sdl.Event.app_low_memory, cst "app_lowmemory"; Sdl.Event.app_terminating, cst "app_terminating"; Sdl.Event.app_will_enter_background, cst "app_willenterbackground"; Sdl.Event.app_will_enter_foreground, cst "app_will_enter_foreground"; Sdl.Event.clipboard_update, cst "clipboard_update"; Sdl.Event.controller_axis_motion, pp_controller_axis_event; Sdl.Event.controller_button_down, pp_controller_button_event; Sdl.Event.controller_button_up, pp_controller_button_event; Sdl.Event.controller_device_added, pp_controller_device_event; Sdl.Event.controller_device_remapped, pp_controller_device_event; Sdl.Event.controller_device_removed, pp_controller_device_event; Sdl.Event.dollar_gesture, pp_dollar_gesture_event; Sdl.Event.dollar_record, cst "dollar_record"; Sdl.Event.drop_file, pp_drop_event; Sdl.Event.finger_down, pp_touch_finger_event; Sdl.Event.finger_motion, pp_touch_finger_event; Sdl.Event.finger_up, pp_touch_finger_event; Sdl.Event.joy_axis_motion, pp_joy_axis_event; Sdl.Event.joy_ball_motion, pp_joy_ball_event; Sdl.Event.joy_button_down, pp_joy_button_event; Sdl.Event.joy_button_up, pp_joy_button_event; Sdl.Event.joy_device_added, pp_joy_device_event; Sdl.Event.joy_device_removed, pp_joy_device_event; Sdl.Event.joy_hat_motion, pp_joy_hat_event; Sdl.Event.key_down, pp_keyboard_event; Sdl.Event.key_up, pp_keyboard_event; Sdl.Event.mouse_button_down, pp_mouse_button_event; Sdl.Event.mouse_button_up, pp_mouse_button_event; Sdl.Event.mouse_motion, pp_mouse_motion_event; Sdl.Event.mouse_wheel, pp_mouse_wheel_event; Sdl.Event.multi_gesture, pp_multi_gesture_event; Sdl.Event.quit, cst "quit"; Sdl.Event.sys_wm_event, cst "sys_wm_event"; Sdl.Event.text_editing, pp_text_editing_event; Sdl.Event.text_input, pp_text_input_event; Sdl.Event.user_event, pp_user_event; Sdl.Event.window_event, pp_window_event; Sdl.Event.first_event, cst "firstevent"; Sdl.Event.last_event, cst "last_event"; ] with Not_found -> cst "unknown" let pp_event ppf e = pp ppf "%a" (event_pp e) e let pp_joystick_power_level ppf lvl = let open Sdl.Joystick_power_level in pp ppf "%s" (List.assoc lvl [low, "low"; medium, "medium"; full, "full"; wired, "wired"; max, "max"; unknown, "unknown"] ) let pp_joystick_type ppf ty = let open Sdl.Joystick_type in pp ppf "%s" (List.assoc ty [unknown,"unknown"; gamecontroller, "gamecontroller"; wheel,"wheel";arcade_stick,"arcade_stick"; flight_stick, "flight_stick"; dance_pad,"dance_pad";guitar,"guitar";drum_kit, "drum_kit"; arcade_pad,"arcade_pad"; throttle, "throttle" ] ) (*--------------------------------------------------------------------------- Copyright (c) 2013 The tsdl programmers Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
(*--------------------------------------------------------------------------- Copyright (c) 2013 The tsdl programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*)
calc_prio_left2.ml
open Earley_core open Earley open Generate_calc type calc_prio = | Sum | Prod | Pow | Atom let float_re = "[0-9]+\\([.][0-9]+\\)?\\([eE][-+]?[0-9]+\\)?" let float_num = Earley.fsequence (Earley_str.regexp ~name:"float" float_re (fun groupe -> groupe 0)) (Earley.empty (fun f -> float_of_string f)) let prod_sym = Earley.alternatives [Earley.fsequence_ignore (Earley.char '/' '/') (Earley.empty (/.)); Earley.fsequence_ignore (Earley.char '*' '*') (Earley.empty ( *. ))] let sum_sym = Earley.alternatives [Earley.fsequence_ignore (Earley.char '-' '-') (Earley.empty (-.)); Earley.fsequence_ignore (Earley.char '+' '+') (Earley.empty (+.))] let (expr_suit,expr_suit__set__grammar) = Earley.grammar_family "expr_suit" let expr = Earley.declare_grammar "expr" let _ = expr_suit__set__grammar (fun p -> Earley.alternatives ((if p >= Sum then [Earley.fsequence sum_sym (Earley.fsequence expr (Earley.empty (fun ((p',e') as _default_0) -> fun fn -> if p' <= Sum then give_up (); (fun e -> (Sum, (fn e e'))))))] else []) @ ((if p > Pow then [Earley.fsequence_ignore (Earley.string "**" "**") (Earley.fsequence expr (Earley.empty (fun ((p',e') as _default_0) -> if p' < Pow then give_up (); (fun e -> (Pow, (e ** e'))))))] else []) @ ((if p >= Prod then [Earley.fsequence prod_sym (Earley.fsequence expr (Earley.empty (fun ((p',e') as _default_0) -> fun fn -> if p' <= Prod then give_up (); (fun e -> (Prod, (fn e e'))))))] else []) @ [])))) let _ = Earley.set_grammar expr (Earley.alternatives [Earley.iter (Earley.fsequence expr (Earley.empty (fun ((p,e) as _default_0) -> Earley.fsequence (expr_suit p) (Earley.empty (fun g -> g e))))); Earley.fsequence float_num (Earley.empty (fun f -> (Atom, f))); Earley.fsequence_ignore (Earley.char '(' '(') (Earley.fsequence expr (Earley.fsequence_ignore (Earley.char ')' ')') (Earley.empty (fun ((_,e) as _default_0) -> (Atom, e))))); Earley.fsequence_ignore (Earley.char '-' '-') (Earley.fsequence expr (Earley.empty (fun ((p,e) as _default_0) -> if p < Pow then give_up (); (Pow, (-. e))))); Earley.fsequence_ignore (Earley.char '+' '+') (Earley.fsequence expr (Earley.empty (fun ((p,e) as _default_0) -> if p < Pow then give_up (); (Pow, e))))]) let _ = run (apply snd expr)
fprint_pretty.c
#include <stdlib.h> #include <string.h> #include "fq_nmod_mpoly.h" int fq_nmod_mpoly_fprint_pretty( FILE * file, const fq_nmod_mpoly_t A, const char ** x_in, const fq_nmod_mpoly_ctx_t ctx) { slong d = fq_nmod_ctx_degree(ctx->fqctx); slong len = A->length; ulong * exp = A->exps; slong bits = A->bits; slong i, j, N; fmpz * exponents; int r = 0; char ** x = (char **) x_in; TMP_INIT; if (len == 0) { r = (EOF != fputc('0', file)); return r; } #define CHECK_r if (r <= 0) goto done; N = mpoly_words_per_exp(bits, ctx->minfo); TMP_START; if (x == NULL) { x = (char **) TMP_ALLOC(ctx->minfo->nvars*sizeof(char *)); for (i = 0; i < ctx->minfo->nvars; i++) { x[i] = (char *) TMP_ALLOC(((FLINT_BITS+4)/3)*sizeof(char)); flint_sprintf(x[i], "x%wd", i+1); } } exponents = (fmpz *) TMP_ALLOC(ctx->minfo->nvars*sizeof(fmpz)); for (i = 0; i < ctx->minfo->nvars; i++) fmpz_init(exponents + i); for (i = 0; i < len; i++) { if (i > 0) { r = flint_fprintf(file, " + "); CHECK_r } r = flint_fprintf(file, "("); CHECK_r r = n_fq_fprint_pretty(file, A->coeffs + d*i, ctx->fqctx); CHECK_r r = flint_fprintf(file, ")"); CHECK_r mpoly_get_monomial_ffmpz(exponents, exp + N*i, bits, ctx->minfo); for (j = 0; j < ctx->minfo->nvars; j++) { int cmp = fmpz_cmp_ui(exponents + j, 1); if (cmp > 0) { r = flint_fprintf(file, "*%s^", x[j]); CHECK_r r = fmpz_fprint(file, exponents + j); CHECK_r } else if (cmp == 0) { r = flint_fprintf(file, "*%s", x[j]); CHECK_r } } } done: for (i = 0; i < ctx->minfo->nvars; i++) fmpz_clear(exponents + i); TMP_END; return r; }
/* 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/>. */
unit.mli
(** Unit values. @since 4.08 *) (** {1:unit The unit type} *) type t = unit = () (** The unit type. The constructor [()] is included here so that it has a path, but it is not intended to be used in user-defined data types. *) val equal : t -> t -> bool (** [equal u1 u2] is [true]. *) val compare : t -> t -> int (** [compare u1 u2] is [0]. *) val to_string : t -> string (** [to_string b] is ["()"]. *)
(**************************************************************************) (* *) (* OCaml *) (* *) (* The OCaml programmers *) (* *) (* Copyright 2018 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. *) (* *) (**************************************************************************)
irred_smprime_zippel.c
#include "nmod_mpoly_factor.h" #include "fq_nmod_mpoly_factor.h" static void _sort_and_delete_duplicates( fq_nmod_mpoly_t A, slong d, const mpoly_ctx_t mctx) { slong i, j; slong N = mpoly_words_per_exp(A->bits, mctx); for (i = 1; i < A->length; i++) for (j = i; j > 0 && mpoly_monomial_lt_nomask(A->exps + N*(j - 1), A->exps + N*j, N); j--) { mpoly_monomial_swap(A->exps + N*(j - 1), A->exps + N*j, N); _n_fq_swap(A->coeffs + d*(j - 1), A->coeffs + d*(j), d); } j = -1; for (i = 0; i < A->length; i++) { if (j >= 0 && mpoly_monomial_equal(A->exps + N*j, A->exps + N*i, N)) { FLINT_ASSERT(_n_fq_equal(A->coeffs + d*j, A->coeffs + d*i, d)); continue; } j++; _n_fq_set(A->coeffs + d*j, A->coeffs + d*i, d); mpoly_monomial_set(A->exps + N*j, A->exps + N*i, N); } j++; A->length = j; } static void _clearit( n_polyun_t W, mpoly_rbtree_ui_t T, slong idx) { mpoly_rbnode_ui_struct * nodes = T->nodes + 2; FLINT_ASSERT(0 <= idx && idx < T->length); if (nodes[idx].right >= 0) _clearit(W, T, nodes[idx].right); FLINT_ASSERT(W->length < W->alloc); W->exps[W->length] = nodes[idx].key; W->coeffs[W->length] = ((n_poly_struct *) T->data)[idx]; W->length++; if (nodes[idx].left >= 0) _clearit(W, T, nodes[idx].left); } static void fq_nmod_mpoly_set_eval_helper3( n_polyun_t EH, const fq_nmod_mpoly_t A, slong yvar, n_poly_struct * caches, const fq_nmod_mpoly_ctx_t ctx) { slong d = fq_nmod_ctx_degree(ctx->fqctx); slong xvar = 0; slong zvar = 1; slong i, j, k, n; ulong y, x, z; slong yoff, xoff, zoff, * off; slong yshift, xshift, zshift, * shift; mp_limb_t * p; flint_bitcnt_t bits = A->bits; slong Alen = A->length; const ulong * Aexps = A->exps; const mp_limb_t * Acoeffs = A->coeffs; slong N = mpoly_words_per_exp(bits, ctx->minfo); ulong mask = (-UWORD(1)) >> (FLINT_BITS - bits); ulong * ind; n_polyun_t T; mpoly_rbtree_ui_t W; TMP_INIT; TMP_START; n_polyun_init(T); mpoly_gen_offset_shift_sp(&yoff, &yshift, yvar, bits, ctx->minfo); mpoly_gen_offset_shift_sp(&xoff, &xshift, xvar, bits, ctx->minfo); mpoly_gen_offset_shift_sp(&zoff, &zshift, zvar, bits, ctx->minfo); off = (slong *) TMP_ALLOC(2*yvar*sizeof(slong)); shift = off + yvar; for (i = 2; i < yvar; i++) mpoly_gen_offset_shift_sp(&off[i], &shift[i], i, bits, ctx->minfo); mpoly_rbtree_ui_init(W, sizeof(n_poly_struct)); for (i = 0; i < Alen; i++) { n_poly_struct * Wc; int its_new; y = (Aexps[N*i + yoff] >> yshift) & mask; x = (Aexps[N*i + xoff] >> xshift) & mask; z = (Aexps[N*i + zoff] >> zshift) & mask; Wc = mpoly_rbtree_ui_lookup(W, &its_new, pack_exp3(y, x, z)); if (its_new) { n_poly_init2(Wc, 4); Wc->coeffs[0] = i; Wc->length = 1; } else { n_poly_fit_length(Wc, Wc->length + 1); Wc->coeffs[Wc->length] = i; Wc->length++; } } FLINT_ASSERT(W->length > 0); T->exps = FLINT_ARRAY_ALLOC(W->length, ulong); T->coeffs = FLINT_ARRAY_ALLOC(W->length, n_poly_struct); T->alloc = W->length; T->length = 0; _clearit(T, W, W->nodes[2 - 1].left); mpoly_rbtree_ui_clear(W); n_polyun_fit_length(EH, T->length); EH->length = T->length; for (i = 0; i < T->length; i++) { EH->exps[i] = T->exps[i]; n = T->coeffs[i].length; n_poly_fit_length(EH->coeffs + i, d*3*n); EH->coeffs[i].length = n; p = EH->coeffs[i].coeffs; ind = T->coeffs[i].coeffs; for (j = 0; j < n; j++) { slong Ai = ind[j]; /* set cur = monomial eval */ _n_fq_one(p + d*j, d); for (k = 2; k < yvar; k++) { ulong ei = (Aexps[N*Ai + off[k]] >> shift[k]) & mask; n_fq_pow_cache_mulpow_ui(p + d*j, p + d*j, ei, caches + 3*k + 0, caches + 3*k + 1, caches + 3*k + 2, ctx->fqctx); } /* copy cur to inc */ _n_fq_set(p + d*(1*n + j), p + d*(0*n + j), d); /* copy coeff */ _n_fq_set(p + d*(2*n + j), Acoeffs + d*Ai, d); } } n_polyun_clear(T); TMP_END; } static void fq_nmod_mpoly_set_evalp_helper3( n_polyun_t EH, const fq_nmod_mpoly_t A, slong yvar, n_poly_struct * caches, const fq_nmod_mpoly_ctx_t ctx) { slong d = fq_nmod_ctx_degree(ctx->fqctx); slong xvar = 0; slong zvar = 1; slong i, j, k, n; ulong y, x, z; slong yoff, xoff, zoff, * off; slong yshift, xshift, zshift, * shift; mp_limb_t * p; flint_bitcnt_t bits = A->bits; slong Alen = A->length; const ulong * Aexps = A->exps; const mp_limb_t * Acoeffs = A->coeffs; slong N = mpoly_words_per_exp(bits, ctx->minfo); ulong mask = (-UWORD(1)) >> (FLINT_BITS - bits); ulong * ind; n_polyun_t T; mpoly_rbtree_ui_t W; TMP_INIT; TMP_START; n_polyun_init(T); mpoly_gen_offset_shift_sp(&yoff, &yshift, yvar, bits, ctx->minfo); mpoly_gen_offset_shift_sp(&xoff, &xshift, xvar, bits, ctx->minfo); mpoly_gen_offset_shift_sp(&zoff, &zshift, zvar, bits, ctx->minfo); off = (slong *) TMP_ALLOC(2*yvar*sizeof(slong)); shift = off + yvar; for (i = 2; i < yvar; i++) mpoly_gen_offset_shift_sp(&off[i], &shift[i], i, bits, ctx->minfo); mpoly_rbtree_ui_init(W, sizeof(n_poly_struct)); for (i = 0; i < Alen; i++) { n_poly_struct * Wc; int its_new; y = (Aexps[N*i + yoff] >> yshift) & mask; x = (Aexps[N*i + xoff] >> xshift) & mask; z = (Aexps[N*i + zoff] >> zshift) & mask; Wc = mpoly_rbtree_ui_lookup(W, &its_new, pack_exp3(y, x, z)); if (its_new) { n_poly_init2(Wc, 4); Wc->coeffs[0] = i; Wc->length = 1; } else { n_poly_fit_length(Wc, Wc->length + 1); Wc->coeffs[Wc->length] = i; Wc->length++; } } FLINT_ASSERT(W->length > 0); T->exps = FLINT_ARRAY_ALLOC(W->length, ulong); T->coeffs = FLINT_ARRAY_ALLOC(W->length, n_poly_struct); T->alloc = W->length; T->length = 0; _clearit(T, W, W->nodes[2 - 1].left); mpoly_rbtree_ui_clear(W); n_polyun_fit_length(EH, T->length); EH->length = T->length; for (i = 0; i < T->length; i++) { EH->exps[i] = T->exps[i]; n = T->coeffs[i].length; n_poly_fit_length(EH->coeffs + i, (d + 2)*n); EH->coeffs[i].length = n; p = EH->coeffs[i].coeffs; ind = T->coeffs[i].coeffs; for (j = 0; j < n; j++) { slong Ai = ind[j]; /* set cur = monomial eval */ p[j] = 1; for (k = 2; k < yvar; k++) { ulong ei = (Aexps[N*Ai + off[k]] >> shift[k]) & mask; p[j] = nmod_pow_cache_mulpow_ui(p[j], ei, caches + 3*k + 0, caches + 3*k + 1, caches + 3*k + 2, ctx->fqctx->mod); } /* copy cur to inc */ p[j + n] = p[j]; /* copy coeff */ _n_fq_set(p + 2*n + d*j, Acoeffs + d*Ai, d); } } TMP_END; n_polyun_clear(T); } /* for each term Y^y*X^x*Z^z * pol(x1,...) in B with j < deg set Y^0*X^x*Z^z in H as the monomials with the monomial evals as coeffs merge monomial sets comming from different y's (shouldn't happen) */ static slong fq_nmod_mpoly_set_eval_helper_and_zip_form3( ulong * deg_, /* deg_X(B), output */ n_polyun_t EH, fq_nmod_mpolyu_t H, const fq_nmod_mpoly_t B, n_poly_struct * caches, slong yvar, /* Y = gen(yvar) (X = gen(0), Z = gen(1))*/ const fq_nmod_mpoly_ctx_t ctx) { slong d = fq_nmod_ctx_degree(ctx->fqctx); slong xvar = 0; slong zvar = 1; slong i, j, k, n; slong * off, * shift; ulong y, x, z; mp_limb_t * p; fq_nmod_mpoly_struct * Hc; slong old_len, zip_length = 0; flint_bitcnt_t bits = B->bits; slong Blen = B->length; const ulong * Bexps = B->exps; const mp_limb_t * Bcoeffs = B->coeffs; slong N = mpoly_words_per_exp(bits, ctx->minfo); ulong mask = (-UWORD(1)) >> (FLINT_BITS - bits); ulong * ind; n_polyun_t T; ulong deg; TMP_INIT; FLINT_ASSERT(bits <= FLINT_BITS); FLINT_ASSERT(bits == B->bits); FLINT_ASSERT(bits == H->bits); FLINT_ASSERT(Blen > 0); TMP_START; off = (slong *) TMP_ALLOC(2*yvar*sizeof(slong)); shift = off + yvar; for (i = 2; i < yvar; i++) mpoly_gen_offset_shift_sp(&off[i], &shift[i], i, bits, ctx->minfo); /* init T */ { mpoly_rbtree_ui_t W; n_poly_struct * Wc; slong yoff, xoff, zoff; slong yshift, xshift, zshift; int its_new; mpoly_gen_offset_shift_sp(&yoff, &yshift, yvar, bits, ctx->minfo); mpoly_gen_offset_shift_sp(&xoff, &xshift, xvar, bits, ctx->minfo); mpoly_gen_offset_shift_sp(&zoff, &zshift, zvar, bits, ctx->minfo); deg = (Bexps[N*0 + xoff] >> xshift) & mask; mpoly_rbtree_ui_init(W, sizeof(n_poly_struct)); for (i = 0; i < Blen; i++) { y = (Bexps[N*i + yoff] >> yshift) & mask; x = (Bexps[N*i + xoff] >> xshift) & mask; z = (Bexps[N*i + zoff] >> zshift) & mask; FLINT_ASSERT(x <= deg); Wc = mpoly_rbtree_ui_lookup(W, &its_new, pack_exp3(y, x, z)); if (its_new) { n_poly_init2(Wc, 4); Wc->coeffs[0] = i; Wc->length = 1; } else { n_poly_fit_length(Wc, Wc->length + 1); Wc->coeffs[Wc->length] = i; Wc->length++; } } FLINT_ASSERT(W->length > 0); T->exps = FLINT_ARRAY_ALLOC(W->length, ulong); T->coeffs = FLINT_ARRAY_ALLOC(W->length, n_poly_struct); T->alloc = W->length; T->length = 0; _clearit(T, W, W->nodes[2 - 1].left); mpoly_rbtree_ui_clear(W); } n_polyun_fit_length(EH, T->length); EH->length = T->length; H->length = 0; for (i = 0; i < T->length; i++) { EH->exps[i] = T->exps[i]; y = extract_exp(EH->exps[i], 2, 3); x = extract_exp(EH->exps[i], 1, 3); z = extract_exp(EH->exps[i], 0, 3); n = T->coeffs[i].length; n_poly_fit_length(EH->coeffs + i, d*3*n); EH->coeffs[i].length = n; p = EH->coeffs[i].coeffs; ind = T->coeffs[i].coeffs; for (j = 0; j < n; j++) { slong Bi = ind[j]; /* set cur = monomial eval */ _n_fq_one(p + d*j, d); for (k = 2; k < yvar; k++) { ulong ei = (Bexps[N*Bi + off[k]] >> shift[k]) & mask; n_fq_pow_cache_mulpow_ui(p + d*j, p + d*j, ei, caches + 3*k + 0, caches + 3*k + 1, caches + 3*k + 2, ctx->fqctx); } /* copy cur to inc */ _n_fq_set(p + d*(1*n + j), p + d*(0*n + j), d); /* copy coeff */ _n_fq_set(p + d*(2*n + j), Bcoeffs + d*Bi, d); } if (x < deg) { FLINT_ASSERT(y == 0 && "strange but ok"); Hc = _fq_nmod_mpolyu_get_coeff(H, pack_exp3(0, x, z), ctx); fq_nmod_mpoly_fit_length(Hc, n, ctx); old_len = Hc->length; for (j = 0; j < n; j++) { _n_fq_set(Hc->coeffs + d*(old_len + j), p + d*j, d); mpoly_monomial_set(Hc->exps + N*(old_len + j), Bexps + N*ind[j], N); } Hc->length += n; zip_length = FLINT_MAX(zip_length, Hc->length); if (old_len > 0) { FLINT_ASSERT(0 && "strange but ok"); _sort_and_delete_duplicates(Hc, d, ctx->minfo); } } } n_polyun_clear(T); TMP_END; *deg_ = deg; return zip_length; } static slong fq_nmod_mpoly_set_evalp_helper_and_zip_form3( ulong * deg_, /* deg_X(B), output */ n_polyun_t EH, fq_nmod_mpolyu_t H, const fq_nmod_mpoly_t B, n_poly_struct * caches, slong yvar, /* Y = gen(yvar) (X = gen(0), Z = gen(1))*/ const fq_nmod_mpoly_ctx_t ctx) { slong d = fq_nmod_ctx_degree(ctx->fqctx); slong xvar = 0; slong zvar = 1; slong i, j, k, n; slong * off, * shift; ulong y, x, z; mp_limb_t * p; fq_nmod_mpoly_struct * Hc; slong old_len, zip_length = 0; flint_bitcnt_t bits = B->bits; slong Blen = B->length; const ulong * Bexps = B->exps; const mp_limb_t * Bcoeffs = B->coeffs; slong N = mpoly_words_per_exp(bits, ctx->minfo); ulong mask = (-UWORD(1)) >> (FLINT_BITS - bits); ulong * ind; n_polyun_t T; ulong deg; TMP_INIT; FLINT_ASSERT(bits <= FLINT_BITS); FLINT_ASSERT(bits == B->bits); FLINT_ASSERT(bits == H->bits); FLINT_ASSERT(Blen > 0); TMP_START; off = (slong *) TMP_ALLOC(2*yvar*sizeof(slong)); shift = off + yvar; for (i = 2; i < yvar; i++) mpoly_gen_offset_shift_sp(&off[i], &shift[i], i, bits, ctx->minfo); /* init T */ { mpoly_rbtree_ui_t W; n_poly_struct * Wc; slong yoff, xoff, zoff; slong yshift, xshift, zshift; int its_new; mpoly_gen_offset_shift_sp(&yoff, &yshift, yvar, bits, ctx->minfo); mpoly_gen_offset_shift_sp(&xoff, &xshift, xvar, bits, ctx->minfo); mpoly_gen_offset_shift_sp(&zoff, &zshift, zvar, bits, ctx->minfo); deg = (Bexps[N*0 + xoff] >> xshift) & mask; mpoly_rbtree_ui_init(W, sizeof(n_poly_struct)); for (i = 0; i < Blen; i++) { y = (Bexps[N*i + yoff] >> yshift) & mask; x = (Bexps[N*i + xoff] >> xshift) & mask; z = (Bexps[N*i + zoff] >> zshift) & mask; FLINT_ASSERT(x <= deg); Wc = mpoly_rbtree_ui_lookup(W, &its_new, pack_exp3(y, x, z)); if (its_new) { n_poly_init2(Wc, 4); Wc->coeffs[0] = i; Wc->length = 1; } else { n_poly_fit_length(Wc, Wc->length + 1); Wc->coeffs[Wc->length] = i; Wc->length++; } } FLINT_ASSERT(W->length > 0); T->exps = FLINT_ARRAY_ALLOC(W->length, ulong); T->coeffs = FLINT_ARRAY_ALLOC(W->length, n_poly_struct); T->alloc = W->length; T->length = 0; _clearit(T, W, W->nodes[2 - 1].left); mpoly_rbtree_ui_clear(W); } n_polyun_fit_length(EH, T->length); EH->length = T->length; H->length = 0; for (i = 0; i < T->length; i++) { EH->exps[i] = T->exps[i]; y = extract_exp(EH->exps[i], 2, 3); x = extract_exp(EH->exps[i], 1, 3); z = extract_exp(EH->exps[i], 0, 3); n = T->coeffs[i].length; n_poly_fit_length(EH->coeffs + i, (d + 2)*n); EH->coeffs[i].length = n; p = EH->coeffs[i].coeffs; ind = T->coeffs[i].coeffs; for (j = 0; j < n; j++) { slong Bi = ind[j]; /* set cur = monomial eval */ p[j] = 1; for (k = 2; k < yvar; k++) { ulong ei = (Bexps[N*Bi + off[k]] >> shift[k]) & mask; p[j] = nmod_pow_cache_mulpow_ui(p[j], ei, caches + 3*k + 0, caches + 3*k + 1, caches + 3*k + 2, ctx->fqctx->mod); } /* copy cur to inc */ p[j + n] = p[j]; /* copy coeff */ _n_fq_set(p + 2*n + d*j, Bcoeffs + d*Bi, d); } if (x < deg) { FLINT_ASSERT(y == 0 && "strange but ok"); Hc = _fq_nmod_mpolyu_get_coeff(H, pack_exp3(0, x, z), ctx); _fq_nmod_mpoly_fit_length(&Hc->coeffs, &Hc->coeffs_alloc, 1, &Hc->exps, &Hc->exps_alloc, N, n); old_len = Hc->length; for (j = 0; j < n; j++) { Hc->coeffs[old_len + j] = p[j]; mpoly_monomial_set(Hc->exps + N*(old_len + j), Bexps + N*ind[j], N); } Hc->length += n; zip_length = FLINT_MAX(zip_length, Hc->length); if (old_len > 0) { FLINT_ASSERT(0 && "strange but ok"); _sort_and_delete_duplicates(Hc, 1, ctx->minfo); } } } n_polyun_clear(T); TMP_END; *deg_ = deg; return zip_length; } static void fq_nmod_polyu_eval_step( n_polyu_t E, n_polyun_t A, const fq_nmod_ctx_t ctx) { slong d = fq_nmod_ctx_degree(ctx); slong Ai, Ei, n; mp_limb_t * p; n_polyu_fit_length(E, d*A->length); Ei = 0; for (Ai = 0; Ai < A->length; Ai++) { FLINT_ASSERT(Ei < E->alloc); E->exps[Ei] = A->exps[Ai]; n = A->coeffs[Ai].length; p = A->coeffs[Ai].coeffs; FLINT_ASSERT(A->coeffs[Ai].alloc >= d*3*n); _n_fq_zip_eval_step(E->coeffs + d*Ei, p + d*(0*n), p + d*(1*n), p + d*(2*n), n, ctx); Ei += !_n_fq_is_zero(E->coeffs + d*Ei, d); } E->length = Ei; } static void fq_nmod_polyu_evalp_step( n_polyu_t E, n_polyun_t A, const fq_nmod_ctx_t ctx) { slong d = fq_nmod_ctx_degree(ctx); slong Ai, Ei, n; mp_limb_t * p; n_polyu_fit_length(E, d*A->length); Ei = 0; for (Ai = 0; Ai < A->length; Ai++) { FLINT_ASSERT(Ei < E->alloc); E->exps[Ei] = A->exps[Ai]; n = A->coeffs[Ai].length; p = A->coeffs[Ai].coeffs; FLINT_ASSERT(A->coeffs[Ai].alloc >= (d + 2)*n); _n_fqp_zip_eval_step(E->coeffs + d*Ei, p + 0*n, p + 1*n, p + 2*n, n, d, ctx->mod); Ei += !_n_fq_is_zero(E->coeffs + d*Ei, d); } E->length = Ei; } static void fq_nmod_polyu3_add_zip_limit1( n_polyun_t Z, const n_polyun_t A, const ulong deg1, slong cur_length, slong fit_length, const fq_nmod_ctx_t ctx) { slong d = fq_nmod_ctx_degree(ctx); const n_fq_poly_struct * Acoeffs = A->coeffs; ulong * Aexps = A->exps; n_fq_poly_struct * Zcoeffs = Z->coeffs; ulong * Zexps = Z->exps; slong Ai, ai, Zi, j; for (Zi = 0; Zi < Z->length; Zi++) { FLINT_ASSERT(Z->coeffs[Zi].length == cur_length); } Ai = -1; ai = -1; do { Ai++; } while (Ai < A->length && extract_exp(Aexps[Ai], 1, 3) >= deg1); if (Ai < A->length) ai = n_poly_degree(Acoeffs + Ai); Zi = 0; while (Ai < A->length && Zi < Z->length) { if (Aexps[Ai] + ai > Zexps[Zi]) { /* missing from Z */ n_polyun_fit_length(Z, Z->length + 1); Zcoeffs = Z->coeffs; Zexps = Z->exps; for (j = Z->length; j > Zi; j--) { n_poly_swap(Zcoeffs + j, Zcoeffs + j - 1); ULONG_SWAP(Zexps[j], Zexps[j - 1]); } Z->length++; Zexps[Zi] = Aexps[Ai] + ai; n_poly_fit_length(Zcoeffs + Zi, d*fit_length); Zcoeffs[Zi].length = cur_length; flint_mpn_zero(Zcoeffs[Zi].coeffs, d*cur_length); goto in_both; } else if (Aexps[Ai] + ai < Zexps[Zi]) { /* missing from A */ FLINT_ASSERT(d*(cur_length + 1) <= Zcoeffs[Zi].alloc); _n_fq_zero(Zcoeffs[Zi].coeffs + d*cur_length, d); Zcoeffs[Zi].length = cur_length + 1; Zi++; } else { in_both: FLINT_ASSERT(cur_length == Zcoeffs[Zi].length); FLINT_ASSERT(d*(cur_length + 1) <= Zcoeffs[Zi].alloc); _n_fq_set(Zcoeffs[Zi].coeffs + d*cur_length, Acoeffs[Ai].coeffs + d*ai, d); Zcoeffs[Zi].length = cur_length + 1; Zi++; do { ai--; } while (ai >= 0 && _n_fq_is_zero(Acoeffs[Ai].coeffs + d*ai, d)); if (ai < 0) { do { Ai++; } while (Ai < A->length && extract_exp(Aexps[Ai], 1, 3) >= deg1); if (Ai < A->length) ai = n_poly_degree(Acoeffs + Ai); } } } /* everything in A must be put on the end of Z */ while (Ai < A->length) { Zi = Z->length; n_polyun_fit_length(Z, Zi + A->length - Ai); Zcoeffs = Z->coeffs; Zexps = Z->exps; Zexps[Zi] = Aexps[Ai] + ai; n_poly_fit_length(Zcoeffs + Zi, d*fit_length); Zcoeffs[Zi].length = cur_length; flint_mpn_zero(Zcoeffs[Zi].coeffs, d*cur_length); FLINT_ASSERT(cur_length == Zcoeffs[Zi].length); FLINT_ASSERT(d*(cur_length + 1) <= Zcoeffs[Zi].alloc); _n_fq_set(Zcoeffs[Zi].coeffs + d*cur_length, Acoeffs[Ai].coeffs + d*ai, d); Zcoeffs[Zi].length = cur_length + 1; Z->length = ++Zi; do { ai--; } while (ai >= 0 && _n_fq_is_zero(Acoeffs[Ai].coeffs + d*ai, d)); if (ai < 0) { do { Ai++; } while (Ai < A->length && extract_exp(Aexps[Ai], 1, 3) >= deg1); if (Ai < A->length) ai = n_poly_degree(Acoeffs + Ai); } } /* everything in Z must have a zero appended */ while (Zi < Z->length) { FLINT_ASSERT(cur_length == Zcoeffs[Zi].length); FLINT_ASSERT(d*(cur_length + 1) <= Zcoeffs[Zi].alloc); _n_fq_zero(Zcoeffs[Zi].coeffs + d*cur_length, d); Zcoeffs[Zi].length = cur_length + 1; Zi++; } for (Zi = 0; Zi < Z->length; Zi++) { FLINT_ASSERT(Z->coeffs[Zi].length == cur_length + 1); } } /* for each Y^y*X^x*Z^z in B with x = deg, keep the Y^y*X^x*Z^z*poly(x1,...) in B for each Y^y*X^x*Z^z in Z, assert that x < deg if there is no Y^0*X^x*Z^y in H, fail find coefficients of poly using this entry in H output Y^y*X^x*Z^z*poly(x1,...) to A sort A return -1: singular vandermonde matrix encountered 0: inconsistent system encountered 1: success */ static int fq_nmod_mpoly_from_zip( fq_nmod_mpoly_t B, const n_polyun_t Z, fq_nmod_mpolyu_t H, ulong deg, slong yvar, /* Y = gen(yvar) */ const fq_nmod_mpoly_ctx_t ctx, n_polyun_t M, /* temp */ n_poly_stack_t St) { slong d = fq_nmod_ctx_degree(ctx->fqctx); int success; slong Hi, Zi, Bi, i, j; slong xvar = 0; slong zvar = 1; ulong x, y, z; flint_bitcnt_t bits = B->bits; mp_limb_t * Bcoeffs; ulong * Bexps; slong N = mpoly_words_per_exp_sp(bits, ctx->minfo); ulong mask = (-UWORD(1)) >> (FLINT_BITS - bits); slong xoff, xshift, yoff, yshift, zoff, zshift; fq_nmod_mpoly_struct * Hc; slong Hlen = H->length; FLINT_ASSERT(bits == H->bits); n_polyun_fit_length(M, Hlen + 1); for (i = 0; i <= Hlen; i++) M->coeffs[i].length = 0; mpoly_gen_offset_shift_sp(&yoff, &yshift, yvar, bits, ctx->minfo); mpoly_gen_offset_shift_sp(&xoff, &xshift, xvar, bits, ctx->minfo); mpoly_gen_offset_shift_sp(&zoff, &zshift, zvar, bits, ctx->minfo); /* x is most significant in ctx, so keeping the lc_x in B is easy */ FLINT_ASSERT(xvar == 0); for (Bi = 0; Bi < B->length; Bi++) { x = (((B->exps + N*Bi)[xoff] >> xshift) & mask); FLINT_ASSERT(x <= deg); if (x != deg) break; } for (Zi = 0; Zi < Z->length; Zi++) { y = extract_exp(Z->exps[Zi], 2, 3); x = extract_exp(Z->exps[Zi], 1, 3); z = extract_exp(Z->exps[Zi], 0, 3); FLINT_ASSERT(x < deg); Hi = mpoly_monomial_index1_nomask(H->exps, H->length, pack_exp3(0, x, z)); if (Hi < 0) return 0; FLINT_ASSERT(Hi < Hlen); FLINT_ASSERT(H->exps[Hi] == pack_exp3(0, x, z)); Hc = H->coeffs + Hi; FLINT_ASSERT(bits == Hc->bits); FLINT_ASSERT(Hc->length > 0); fq_nmod_mpoly_fit_length(B, Bi + Hc->length, ctx); Bcoeffs = B->coeffs; if (M->coeffs[Hi].length < 1) n_fq_poly_product_roots_n_fq(M->coeffs + Hi, Hc->coeffs, Hc->length, ctx->fqctx, St); n_poly_fit_length(M->coeffs + Hlen, d*Hc->length); success = _n_fq_zip_vand_solve(Bcoeffs + d*Bi, Hc->coeffs, Hc->length, Z->coeffs[Zi].coeffs, Z->coeffs[Zi].length, M->coeffs[Hi].coeffs, M->coeffs[Hlen].coeffs, ctx->fqctx); if (success < 1) return success; Bexps = B->exps; for (j = Bi, i = 0; i < Hc->length; j++, i++) { if (_n_fq_is_zero(Bcoeffs + d*j, d)) continue; FLINT_ASSERT(N*Bi < B->exps_alloc); FLINT_ASSERT(d*Bi < B->coeffs_alloc); _n_fq_set(Bcoeffs + d*Bi, Bcoeffs + d*j, d); mpoly_monomial_set(Bexps + N*Bi, Hc->exps + N*i, N); (Bexps + N*Bi)[yoff] += y << yshift; Bi++; } } B->length = Bi; fq_nmod_mpoly_sort_terms(B, ctx); FLINT_ASSERT(fq_nmod_mpoly_is_canonical(B, ctx)); return 1; } static int fq_nmod_mpoly_from_zipp( fq_nmod_mpoly_t B, const n_polyun_t Z, fq_nmod_mpolyu_t H, ulong deg, slong yvar, /* Y = gen(yvar) */ const fq_nmod_mpoly_ctx_t ctx, n_polyun_t M) { slong d = fq_nmod_ctx_degree(ctx->fqctx); int success; slong Hi, Zi, Bi, i, j; slong xvar = 0; slong zvar = 1; ulong x, y, z; flint_bitcnt_t bits = B->bits; mp_limb_t * Bcoeffs; ulong * Bexps; slong N = mpoly_words_per_exp_sp(bits, ctx->minfo); ulong mask = (-UWORD(1)) >> (FLINT_BITS - bits); slong xoff, xshift, yoff, yshift, zoff, zshift; fq_nmod_mpoly_struct * Hc; slong Hlen = H->length; FLINT_ASSERT(bits == H->bits); n_polyun_fit_length(M, Hlen + 1); for (i = 0; i <= Hlen; i++) M->coeffs[i].length = 0; mpoly_gen_offset_shift_sp(&yoff, &yshift, yvar, bits, ctx->minfo); mpoly_gen_offset_shift_sp(&xoff, &xshift, xvar, bits, ctx->minfo); mpoly_gen_offset_shift_sp(&zoff, &zshift, zvar, bits, ctx->minfo); /* x is most significant in ctx, so keeping the lc_x in B is easy */ FLINT_ASSERT(xvar == 0); for (Bi = 0; Bi < B->length; Bi++) { x = (((B->exps + N*Bi)[xoff] >> xshift) & mask); FLINT_ASSERT(x <= deg); if (x != deg) break; } for (Zi = 0; Zi < Z->length; Zi++) { y = extract_exp(Z->exps[Zi], 2, 3); x = extract_exp(Z->exps[Zi], 1, 3); z = extract_exp(Z->exps[Zi], 0, 3); FLINT_ASSERT(x < deg); Hi = mpoly_monomial_index1_nomask(H->exps, H->length, pack_exp3(0, x, z)); if (Hi < 0) return 0; FLINT_ASSERT(Hi < Hlen); FLINT_ASSERT(H->exps[Hi] == pack_exp3(0, x, z)); Hc = H->coeffs + Hi; FLINT_ASSERT(bits == Hc->bits); FLINT_ASSERT(Hc->length > 0); fq_nmod_mpoly_fit_length(B, Bi + Hc->length, ctx); Bcoeffs = B->coeffs; if (M->coeffs[Hi].length < 1) n_poly_mod_product_roots_nmod_vec(M->coeffs + Hi, Hc->coeffs, Hc->length, ctx->fqctx->mod); n_poly_fit_length(M->coeffs + Hlen, Hc->length); success = _n_fqp_zip_vand_solve(Bcoeffs + d*Bi, Hc->coeffs, Hc->length, Z->coeffs[Zi].coeffs, Z->coeffs[Zi].length, M->coeffs[Hi].coeffs, M->coeffs[Hlen].coeffs, ctx->fqctx); if (success < 1) return success; Bexps = B->exps; for (j = Bi, i = 0; i < Hc->length; j++, i++) { if (_n_fq_is_zero(Bcoeffs + d*j, d)) continue; FLINT_ASSERT(d*Bi < B->coeffs_alloc); FLINT_ASSERT(N*Bi < B->exps_alloc); _n_fq_set(Bcoeffs + d*Bi, Bcoeffs + d*j, d); mpoly_monomial_set(Bexps + N*Bi, Hc->exps + N*i, N); (Bexps + N*Bi)[yoff] += y << yshift; Bi++; } } B->length = Bi; fq_nmod_mpoly_sort_terms(B, ctx); FLINT_ASSERT(fq_nmod_mpoly_is_canonical(B, ctx)); return 1; } /* bit counts of all degrees should be < FLINT_BITS/3 */ int fq_nmod_mpoly_hlift_zippel( slong m, fq_nmod_mpoly_struct * B, slong r, const fq_nmod_struct * alpha, const fq_nmod_mpoly_t A, const slong * degs, const fq_nmod_mpoly_ctx_t ctx, flint_rand_t state) { int success, betas_in_fp; slong i; slong zip_fails_remaining; slong req_zip_images, cur_zip_image; fq_nmod_mpolyu_struct * H; n_polyun_struct M[1], Aeh[1], * Beh, * BBeval, * Z; n_polyu_struct Aeval[1], * Beval; fq_nmod_struct * beta; n_poly_struct * caches; flint_bitcnt_t bits = A->bits; fq_nmod_mpoly_t T1, T2; n_poly_bpoly_stack_t St; ulong * Bdegs; const slong degs0 = degs[0]; FLINT_ASSERT(m > 2); FLINT_ASSERT(r > 1); FLINT_ASSERT(bits <= FLINT_BITS); #if FLINT_WANT_ASSERT { fq_nmod_mpoly_t T; slong j, * check_degs = FLINT_ARRAY_ALLOC(ctx->minfo->nvars, slong); fq_nmod_mpoly_init(T, ctx); fq_nmod_mpoly_degrees_si(check_degs, A, ctx); for (j = 0; j < ctx->minfo->nvars; j++) FLINT_ASSERT(FLINT_BIT_COUNT(check_degs[j]) < FLINT_BITS/3); fq_nmod_mpoly_one(T, ctx); for (i = 0; i < r; i++) { fq_nmod_mpoly_degrees_si(check_degs, B + i, ctx); for (j = 0; j < ctx->minfo->nvars; j++) FLINT_ASSERT(FLINT_BIT_COUNT(check_degs[j]) < FLINT_BITS/3); fq_nmod_mpoly_mul(T, T, B + i, ctx); } fq_nmod_mpoly_sub(T, A, T, ctx); fq_nmod_mpoly_evaluate_one_fq_nmod(T, T, m, alpha + m - 1, ctx); FLINT_ASSERT(fq_nmod_mpoly_is_zero(T, ctx)); fq_nmod_mpoly_clear(T, ctx); flint_free(check_degs); } #endif n_poly_stack_init(St->poly_stack); n_bpoly_stack_init(St->bpoly_stack); beta = FLINT_ARRAY_ALLOC(ctx->minfo->nvars, fq_nmod_struct); for (i = 0; i < ctx->minfo->nvars; i++) fq_nmod_init(beta + i, ctx->fqctx); /* caches for powers of the betas */ caches = FLINT_ARRAY_ALLOC(3*ctx->minfo->nvars, n_poly_struct); for (i = 0; i < 3*ctx->minfo->nvars; i++) n_poly_init(caches + i); Bdegs = FLINT_ARRAY_ALLOC(r, ulong); H = FLINT_ARRAY_ALLOC(r, fq_nmod_mpolyu_struct); Beh = FLINT_ARRAY_ALLOC(r, n_polyun_struct); Beval = FLINT_ARRAY_ALLOC(r, n_polyu_struct); BBeval = FLINT_ARRAY_ALLOC(r, n_polyun_struct); Z = FLINT_ARRAY_ALLOC(r, n_polyun_struct); n_polyun_init(Aeh); n_polyu_init(Aeval); n_polyun_init(M); for (i = 0; i < r; i++) { fq_nmod_mpolyu_init(H + i, bits, ctx); n_polyun_init(Beh + i); n_polyu_init(Beval + i); n_polyun_init(BBeval + i); n_polyun_init(Z + i); } /* init done */ for (i = 0; i < r; i++) { success = fq_nmod_mpoly_repack_bits_inplace(B + i, bits, ctx); if (!success) goto cleanup; } zip_fails_remaining = 3; choose_betas: /* only beta[2], beta[3], ..., beta[m - 1] will be used */ betas_in_fp = (ctx->fqctx->mod.norm < FLINT_BITS/4); if (betas_in_fp) { for (i = 2; i < m; i++) { ulong bb = n_urandint(state, ctx->fqctx->mod.n - 3) + 2; fq_nmod_set_ui(beta + i, bb, ctx->fqctx); nmod_pow_cache_start(bb, caches + 3*i + 0, caches + 3*i + 1, caches + 3*i + 2); } fq_nmod_mpoly_set_evalp_helper3(Aeh, A, m, caches, ctx); } else { for (i = 2; i < m; i++) { fq_nmod_rand_not_zero(beta + i, state, ctx->fqctx); n_fq_pow_cache_start_fq_nmod(beta + i, caches + 3*i + 0, caches + 3*i + 1, caches + 3*i + 2, ctx->fqctx); } fq_nmod_mpoly_set_eval_helper3(Aeh, A, m, caches, ctx); } req_zip_images = 1; for (i = 0; i < r; i++) { slong this_images = betas_in_fp ? fq_nmod_mpoly_set_evalp_helper_and_zip_form3( Bdegs + i, Beh + i, H + i, B + i, caches, m, ctx) : fq_nmod_mpoly_set_eval_helper_and_zip_form3( Bdegs + i, Beh + i, H + i, B + i, caches, m, ctx); req_zip_images = FLINT_MAX(req_zip_images, this_images); FLINT_ASSERT(Bdegs[i] > 0); Z[i].length = 0; } for (cur_zip_image = 0; cur_zip_image < req_zip_images; cur_zip_image++) { if (betas_in_fp) { fq_nmod_polyu_evalp_step(Aeval, Aeh, ctx->fqctx); for (i = 0; i < r; i++) fq_nmod_polyu_evalp_step(Beval + i, Beh + i, ctx->fqctx); } else { fq_nmod_polyu_eval_step(Aeval, Aeh, ctx->fqctx); for (i = 0; i < r; i++) fq_nmod_polyu_eval_step(Beval + i, Beh + i, ctx->fqctx); } success = n_fq_polyu3_hlift(r, BBeval, Aeval, Beval, alpha + m - 1, degs0, ctx->fqctx, St); if (success < 1) { if (--zip_fails_remaining >= 0) goto choose_betas; success = 0; goto cleanup; } for (i = 0; i < r; i++) { fq_nmod_polyu3_add_zip_limit1(Z + i, BBeval + i, Bdegs[i], cur_zip_image, req_zip_images, ctx->fqctx); } } for (i = 0; i < r; i++) { success = betas_in_fp ? fq_nmod_mpoly_from_zipp(B + i, Z + i, H + i, Bdegs[i], m, ctx, M) : fq_nmod_mpoly_from_zip(B + i, Z + i, H + i, Bdegs[i], m, ctx, M, St->poly_stack); if (success < 1) { success = 0; goto cleanup; } } fq_nmod_mpoly_init3(T1, A->length, bits, ctx); fq_nmod_mpoly_init3(T2, A->length, bits, ctx); fq_nmod_mpoly_mul(T1, B + 0, B + 1, ctx); for (i = 2; i < r; i++) { fq_nmod_mpoly_mul(T2, T1, B + i, ctx); fq_nmod_mpoly_swap(T1, T2, ctx); } success = fq_nmod_mpoly_equal(T1, A, ctx); fq_nmod_mpoly_clear(T1, ctx); fq_nmod_mpoly_clear(T2, ctx); cleanup: n_polyun_clear(Aeh); n_polyu_clear(Aeval); n_polyun_clear(M); for (i = 0; i < r; i++) { fq_nmod_mpolyu_clear(H + i, ctx); n_polyun_clear(Beh + i); n_polyu_clear(Beval + i); n_polyun_clear(BBeval + i); n_polyun_clear(Z + i); } for (i = 0; i < ctx->minfo->nvars; i++) fq_nmod_clear(beta + i, ctx->fqctx); flint_free(beta); for (i = 0; i < 3*ctx->minfo->nvars; i++) n_poly_clear(caches + i); flint_free(caches); flint_free(Bdegs); flint_free(H); flint_free(Beh); flint_free(Beval); flint_free(BBeval); flint_free(Z); n_poly_stack_clear(St->poly_stack); n_bpoly_stack_clear(St->bpoly_stack); return success; } /* return 1: success 0: failed -1: exception */ int fq_nmod_mpoly_factor_irred_smprime_zippel( fq_nmod_mpolyv_t fac, const fq_nmod_mpoly_t A, const fq_nmod_mpoly_factor_t lcAfac, const fq_nmod_mpoly_t lcA, const fq_nmod_mpoly_ctx_t ctx, flint_rand_t state) { slong d = fq_nmod_ctx_degree(ctx->fqctx); int success; int alphas_tries_remaining, alphabetas_tries_remaining, alphabetas_length; const slong n = ctx->minfo->nvars - 1; slong i, j, k, r; fq_nmod_struct * alpha; n_poly_struct * alphabetas; fq_nmod_mpoly_struct * Aevals; slong * degs, * degeval; fq_nmod_mpolyv_t tfac; fq_nmod_mpoly_t t, Acopy; fq_nmod_mpoly_struct * newA; n_poly_t Abfc; n_bpoly_t Ab; n_tpoly_t Abfp; fq_nmod_mpoly_t m, mpow; fq_nmod_mpolyv_t new_lcs, lc_divs; FLINT_ASSERT(n > 1); FLINT_ASSERT(A->length > 1); FLINT_ASSERT(_n_fq_is_one(A->coeffs + d*0, d)); FLINT_ASSERT(A->bits <= FLINT_BITS); if (ctx->fqctx->modulus->length < n_clog(A->length, ctx->fqctx->modulus->mod.n)) return 0; fq_nmod_mpoly_init(Acopy, ctx); fq_nmod_mpoly_init(m, ctx); fq_nmod_mpoly_init(mpow, ctx); fq_nmod_mpolyv_init(new_lcs, ctx); fq_nmod_mpolyv_init(lc_divs, ctx); n_poly_init(Abfc); n_tpoly_init(Abfp); n_bpoly_init(Ab); degs = FLINT_ARRAY_ALLOC(n + 1, slong); degeval = FLINT_ARRAY_ALLOC(n + 1, slong); alpha = FLINT_ARRAY_ALLOC(n, fq_nmod_struct); alphabetas = FLINT_ARRAY_ALLOC(n, n_poly_struct); Aevals = FLINT_ARRAY_ALLOC(n, fq_nmod_mpoly_struct); for (i = 0; i < n; i++) { fq_nmod_init(alpha + i, ctx->fqctx); n_poly_init(alphabetas + i); fq_nmod_mpoly_init(Aevals + i, ctx); } fq_nmod_mpolyv_init(tfac, ctx); fq_nmod_mpoly_init(t, ctx); /* init done */ alphabetas_length = 2; alphas_tries_remaining = 10; fq_nmod_mpoly_degrees_si(degs, A, ctx); next_alpha: if (--alphas_tries_remaining < 0) { success = 0; goto cleanup; } for (i = 0; i < n; i++) { fq_nmod_rand(alpha + i, state, ctx->fqctx); if (fq_nmod_is_zero(alpha + i, ctx->fqctx)) fq_nmod_one(alpha + i, ctx->fqctx); } /* ensure degrees do not drop under evaluation */ for (i = n - 1; i >= 0; i--) { fq_nmod_mpoly_evaluate_one_fq_nmod(Aevals + i, i == n - 1 ? A : Aevals + i + 1, i + 1, alpha + i, ctx); fq_nmod_mpoly_degrees_si(degeval, Aevals + i, ctx); for (j = 0; j <= i; j++) if (degeval[j] != degs[j]) goto next_alpha; } /* make sure univar is squarefree */ fq_nmod_mpoly_derivative(t, Aevals + 0, 0, ctx); fq_nmod_mpoly_gcd(t, t, Aevals + 0, ctx); if (!fq_nmod_mpoly_is_one(t, ctx)) goto next_alpha; alphabetas_tries_remaining = 2 + alphabetas_length; next_alphabetas: if (--alphabetas_tries_remaining < 0) { if (++alphabetas_length > 5) { success = 0; goto cleanup; } goto next_alpha; } for (i = 0; i < n; i++) { n_poly_fit_length(alphabetas + i, d*alphabetas_length); n_fq_set_fq_nmod(alphabetas[i].coeffs + d*0, alpha + i, ctx->fqctx); for (j = d; j < d*alphabetas_length; j++) alphabetas[i].coeffs[j] = n_urandint(state, ctx->fqctx->mod.n); alphabetas[i].length = alphabetas_length; _n_fq_poly_normalise(alphabetas + i, d); } _fq_nmod_mpoly_eval_rest_to_n_fq_bpoly(Ab, A, alphabetas, ctx); success = n_fq_bpoly_factor_smprime(Abfc, Abfp, Ab, 0, ctx->fqctx); if (!success) { FLINT_ASSERT(0 && "this should not happen"); goto next_alpha; } r = Abfp->length; if (r < 2) { fq_nmod_mpolyv_fit_length(fac, 1, ctx); fac->length = 1; fq_nmod_mpoly_set(fac->coeffs + 0, A, ctx); success = 1; goto cleanup; } fq_nmod_mpolyv_fit_length(lc_divs, r, ctx); lc_divs->length = r; if (lcAfac->num > 0) { success = fq_nmod_mpoly_factor_lcc_wang(lc_divs->coeffs, lcAfac, Abfc, Abfp->coeffs, r, alphabetas, ctx); if (!success) goto next_alphabetas; } else { for (i = 0; i < r; i++) fq_nmod_mpoly_one(lc_divs->coeffs + i, ctx); } success = fq_nmod_mpoly_divides(m, lcA, lc_divs->coeffs + 0, ctx); FLINT_ASSERT(success); for (i = 1; i < r; i++) { success = fq_nmod_mpoly_divides(m, m, lc_divs->coeffs + i, ctx); FLINT_ASSERT(success); } fq_nmod_mpoly_pow_ui(mpow, m, r - 1, ctx); if (fq_nmod_mpoly_is_one(mpow, ctx)) { newA = (fq_nmod_mpoly_struct *) A; } else { newA = Acopy; fq_nmod_mpoly_mul(newA, A, mpow, ctx); } if (newA->bits > FLINT_BITS) { success = 0; goto cleanup; } fq_nmod_mpoly_degrees_si(degs, newA, ctx); for (i = 0; i < n + 1; i++) { if (FLINT_BIT_COUNT(degs[i]) >= FLINT_BITS/3) { success = -1; goto cleanup; } } fq_nmod_mpoly_set(t, mpow, ctx); for (i = n - 1; i >= 0; i--) { fq_nmod_mpoly_evaluate_one_fq_nmod(t, mpow, i + 1, alpha + i, ctx); fq_nmod_mpoly_swap(t, mpow, ctx); fq_nmod_mpoly_mul(Aevals + i, Aevals + i, mpow, ctx); } fq_nmod_mpolyv_fit_length(new_lcs, (n + 1)*r, ctx); i = n; for (j = 0; j < r; j++) { fq_nmod_mpoly_mul(new_lcs->coeffs + i*r + j, lc_divs->coeffs + j, m, ctx); } for (i = n - 1; i >= 0; i--) { for (j = 0; j < r; j++) { fq_nmod_mpoly_evaluate_one_fq_nmod(new_lcs->coeffs + i*r + j, new_lcs->coeffs + (i + 1)*r + j, i + 1, alpha + i, ctx); } } fq_nmod_mpolyv_fit_length(fac, r, ctx); fac->length = r; for (i = 0; i < r; i++) { fq_nmod_t q, qt; fq_nmod_init(q, ctx->fqctx); fq_nmod_init(qt, ctx->fqctx); FLINT_ASSERT(fq_nmod_mpoly_is_fq_nmod(new_lcs->coeffs + 0*r + i, ctx)); FLINT_ASSERT(fq_nmod_mpoly_length(new_lcs->coeffs + 0*r + i, ctx) == 1); _fq_nmod_mpoly_set_n_fq_bpoly_gen1_zero(fac->coeffs + i, newA->bits, Abfp->coeffs + i, 0, ctx); FLINT_ASSERT(fac->coeffs[i].length > 0); n_fq_get_fq_nmod(qt, fac->coeffs[i].coeffs + d*0, ctx->fqctx); fq_nmod_inv(q, qt, ctx->fqctx); n_fq_get_fq_nmod(qt, new_lcs->coeffs[0*r + i].coeffs + 0, ctx->fqctx); fq_nmod_mul(q, q, qt, ctx->fqctx); fq_nmod_mpoly_scalar_mul_fq_nmod(fac->coeffs + i, fac->coeffs + i, q, ctx); fq_nmod_clear(q, ctx->fqctx); fq_nmod_clear(qt, ctx->fqctx); } fq_nmod_mpolyv_fit_length(tfac, r, ctx); tfac->length = r; for (k = 1; k <= n; k++) { for (i = 0; i < r; i++) { _fq_nmod_mpoly_set_lead0(tfac->coeffs + i, fac->coeffs + i, new_lcs->coeffs + k*r + i, ctx); } if (k > 2) { success = fq_nmod_mpoly_hlift_zippel(k, tfac->coeffs, r, alpha, k < n ? Aevals + k : newA, degs, ctx, state); } else { success = fq_nmod_mpoly_hlift(k, tfac->coeffs, r, alpha, k < n ? Aevals + k : newA, degs, ctx); } if (!success) goto next_alphabetas; fq_nmod_mpolyv_swap(tfac, fac, ctx); } if (!fq_nmod_mpoly_is_fq_nmod(m, ctx)) { for (i = 0; i < r; i++) { /* hlift should not have returned any large bits */ FLINT_ASSERT(fac->coeffs[i].bits <= FLINT_BITS); if (!fq_nmod_mpolyl_content(t, fac->coeffs + i, 1, ctx)) { success = -1; goto cleanup; } success = fq_nmod_mpoly_divides(fac->coeffs + i, fac->coeffs + i, t, ctx); FLINT_ASSERT(success); } } for (i = 0; i < r; i++) fq_nmod_mpoly_make_monic(fac->coeffs + i, fac->coeffs + i, ctx); success = 1; cleanup: fq_nmod_mpolyv_clear(new_lcs, ctx); fq_nmod_mpolyv_clear(lc_divs, ctx); n_poly_clear(Abfc); n_tpoly_clear(Abfp); n_bpoly_clear(Ab); for (i = 0; i < n; i++) { fq_nmod_mpoly_clear(Aevals + i, ctx); n_poly_clear(alphabetas + i); fq_nmod_clear(alpha + i, ctx->fqctx); } flint_free(alphabetas); flint_free(alpha); flint_free(Aevals); flint_free(degs); flint_free(degeval); fq_nmod_mpolyv_clear(tfac, ctx); fq_nmod_mpoly_clear(t, ctx); fq_nmod_mpoly_clear(Acopy, ctx); fq_nmod_mpoly_clear(m, ctx); fq_nmod_mpoly_clear(mpow, ctx); #if FLINT_WANT_ASSERT if (success) { fq_nmod_mpoly_t prod; fq_nmod_mpoly_init(prod, ctx); fq_nmod_mpoly_one(prod, ctx); for (i = 0; i < fac->length; i++) fq_nmod_mpoly_mul(prod, prod, fac->coeffs + i, ctx); FLINT_ASSERT(fq_nmod_mpoly_equal(prod, A, ctx)); fq_nmod_mpoly_clear(prod, ctx); } #endif return success; }
/* Copyright (C) 2020 Daniel Schultz This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
t-div.c
#include <stdio.h> #include <stdlib.h> #include <gmp.h> #include "flint.h" #include "fmpz.h" #include "fmpq.h" int main(void) { int i; FLINT_TEST_INIT(state); flint_printf("div...."); fflush(stdout); /* x = y * z */ for (i = 0; i < 10000; i++) { fmpq_t x, y, z; mpq_t X, Y, Z; fmpq_init(x); fmpq_init(y); fmpq_init(z); mpq_init(X); mpq_init(Y); mpq_init(Z); fmpq_randtest(x, state, 200); fmpq_randtest(y, state, 200); do { fmpq_randtest(z, state, 200); } while (fmpq_is_zero(z)); fmpq_get_mpq(X, x); fmpq_get_mpq(Y, y); fmpq_get_mpq(Z, z); fmpq_div(x, y, z); if (!fmpq_is_canonical(x)) { flint_printf("FAIL: result not canonical!\n"); fmpq_print(x); flint_printf("\n"); fmpq_print(y); flint_printf("\n"); fmpq_print(z); flint_printf("\n"); fflush(stdout); flint_abort(); } mpq_div(X, Y, Z); fmpq_get_mpq(Y, x); if (!mpq_equal(X, Y)) { flint_printf("FAIL: fmpq_div(x,y,z) != mpq_div(X,Y,Z)\n"); flint_printf("x = "); fmpq_print(x); flint_printf("\ny = "); fmpq_print(y); flint_printf("\nz = "); fmpq_print(z); flint_printf("\n"); fflush(stdout); flint_abort(); } fmpq_clear(x); fmpq_clear(y); fmpq_clear(z); mpq_clear(X); mpq_clear(Y); mpq_clear(Z); } /* x = x / y */ for (i = 0; i < 10000; i++) { fmpq_t x, y; mpq_t X, Y; fmpq_init(x); fmpq_init(y); mpq_init(X); mpq_init(Y); fmpq_randtest(x, state, 200); do { fmpq_randtest(y, state, 200); } while (fmpq_is_zero(y)); fmpq_get_mpq(X, x); fmpq_get_mpq(Y, y); fmpq_div(x, x, y); if (!fmpq_is_canonical(x)) { flint_printf("FAIL: result not canonical!\n"); fmpq_print(x); flint_printf("\n"); fmpq_print(y); flint_printf("\n"); fflush(stdout); flint_abort(); } mpq_div(X, X, Y); fmpq_get_mpq(Y, x); if (!mpq_equal(X, Y)) { flint_printf("FAIL: fmpq_div(x,x,y) != mpq_div(X,X,Y)\n"); flint_printf("x = "); fmpq_print(x); flint_printf("\ny = "); fmpq_print(y); flint_printf("\n"); fflush(stdout); flint_abort(); } fmpq_clear(x); fmpq_clear(y); mpq_clear(X); mpq_clear(Y); } /* x = y / x */ for (i = 0; i < 10000; i++) { fmpq_t x, y; mpq_t X, Y; fmpq_init(x); fmpq_init(y); mpq_init(X); mpq_init(Y); do { fmpq_randtest(x, state, 200); } while (fmpq_is_zero(x)); fmpq_randtest(y, state, 200); fmpq_get_mpq(X, x); fmpq_get_mpq(Y, y); fmpq_div(x, y, x); if (!fmpq_is_canonical(x)) { flint_printf("FAIL: result not canonical!\n"); fmpq_print(x); flint_printf("\n"); fmpq_print(y); flint_printf("\n"); fflush(stdout); flint_abort(); } mpq_div(X, Y, X); fmpq_get_mpq(Y, x); if (!mpq_equal(X, Y)) { flint_printf("FAIL: fmpq_div(x,y,x) != mpq_div(X,Y,X)\n"); flint_printf("x = "); fmpq_print(x); flint_printf("\ny = "); fmpq_print(y); flint_printf("\n"); fflush(stdout); flint_abort(); } fmpq_clear(x); fmpq_clear(y); mpq_clear(X); mpq_clear(Y); } 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/>. */
optics.ml
let undefined _ = let exception Undefined in raise Undefined module Either = struct type ('a, 'b) t = Left of 'a | Right of 'b let left a = Left a let right b = Right b end module Lens = struct type ('s, 'a) t = V : ('s -> 'a * 'r) * ('a * 'r -> 's) -> ('s, 'a) t let v (type a b r) (f : a -> b * r) (g : b * r -> a) = V (f, g) let get (type a b) (V (f, _) : (a, b) t) (v : a) : b = fst @@ f v let set (type a b) (V (f, g) : (a, b) t) (t : a) (v : b) = let _, r = f t in g (v, r) let id x = x let fst : ('a * 'b, 'a) t = V (id, id) let snd : ('a * 'b, 'b) t = V ((fun (a, b) -> (b, a)), fun (b, a) -> (a, b)) let head : ('a list, 'a) t = V ((fun lst -> (List.hd lst, List.tl lst)), fun (hd, tl) -> hd :: tl) let splice_out lst n = let rec aux ((before, after) as acc) n = function | [] -> (List.rev before, List.rev after) | x :: xs when n < 0 -> aux (before, x :: after) (n - 1) xs | _ :: xs when n = 0 -> aux acc (n - 1) xs | x :: xs -> aux (x :: before, after) (n - 1) xs in aux ([], []) n lst let nth n : ('a list, 'a) t = V ( (fun lst -> (List.nth lst n, splice_out lst n)), fun (n, (b, a)) -> b @ [ n ] @ a ) let ( >> ) (type a b c) (V (f, g) : (a, b) t) (V (f', g') : (b, c) t) : (a, c) t = V ( (fun x -> let a, r1 = f x in let v, r2 = f' a in (v, (r1, r2))), fun (y, (r1, r2)) -> g (g' (y, r2), r1) ) end module Prism = struct type ('s, 'a) t = | V : ('s -> ('a, 'r) result) * (('a, 'r) result -> 's) -> ('s, 'a) t let get (type s a) (V (f, _) : (s, a) t) (v : s) : a option = Result.to_option @@ f v let set (type s a) (V (_, g) : (s, a) t) (v : a) = g (Ok v) let some = V ( (function Some t -> Ok t | None -> Error ()), function Ok t -> Some t | Error () -> None ) let none = V ( (function None -> Ok () | Some t -> Error t), function Ok () -> None | Error t -> Some t ) let ( >> ) (type a b c) (V (f, g) : (a, b) t) (V (f', g') : (b, c) t) : (a, c) t = let first x = match f x with | Error r1 -> Error (Either.left r1) | Ok b -> ( match f' b with Ok c -> Ok c | Error r2 -> Error (Either.right r2)) in let second = function | Ok v -> g (Ok (g' (Ok v))) | Error (Either.Left r1) -> g (Error r1) | Error (Either.Right r2) -> g (Ok (g' (Error r2))) in V (first, second) end module Optional = struct type ('s, 'a) t = ('s, 'a option) Lens.t let lens (type a b) (Lens.V (f, g) : (a, b) Lens.t) : (a, b) t = let wrapped_focus x = let v, r = f x in (Some v, r) in let wrapped_return = function | Some x, r -> g (x, r) | None, _ -> undefined () (* Not possible for a lens! *) in Lens.V (wrapped_focus, wrapped_return) let prism (type a b) (Prism.V (f, g) : (a, b) Prism.t) : (a, b) t = let wrapped_focus x = match f x with Ok v -> (Some v, None) | Error r -> (None, Some r) in let wrapped_return = function | Some x, None -> g (Ok x) | None, Some r -> g (Error r) | _ -> undefined () (* Other cases are not possible *) in Lens.V (wrapped_focus, wrapped_return) let ( >& ) (type a b c) (Lens.V (f1, g1) : (a, b) Lens.t) (Prism.V (f2, g2) : (b, c) Prism.t) : (a, c) t = let wrapped_focus x = let b, r1 = f1 x in match f2 b with | Ok c -> (Some c, Either.left r1) | Error r2 -> (None, Either.right (r1, r2)) in let wrapped_return = function | Some c, Either.Left r1 -> g1 (g2 (Ok c), r1) | None, Either.Right (r1, r2) -> g1 (g2 (Error r2), r1) | _ -> undefined () in Lens.V (wrapped_focus, wrapped_return) let ( >$ ) (type a b c) (Prism.V (f1, g1) : (a, b) Prism.t) (Lens.V (f2, g2) : (b, c) Lens.t) : (a, c) t = let wrapped_focus x = match f1 x with | Ok b -> let c, r2 = f2 b in (Some c, Either.right r2) | Error r1 -> (None, Either.left r1) in let wrapped_return = function | Some c, Either.Right r2 -> g1 (Ok (g2 (c, r2))) | None, Either.Left r1 -> g1 (Error r1) | _ -> undefined () in Lens.V (wrapped_focus, wrapped_return) let ( >> ) (type a b c) (Lens.V (f1, g1) : (a, b) t) (Lens.V (f2, g2) : (b, c) t) : (a, c) t = let wrapped_focus x = let b, r1 = f1 x in match b with | Some b -> let c, r2 = f2 b in (c, Either.right (r1, r2)) | None -> (None, Either.left r1) in let wrapped_return = function | c, Either.Right (r1, r2) -> g1 (Some (g2 (c, r2)), r1) | None, Either.Left r1 -> g1 (None, r1) | _ -> undefined () in Lens.V (wrapped_focus, wrapped_return) end module Infix = struct let ( >> ) = Optional.( >> ) let ( &> ) o l = Optional.(o >> lens l) let ( $> ) o p = Optional.(o >> prism p) let ( >& ) = Optional.( >& ) let ( >$ ) = Optional.( >$ ) let ( & ) = Lens.( >> ) let ( $ ) = Prism.( >> ) end
ubpf_vm.c
#define _GNU_SOURCE #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <stdarg.h> #include <inttypes.h> #include <sys/mman.h> #include "ubpf_int.h" #include "endian.h" #define MAX_EXT_FUNCS 64 static bool validate(const struct ubpf_vm *vm, const struct ebpf_inst *insts, uint32_t num_insts, char **errmsg); static bool bounds_check(void *addr, int size, const char *type, uint16_t cur_pc, void *mem, size_t mem_len, void *stack); struct ubpf_vm * ubpf_create(void) { struct ubpf_vm *vm = calloc(1, sizeof(*vm)); if (vm == NULL) { return NULL; } vm->ext_funcs = calloc(MAX_EXT_FUNCS, sizeof(*vm->ext_funcs)); if (vm->ext_funcs == NULL) { ubpf_destroy(vm); return NULL; } vm->ext_func_names = calloc(MAX_EXT_FUNCS, sizeof(*vm->ext_func_names)); if (vm->ext_func_names == NULL) { ubpf_destroy(vm); return NULL; } return vm; } void ubpf_destroy(struct ubpf_vm *vm) { if (vm->jitted) { munmap(vm->jitted, vm->jitted_size); } free(vm->insts); free(vm->ext_funcs); free(vm->ext_func_names); free(vm); } int ubpf_register(struct ubpf_vm *vm, unsigned int idx, const char *name, void *fn) { if (idx >= MAX_EXT_FUNCS) { return -1; } vm->ext_funcs[idx] = (ext_func)fn; vm->ext_func_names[idx] = name; return 0; } unsigned int ubpf_lookup_registered_function(struct ubpf_vm *vm, const char *name) { int i; for (i = 0; i < MAX_EXT_FUNCS; i++) { const char *other = vm->ext_func_names[i]; if (other && !strcmp(other, name)) { return i; } } return -1; } int ubpf_load(struct ubpf_vm *vm, const void *code, uint32_t code_len, char **errmsg) { *errmsg = NULL; if (vm->insts) { *errmsg = ubpf_error("code has already been loaded into this VM"); return -1; } if (code_len % 8 != 0) { *errmsg = ubpf_error("code_len must be a multiple of 8"); return -1; } if (!validate(vm, code, code_len/8, errmsg)) { return -1; } vm->insts = malloc(code_len); if (vm->insts == NULL) { *errmsg = ubpf_error("out of memory"); return -1; } memcpy(vm->insts, code, code_len); vm->num_insts = code_len/sizeof(vm->insts[0]); return 0; } static uint32_t u32(uint64_t x) { return x; } uint64_t ubpf_exec(const struct ubpf_vm *vm, void *mem, size_t mem_len) { uint16_t pc = 0; const struct ebpf_inst *insts = vm->insts; uint64_t reg[16]; uint64_t stack[(STACK_SIZE+7)/8]; if (!insts) { /* Code must be loaded before we can execute */ return UINT64_MAX; } reg[1] = (uintptr_t)mem; reg[2] = (uint64_t)mem_len; reg[10] = (uintptr_t)stack + sizeof(stack); while (1) { const uint16_t cur_pc = pc; struct ebpf_inst inst = insts[pc++]; switch (inst.opcode) { case EBPF_OP_ADD_IMM: reg[inst.dst] += inst.imm; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_ADD_REG: reg[inst.dst] += reg[inst.src]; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_SUB_IMM: reg[inst.dst] -= inst.imm; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_SUB_REG: reg[inst.dst] -= reg[inst.src]; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_MUL_IMM: reg[inst.dst] *= inst.imm; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_MUL_REG: reg[inst.dst] *= reg[inst.src]; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_DIV_IMM: reg[inst.dst] = u32(reg[inst.dst]) / u32(inst.imm); reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_DIV_REG: if (reg[inst.src] == 0) { fprintf(stderr, "uBPF error: division by zero at PC %u\n", cur_pc); return UINT64_MAX; } reg[inst.dst] = u32(reg[inst.dst]) / u32(reg[inst.src]); reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_OR_IMM: reg[inst.dst] |= inst.imm; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_OR_REG: reg[inst.dst] |= reg[inst.src]; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_AND_IMM: reg[inst.dst] &= inst.imm; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_AND_REG: reg[inst.dst] &= reg[inst.src]; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_LSH_IMM: reg[inst.dst] <<= inst.imm; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_LSH_REG: reg[inst.dst] <<= reg[inst.src]; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_RSH_IMM: reg[inst.dst] = u32(reg[inst.dst]) >> inst.imm; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_RSH_REG: reg[inst.dst] = u32(reg[inst.dst]) >> reg[inst.src]; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_NEG: reg[inst.dst] = -reg[inst.dst]; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_MOD_IMM: reg[inst.dst] = u32(reg[inst.dst]) % u32(inst.imm); reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_MOD_REG: if (reg[inst.src] == 0) { fprintf(stderr, "uBPF error: division by zero at PC %u\n", cur_pc); return UINT64_MAX; } reg[inst.dst] = u32(reg[inst.dst]) % u32(reg[inst.src]); break; case EBPF_OP_XOR_IMM: reg[inst.dst] ^= inst.imm; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_XOR_REG: reg[inst.dst] ^= reg[inst.src]; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_MOV_IMM: reg[inst.dst] = inst.imm; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_MOV_REG: reg[inst.dst] = reg[inst.src]; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_ARSH_IMM: reg[inst.dst] = (int32_t)reg[inst.dst] >> inst.imm; reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_ARSH_REG: reg[inst.dst] = (int32_t)reg[inst.dst] >> u32(reg[inst.src]); reg[inst.dst] &= UINT32_MAX; break; case EBPF_OP_LE: if (inst.imm == 16) { reg[inst.dst] = htole16(reg[inst.dst]); } else if (inst.imm == 32) { reg[inst.dst] = htole32(reg[inst.dst]); } else if (inst.imm == 64) { reg[inst.dst] = htole64(reg[inst.dst]); } break; case EBPF_OP_BE: if (inst.imm == 16) { reg[inst.dst] = htobe16(reg[inst.dst]); } else if (inst.imm == 32) { reg[inst.dst] = htobe32(reg[inst.dst]); } else if (inst.imm == 64) { reg[inst.dst] = htobe64(reg[inst.dst]); } break; case EBPF_OP_ADD64_IMM: reg[inst.dst] += inst.imm; break; case EBPF_OP_ADD64_REG: reg[inst.dst] += reg[inst.src]; break; case EBPF_OP_SUB64_IMM: reg[inst.dst] -= inst.imm; break; case EBPF_OP_SUB64_REG: reg[inst.dst] -= reg[inst.src]; break; case EBPF_OP_MUL64_IMM: reg[inst.dst] *= inst.imm; break; case EBPF_OP_MUL64_REG: reg[inst.dst] *= reg[inst.src]; break; case EBPF_OP_DIV64_IMM: reg[inst.dst] /= inst.imm; break; case EBPF_OP_DIV64_REG: if (reg[inst.src] == 0) { fprintf(stderr, "uBPF error: division by zero at PC %u\n", cur_pc); return UINT64_MAX; } reg[inst.dst] /= reg[inst.src]; break; case EBPF_OP_OR64_IMM: reg[inst.dst] |= inst.imm; break; case EBPF_OP_OR64_REG: reg[inst.dst] |= reg[inst.src]; break; case EBPF_OP_AND64_IMM: reg[inst.dst] &= inst.imm; break; case EBPF_OP_AND64_REG: reg[inst.dst] &= reg[inst.src]; break; case EBPF_OP_LSH64_IMM: reg[inst.dst] <<= inst.imm; break; case EBPF_OP_LSH64_REG: reg[inst.dst] <<= reg[inst.src]; break; case EBPF_OP_RSH64_IMM: reg[inst.dst] >>= inst.imm; break; case EBPF_OP_RSH64_REG: reg[inst.dst] >>= reg[inst.src]; break; case EBPF_OP_NEG64: reg[inst.dst] = -reg[inst.dst]; break; case EBPF_OP_MOD64_IMM: reg[inst.dst] %= inst.imm; break; case EBPF_OP_MOD64_REG: if (reg[inst.src] == 0) { fprintf(stderr, "uBPF error: division by zero at PC %u\n", cur_pc); return UINT64_MAX; } reg[inst.dst] %= reg[inst.src]; break; case EBPF_OP_XOR64_IMM: reg[inst.dst] ^= inst.imm; break; case EBPF_OP_XOR64_REG: reg[inst.dst] ^= reg[inst.src]; break; case EBPF_OP_MOV64_IMM: reg[inst.dst] = inst.imm; break; case EBPF_OP_MOV64_REG: reg[inst.dst] = reg[inst.src]; break; case EBPF_OP_ARSH64_IMM: reg[inst.dst] = (int64_t)reg[inst.dst] >> inst.imm; break; case EBPF_OP_ARSH64_REG: reg[inst.dst] = (int64_t)reg[inst.dst] >> reg[inst.src]; break; /* * HACK runtime bounds check * * Needed since we don't have a verifier yet. */ #define BOUNDS_CHECK_LOAD(size) \ do { \ if (!bounds_check((void *)reg[inst.src] + inst.offset, size, "load", cur_pc, mem, mem_len, stack)) { \ return UINT64_MAX; \ } \ } while (0) #define BOUNDS_CHECK_STORE(size) \ do { \ if (!bounds_check((void *)reg[inst.dst] + inst.offset, size, "store", cur_pc, mem, mem_len, stack)) { \ return UINT64_MAX; \ } \ } while (0) case EBPF_OP_LDXW: BOUNDS_CHECK_LOAD(4); reg[inst.dst] = *(uint32_t *)(uintptr_t)(reg[inst.src] + inst.offset); break; case EBPF_OP_LDXH: BOUNDS_CHECK_LOAD(2); reg[inst.dst] = *(uint16_t *)(uintptr_t)(reg[inst.src] + inst.offset); break; case EBPF_OP_LDXB: BOUNDS_CHECK_LOAD(1); reg[inst.dst] = *(uint8_t *)(uintptr_t)(reg[inst.src] + inst.offset); break; case EBPF_OP_LDXDW: BOUNDS_CHECK_LOAD(8); reg[inst.dst] = *(uint64_t *)(uintptr_t)(reg[inst.src] + inst.offset); break; case EBPF_OP_STW: BOUNDS_CHECK_STORE(4); *(uint32_t *)(uintptr_t)(reg[inst.dst] + inst.offset) = inst.imm; break; case EBPF_OP_STH: BOUNDS_CHECK_STORE(2); *(uint16_t *)(uintptr_t)(reg[inst.dst] + inst.offset) = inst.imm; break; case EBPF_OP_STB: BOUNDS_CHECK_STORE(1); *(uint8_t *)(uintptr_t)(reg[inst.dst] + inst.offset) = inst.imm; break; case EBPF_OP_STDW: BOUNDS_CHECK_STORE(8); *(uint64_t *)(uintptr_t)(reg[inst.dst] + inst.offset) = inst.imm; break; case EBPF_OP_STXW: BOUNDS_CHECK_STORE(4); *(uint32_t *)(uintptr_t)(reg[inst.dst] + inst.offset) = reg[inst.src]; break; case EBPF_OP_STXH: BOUNDS_CHECK_STORE(2); *(uint16_t *)(uintptr_t)(reg[inst.dst] + inst.offset) = reg[inst.src]; break; case EBPF_OP_STXB: BOUNDS_CHECK_STORE(1); *(uint8_t *)(uintptr_t)(reg[inst.dst] + inst.offset) = reg[inst.src]; break; case EBPF_OP_STXDW: BOUNDS_CHECK_STORE(8); *(uint64_t *)(uintptr_t)(reg[inst.dst] + inst.offset) = reg[inst.src]; break; case EBPF_OP_LDDW: reg[inst.dst] = (uint32_t)inst.imm | ((uint64_t)insts[pc++].imm << 32); break; case EBPF_OP_JA: pc += inst.offset; break; case EBPF_OP_JEQ_IMM: if (reg[inst.dst] == inst.imm) { pc += inst.offset; } break; case EBPF_OP_JEQ_REG: if (reg[inst.dst] == reg[inst.src]) { pc += inst.offset; } break; case EBPF_OP_JGT_IMM: if (reg[inst.dst] > (uint32_t)inst.imm) { pc += inst.offset; } break; case EBPF_OP_JGT_REG: if (reg[inst.dst] > reg[inst.src]) { pc += inst.offset; } break; case EBPF_OP_JGE_IMM: if (reg[inst.dst] >= (uint32_t)inst.imm) { pc += inst.offset; } break; case EBPF_OP_JGE_REG: if (reg[inst.dst] >= reg[inst.src]) { pc += inst.offset; } break; case EBPF_OP_JLT_IMM: if (reg[inst.dst] < (uint32_t)inst.imm) { pc += inst.offset; } break; case EBPF_OP_JLT_REG: if (reg[inst.dst] < reg[inst.src]) { pc += inst.offset; } break; case EBPF_OP_JLE_IMM: if (reg[inst.dst] <= (uint32_t)inst.imm) { pc += inst.offset; } break; case EBPF_OP_JLE_REG: if (reg[inst.dst] <= reg[inst.src]) { pc += inst.offset; } break; case EBPF_OP_JSET_IMM: if (reg[inst.dst] & inst.imm) { pc += inst.offset; } break; case EBPF_OP_JSET_REG: if (reg[inst.dst] & reg[inst.src]) { pc += inst.offset; } break; case EBPF_OP_JNE_IMM: if (reg[inst.dst] != inst.imm) { pc += inst.offset; } break; case EBPF_OP_JNE_REG: if (reg[inst.dst] != reg[inst.src]) { pc += inst.offset; } break; case EBPF_OP_JSGT_IMM: if ((int64_t)reg[inst.dst] > inst.imm) { pc += inst.offset; } break; case EBPF_OP_JSGT_REG: if ((int64_t)reg[inst.dst] > (int64_t)reg[inst.src]) { pc += inst.offset; } break; case EBPF_OP_JSGE_IMM: if ((int64_t)reg[inst.dst] >= inst.imm) { pc += inst.offset; } break; case EBPF_OP_JSGE_REG: if ((int64_t)reg[inst.dst] >= (int64_t)reg[inst.src]) { pc += inst.offset; } break; case EBPF_OP_JSLT_IMM: if ((int64_t)reg[inst.dst] < inst.imm) { pc += inst.offset; } break; case EBPF_OP_JSLT_REG: if ((int64_t)reg[inst.dst] < (int64_t)reg[inst.src]) { pc += inst.offset; } break; case EBPF_OP_JSLE_IMM: if ((int64_t)reg[inst.dst] <= inst.imm) { pc += inst.offset; } break; case EBPF_OP_JSLE_REG: if ((int64_t)reg[inst.dst] <= (int64_t)reg[inst.src]) { pc += inst.offset; } break; case EBPF_OP_EXIT: return reg[0]; case EBPF_OP_CALL: reg[0] = vm->ext_funcs[inst.imm](reg[1], reg[2], reg[3], reg[4], reg[5]); break; } } } static bool validate(const struct ubpf_vm *vm, const struct ebpf_inst *insts, uint32_t num_insts, char **errmsg) { if (num_insts >= MAX_INSTS) { *errmsg = ubpf_error("too many instructions (max %u)", MAX_INSTS); return false; } if (num_insts == 0 || insts[num_insts-1].opcode != EBPF_OP_EXIT) { *errmsg = ubpf_error("no exit at end of instructions"); return false; } int i; for (i = 0; i < num_insts; i++) { struct ebpf_inst inst = insts[i]; bool store = false; switch (inst.opcode) { case EBPF_OP_ADD_IMM: case EBPF_OP_ADD_REG: case EBPF_OP_SUB_IMM: case EBPF_OP_SUB_REG: case EBPF_OP_MUL_IMM: case EBPF_OP_MUL_REG: case EBPF_OP_DIV_REG: case EBPF_OP_OR_IMM: case EBPF_OP_OR_REG: case EBPF_OP_AND_IMM: case EBPF_OP_AND_REG: case EBPF_OP_LSH_IMM: case EBPF_OP_LSH_REG: case EBPF_OP_RSH_IMM: case EBPF_OP_RSH_REG: case EBPF_OP_NEG: case EBPF_OP_MOD_REG: case EBPF_OP_XOR_IMM: case EBPF_OP_XOR_REG: case EBPF_OP_MOV_IMM: case EBPF_OP_MOV_REG: case EBPF_OP_ARSH_IMM: case EBPF_OP_ARSH_REG: break; case EBPF_OP_LE: case EBPF_OP_BE: if (inst.imm != 16 && inst.imm != 32 && inst.imm != 64) { *errmsg = ubpf_error("invalid endian immediate at PC %d", i); return false; } break; case EBPF_OP_ADD64_IMM: case EBPF_OP_ADD64_REG: case EBPF_OP_SUB64_IMM: case EBPF_OP_SUB64_REG: case EBPF_OP_MUL64_IMM: case EBPF_OP_MUL64_REG: case EBPF_OP_DIV64_REG: case EBPF_OP_OR64_IMM: case EBPF_OP_OR64_REG: case EBPF_OP_AND64_IMM: case EBPF_OP_AND64_REG: case EBPF_OP_LSH64_IMM: case EBPF_OP_LSH64_REG: case EBPF_OP_RSH64_IMM: case EBPF_OP_RSH64_REG: case EBPF_OP_NEG64: case EBPF_OP_MOD64_REG: case EBPF_OP_XOR64_IMM: case EBPF_OP_XOR64_REG: case EBPF_OP_MOV64_IMM: case EBPF_OP_MOV64_REG: case EBPF_OP_ARSH64_IMM: case EBPF_OP_ARSH64_REG: break; case EBPF_OP_LDXW: case EBPF_OP_LDXH: case EBPF_OP_LDXB: case EBPF_OP_LDXDW: break; case EBPF_OP_STW: case EBPF_OP_STH: case EBPF_OP_STB: case EBPF_OP_STDW: case EBPF_OP_STXW: case EBPF_OP_STXH: case EBPF_OP_STXB: case EBPF_OP_STXDW: store = true; break; case EBPF_OP_LDDW: if (i + 1 >= num_insts || insts[i+1].opcode != 0) { *errmsg = ubpf_error("incomplete lddw at PC %d", i); return false; } i++; /* Skip next instruction */ break; case EBPF_OP_JA: case EBPF_OP_JEQ_REG: case EBPF_OP_JEQ_IMM: case EBPF_OP_JGT_REG: case EBPF_OP_JGT_IMM: case EBPF_OP_JGE_REG: case EBPF_OP_JGE_IMM: case EBPF_OP_JLT_REG: case EBPF_OP_JLT_IMM: case EBPF_OP_JLE_REG: case EBPF_OP_JLE_IMM: case EBPF_OP_JSET_REG: case EBPF_OP_JSET_IMM: case EBPF_OP_JNE_REG: case EBPF_OP_JNE_IMM: case EBPF_OP_JSGT_IMM: case EBPF_OP_JSGT_REG: case EBPF_OP_JSGE_IMM: case EBPF_OP_JSGE_REG: case EBPF_OP_JSLT_IMM: case EBPF_OP_JSLT_REG: case EBPF_OP_JSLE_IMM: case EBPF_OP_JSLE_REG: if (inst.offset == -1) { *errmsg = ubpf_error("infinite loop at PC %d", i); return false; } int new_pc = i + 1 + inst.offset; if (new_pc < 0 || new_pc >= num_insts) { *errmsg = ubpf_error("jump out of bounds at PC %d", i); return false; } else if (insts[new_pc].opcode == 0) { *errmsg = ubpf_error("jump to middle of lddw at PC %d", i); return false; } break; case EBPF_OP_CALL: if (inst.imm < 0 || inst.imm >= MAX_EXT_FUNCS) { *errmsg = ubpf_error("invalid call immediate at PC %d", i); return false; } if (!vm->ext_funcs[inst.imm]) { *errmsg = ubpf_error("call to nonexistent function %u at PC %d", inst.imm, i); return false; } break; case EBPF_OP_EXIT: break; case EBPF_OP_DIV_IMM: case EBPF_OP_MOD_IMM: case EBPF_OP_DIV64_IMM: case EBPF_OP_MOD64_IMM: if (inst.imm == 0) { *errmsg = ubpf_error("division by zero at PC %d", i); return false; } break; default: *errmsg = ubpf_error("unknown opcode 0x%02x at PC %d", inst.opcode, i); return false; } if (inst.src > 10) { *errmsg = ubpf_error("invalid source register at PC %d", i); return false; } if (inst.dst > 9 && !(store && inst.dst == 10)) { *errmsg = ubpf_error("invalid destination register at PC %d", i); return false; } } return true; } static bool bounds_check(void *addr, int size, const char *type, uint16_t cur_pc, void *mem, size_t mem_len, void *stack) { if (mem && (addr >= mem && (addr + size) <= (mem + mem_len))) { /* Context access */ return true; } else if (addr >= stack && (addr + size) <= (stack + STACK_SIZE)) { /* Stack access */ return true; } else { fprintf(stderr, "uBPF error: out of bounds memory %s at PC %u, addr %p, size %d\n", type, cur_pc, addr, size); fprintf(stderr, "mem %p/%zd stack %p/%d\n", mem, mem_len, stack, STACK_SIZE); return false; } } char * ubpf_error(const char *fmt, ...) { char *msg; va_list ap; va_start(ap, fmt); if (vasprintf(&msg, fmt, ap) < 0) { msg = NULL; } va_end(ap); return msg; }
/* * Copyright 2015 Big Switch Networks, Inc * * 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. */
path_encoding.mli
module type S = sig type t (** [to_path t postfix] returns the context path name for [t] postfixed with [postfix] *) val to_path : t -> string list -> string list (** [of_path path] parses [path] as a context path name for [t] *) val of_path : string list -> t option (** Directory levels of the path encoding of [t] *) val path_length : int end module type ENCODING = sig type t val to_bytes : t -> bytes val of_bytes_opt : bytes -> t option end (** Path encoding in hex: [/[0-9a-f]{2}+/] *) module Make_hex (H : ENCODING) : S with type t := H.t
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* Copyright (c) 2021 DaiLambda, Inc. <contact@dailambda.jp> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
commitment_storage.mli
val init: Raw_context.t -> Commitment_repr.t list -> Raw_context.t tzresult Lwt.t val get_opt: Raw_context.t -> Blinded_public_key_hash.t -> Tez_repr.t option tzresult Lwt.t val delete: Raw_context.t -> Blinded_public_key_hash.t -> Raw_context.t tzresult Lwt.t
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <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. *) (* *) (*****************************************************************************)
stack.h
#ifndef wasm_abi_stack_h #define wasm_abi_stack_h #include "asmjs/shared-constants.h" #include "ir/find_all.h" #include "ir/global-utils.h" #include "shared-constants.h" #include "wasm-builder.h" #include "wasm-emscripten.h" #include "wasm.h" namespace wasm { namespace ABI { enum { StackAlign = 16 }; inline Index stackAlign(Index size) { return (size + StackAlign - 1) & -StackAlign; } // Allocate some space on the stack, and assign it to a local. // The local will have the same constant value in all the function, so you can // just local.get it anywhere there. // // FIXME: This function assumes that the stack grows upward, per the convention // used by fastcomp. The stack grows downward when using the WASM backend. inline void getStackSpace(Index local, Function* func, Index size, Module& wasm) { auto* stackPointer = getStackPointerGlobal(wasm); if (!stackPointer) { Fatal() << "getStackSpace: failed to find the stack pointer"; } // align the size size = stackAlign(size); auto pointerType = !wasm.memories.empty() ? wasm.memories[0]->indexType : Type::i32; // TODO: find existing stack usage, and add on top of that - carefully Builder builder(wasm); auto* block = builder.makeBlock(); block->list.push_back(builder.makeLocalSet( local, builder.makeGlobalGet(stackPointer->name, pointerType))); // TODO: add stack max check Expression* added; if (pointerType == Type::i32) { // The stack goes downward in the LLVM wasm backend. added = builder.makeBinary(SubInt32, builder.makeLocalGet(local, pointerType), builder.makeConst(int32_t(size))); } else { WASM_UNREACHABLE("unhandled pointerType"); } block->list.push_back(builder.makeGlobalSet(stackPointer->name, added)); auto makeStackRestore = [&]() { return builder.makeGlobalSet(stackPointer->name, builder.makeLocalGet(local, pointerType)); }; // add stack restores to the returns FindAllPointers<Return> finder(func->body); for (auto** ptr : finder.list) { auto* ret = (*ptr)->cast<Return>(); if (ret->value && ret->value->type != Type::unreachable) { // handle the returned value auto* block = builder.makeBlock(); auto temp = builder.addVar(func, ret->value->type); block->list.push_back(builder.makeLocalSet(temp, ret->value)); block->list.push_back(makeStackRestore()); block->list.push_back( builder.makeReturn(builder.makeLocalGet(temp, ret->value->type))); block->finalize(); *ptr = block; } else { // restore, then return *ptr = builder.makeSequence(makeStackRestore(), ret); } } // add stack restores to the body if (func->body->type == Type::none) { block->list.push_back(func->body); block->list.push_back(makeStackRestore()); } else if (func->body->type == Type::unreachable) { block->list.push_back(func->body); // no need to restore the old stack value, we're gone anyhow } else { // save the return value auto temp = builder.addVar(func, func->getResults()); block->list.push_back(builder.makeLocalSet(temp, func->body)); block->list.push_back(makeStackRestore()); block->list.push_back(builder.makeLocalGet(temp, func->getResults())); } block->finalize(); func->body = block; } } // namespace ABI } // namespace wasm #endif // wasm_abi_stack_h
/* * Copyright 2017 WebAssembly Community Group participants * * 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. */