_id
stringlengths 64
64
| repository
stringlengths 6
84
| name
stringlengths 4
110
| content
stringlengths 0
248k
| license
null | download_url
stringlengths 89
454
| language
stringclasses 7
values | comments
stringlengths 0
74.6k
| code
stringlengths 0
248k
|
---|---|---|---|---|---|---|---|---|
cf57f1eecc3e612f4f43b6f430b8614739c9efe34213707dfe8ba020ce3c2c61 | easyuc/EasyUC | ecCommands.ml | A modification of src / ecCommands.ml of the EasyCrypt distribution
See " UC DSL " for changes
See "UC DSL" for changes
*)
(* -------------------------------------------------------------------- *)
open EcUtils
open EcLocation
open EcParsetree
module Sid = EcIdent.Sid
module Mx = EcPath.Mx
(* -------------------------------------------------------------------- *)
exception Restart
(* -------------------------------------------------------------------- *)
type pragma = {
pm_verbose : bool; (* true => display goal after each command *)
pm_g_prall : bool; (* true => display all open goals *)
pm_g_prpo : EcPrinting.prpo_display;
pm_check : [`Check | `WeakCheck | `Report];
}
let dpragma = {
pm_verbose = true ;
pm_g_prall = false ;
pm_g_prpo = EcPrinting.{ prpo_pr = false; prpo_po = false; };
pm_check = `Check;
}
module Pragma : sig
val get : unit -> pragma
val set : pragma -> unit
val upd : (pragma -> pragma) -> unit
end = struct
let pragma = ref dpragma
let notify () =
EcUserMessages.set_ppo
EcUserMessages.{ ppo_prpo = (!pragma).pm_g_prpo }
let () = notify ()
let get () = !pragma
let set x = pragma := x; notify ()
let upd f = set (f (get ()))
end
let pragma_verbose (b : bool) =
Pragma.upd (fun pragma -> { pragma with pm_verbose = b; })
let pragma_g_prall (b : bool) =
Pragma.upd (fun pragma -> { pragma with pm_g_prall = b; })
let pragma_g_pr_display (b : bool) =
Pragma.upd (fun pragma ->
{ pragma with pm_g_prpo =
EcPrinting.{ pragma.pm_g_prpo with prpo_pr = b; } })
let pragma_g_po_display (b : bool) =
Pragma.upd (fun pragma ->
{ pragma with pm_g_prpo =
EcPrinting.{ pragma.pm_g_prpo with prpo_po = b; } })
let pragma_check mode =
Pragma.upd (fun pragma -> { pragma with pm_check = mode; })
module Pragmas = struct
let silent = "silent"
let verbose = "verbose"
module Proofs = struct
let check = "Proofs:check"
let weak = "Proofs:weak"
let report = "Proofs:report"
end
module Goals = struct
let printall = "Goals:printall"
let printone = "Goals:printone"
end
module PrPo = struct
let prpo_pr_raw = "PrPo:pr:raw"
let prpo_pr_spl = "PrPo:pr:ands"
let prpo_po_raw = "PrPo:po:raw"
let prpo_po_spl = "PrPo:po:ands"
end
end
exception InvalidPragma of string
let apply_pragma (x : string) =
match x with
| x when x = Pragmas.silent -> pragma_verbose false
| x when x = Pragmas.verbose -> pragma_verbose true
| x when x = Pragmas.Proofs.check -> pragma_check `Check
| x when x = Pragmas.Proofs.weak -> pragma_check `WeakCheck
| x when x = Pragmas.Proofs.report -> pragma_check `Report
| x when x = Pragmas.Goals.printone -> pragma_g_prall false
| x when x = Pragmas.Goals.printall -> pragma_g_prall true
| x when x = Pragmas.PrPo.prpo_pr_raw -> pragma_g_pr_display false
| x when x = Pragmas.PrPo.prpo_pr_spl -> pragma_g_pr_display true
| x when x = Pragmas.PrPo.prpo_po_raw -> pragma_g_po_display false
| x when x = Pragmas.PrPo.prpo_po_spl -> pragma_g_po_display true
| x when x = Pragmas.Goals.printall -> pragma_g_prall true
| _ -> Printf.eprintf "%s\n%!" x; raise (InvalidPragma x)
(* -------------------------------------------------------------------- *)
module Loader : sig
type loader
type kind = EcLoader.kind
type idx_t = EcLoader.idx_t
type namespace = EcLoader.namespace
val create : unit -> loader
val forsys : loader -> loader
val dup : ?namespace:EcLoader.namespace -> loader -> loader
val namespace : loader -> EcLoader.namespace option
val addidir : ?namespace:namespace -> ?recursive:bool -> string -> loader -> unit
val aslist : loader -> ((namespace option * string) * idx_t) list
val locate : ?namespaces:namespace option list -> string ->
loader -> (namespace option * string * kind) option
val push : string -> loader -> unit
val pop : loader -> string option
val context : loader -> string list
val incontext : string -> loader -> bool
end = struct
type loader = {
(*---*) ld_core : EcLoader.ecloader;
mutable ld_stack : string list;
(*---*) ld_namespace : EcLoader.namespace option;
}
type kind = EcLoader.kind
type idx_t = EcLoader.idx_t
type namespace = EcLoader.namespace
module Path = BatPathGen.OfString
let norm p =
try Path.s (Path.normalize_in_tree (Path.p p))
with Path.Malformed_path -> p
let create () =
{ ld_core = EcLoader.create ();
ld_stack = [];
ld_namespace = None; }
let forsys (ld : loader) =
{ ld_core = EcLoader.forsys ld.ld_core;
ld_stack = ld.ld_stack;
ld_namespace = None; }
let dup ?namespace (ld : loader) =
{ ld_core = EcLoader.dup ld.ld_core;
ld_stack = ld.ld_stack;
ld_namespace =
match namespace with
| Some _ -> namespace
| None -> ld.ld_namespace; }
let namespace { ld_namespace = nm } = nm
let addidir ?namespace ?recursive (path : string) (ld : loader) =
EcLoader.addidir ?namespace ?recursive path ld.ld_core
let aslist (ld : loader) =
EcLoader.aslist ld.ld_core
let locate ?namespaces (path : string) (ld : loader) =
EcLoader.locate ?namespaces path ld.ld_core
let push (p : string) (ld : loader) =
ld.ld_stack <- norm p :: ld.ld_stack
let pop (ld : loader) =
match ld.ld_stack with
| [] -> None
| p :: tl -> ld.ld_stack <- tl; Some p
let context (ld : loader) =
ld.ld_stack
let incontext (p : string) (ld : loader) =
List.mem (norm p) ld.ld_stack
end
(* -------------------------------------------------------------------- *)
let process_search scope qs =
EcScope.Search.search scope qs
(* -------------------------------------------------------------------- *)
let process_locate scope x =
EcScope.Search.locate scope x
(* -------------------------------------------------------------------- *)
module HiPrinting = struct
let pr_glob fmt env pm =
let ppe = EcPrinting.PPEnv.ofenv env in
let (p, _) = EcTyping.trans_msymbol env pm in
let us = EcEnv.NormMp.mod_use env p in
Format.fprintf fmt "Globals [# = %d]:@."
(Sid.cardinal us.EcEnv.us_gl);
Sid.iter (fun id ->
Format.fprintf fmt " %s@." (EcIdent.name id))
us.EcEnv.us_gl;
Format.fprintf fmt "@.";
Format.fprintf fmt "Prog. variables [# = %d]:@."
(Mx.cardinal us.EcEnv.us_pv);
List.iter (fun (xp,_) ->
let pv = EcTypes.pv_glob xp in
let ty = EcEnv.Var.by_xpath xp env in
Format.fprintf fmt " @[%a : %a@]@."
(EcPrinting.pp_pv ppe) pv
(EcPrinting.pp_type ppe) ty)
(List.rev (Mx.bindings us.EcEnv.us_pv))
let pr_goal fmt scope n =
match EcScope.xgoal scope with
| None | Some { EcScope.puc_active = None} ->
EcScope.hierror "no active proof"
| Some { EcScope.puc_active = Some (puc, _) } -> begin
match puc.EcScope.puc_jdg with
| EcScope.PSNoCheck -> ()
| EcScope.PSCheck pf -> begin
let hds = EcCoreGoal.all_hd_opened pf in
let sz = List.length hds in
let ppe = EcPrinting.PPEnv.ofenv (EcScope.env scope) in
if n > sz then
EcScope.hierror "only %n goal(s) remaining" sz;
if n <= 0 then
EcScope.hierror "goal ID must be positive";
let penv = EcCoreGoal.proofenv_of_proof pf in
let goal = List.nth hds (n-1) in
let goal = EcCoreGoal.FApi.get_pregoal_by_id goal penv in
let goal = (EcEnv.LDecl.tohyps goal.EcCoreGoal.g_hyps,
goal.EcCoreGoal.g_concl) in
Format.fprintf fmt "Printing Goal %d\n\n%!" n;
EcPrinting.pp_goal ppe (Pragma.get ()).pm_g_prpo
fmt (goal, `One sz)
end
end
end
(* -------------------------------------------------------------------- *)
let process_pr fmt scope p =
let env = EcScope.env scope in
match p with
| Pr_ty qs -> EcPrinting.ObjectInfo.pr_ty fmt env (unloc qs)
| Pr_op qs -> EcPrinting.ObjectInfo.pr_op fmt env (unloc qs)
| Pr_pr qs -> EcPrinting.ObjectInfo.pr_op fmt env (unloc qs)
| Pr_th qs -> EcPrinting.ObjectInfo.pr_th fmt env (unloc qs)
| Pr_ax qs -> EcPrinting.ObjectInfo.pr_ax fmt env (unloc qs)
| Pr_sc qs -> EcPrinting.ObjectInfo.pr_sc fmt env (unloc qs)
| Pr_mod qs -> EcPrinting.ObjectInfo.pr_mod fmt env (unloc qs)
| Pr_mty qs -> EcPrinting.ObjectInfo.pr_mty fmt env (unloc qs)
| Pr_any qs -> EcPrinting.ObjectInfo.pr_any fmt env (unloc qs)
| Pr_db (`Rewrite qs) ->
EcPrinting.ObjectInfo.pr_rw fmt env (unloc qs)
| Pr_db (`Solve q) ->
EcPrinting.ObjectInfo.pr_at fmt env (unloc q)
| Pr_glob pm -> HiPrinting.pr_glob fmt env pm
| Pr_goal n -> HiPrinting.pr_goal fmt scope n
(* -------------------------------------------------------------------- *)
let check_opname_validity (scope : EcScope.scope) (x : string) =
if EcIo.is_binop x = `Invalid then
EcScope.notify scope `Warning
"operator `%s' cannot be used in prefix mode" x;
if EcIo.is_uniop x = `Invalid then
EcScope.notify scope `Warning
"operator `%s' cannot be used in infix mode" x
(* -------------------------------------------------------------------- *)
let process_print scope p =
process_pr Format.std_formatter scope p
(* -------------------------------------------------------------------- *)
exception Pragma of [`Reset | `Restart]
(* -------------------------------------------------------------------- *)
let rec process_type (scope : EcScope.scope) (tyd : ptydecl located) =
EcScope.check_state `InTop "type" scope;
let scope = EcScope.Ty.add scope tyd in
EcScope.notify scope `Info "added type: `%s'" (unloc tyd.pl_desc.pty_name);
scope
(* -------------------------------------------------------------------- *)
and process_types (scope : EcScope.scope) tyds =
List.fold_left process_type scope tyds
(* -------------------------------------------------------------------- *)
and process_typeclass (scope : EcScope.scope) (tcd : ptypeclass located) =
EcScope.check_state `InTop "type class" scope;
let scope = EcScope.Ty.add_class scope tcd in
EcScope.notify scope `Info "added type class: `%s'" (unloc tcd.pl_desc.ptc_name);
scope
(* -------------------------------------------------------------------- *)
and process_tycinst (scope : EcScope.scope) (tci : ptycinstance located) =
EcScope.check_state `InTop "type class instance" scope;
EcScope.Ty.add_instance scope (Pragma.get ()).pm_check tci
(* -------------------------------------------------------------------- *)
and process_module (scope : EcScope.scope) m =
EcScope.check_state `InTop "module" scope;
EcScope.Mod.add scope m
(* -------------------------------------------------------------------- *)
and process_interface (scope : EcScope.scope) intf =
EcScope.check_state `InTop "interface" scope;
EcScope.ModType.add scope intf
(* -------------------------------------------------------------------- *)
and process_operator (scope : EcScope.scope) (pop : poperator located) =
EcScope.check_state `InTop "operator" scope;
let op, axs, scope = EcScope.Op.add scope pop in
let ppe = EcPrinting.PPEnv.ofenv (EcScope.env scope) in
List.iter
(fun { pl_desc = name } ->
EcScope.notify scope `Info "added operator %s %a"
name (EcPrinting.pp_added_op ppe) op;
check_opname_validity scope name)
(pop.pl_desc.po_name :: pop.pl_desc.po_aliases);
List.iter (fun s -> EcScope.notify scope `Info "added axiom: `%s'" s) axs;
scope
(* -------------------------------------------------------------------- *)
and process_predicate (scope : EcScope.scope) (p : ppredicate located) =
EcScope.check_state `InTop "predicate" scope;
let op, scope = EcScope.Pred.add scope p in
let ppe = EcPrinting.PPEnv.ofenv (EcScope.env scope) in
EcScope.notify scope `Info "added predicate %s %a"
(unloc p.pl_desc.pp_name) (EcPrinting.pp_added_op ppe) op;
check_opname_validity scope (unloc p.pl_desc.pp_name);
scope
(* -------------------------------------------------------------------- *)
and process_notation (scope : EcScope.scope) (n : pnotation located) =
EcScope.check_state `InTop "notation" scope;
let scope = EcScope.Notations.add scope n in
EcScope.notify scope `Info "added notation: `%s'"
(unloc n.pl_desc.nt_name);
scope
(* -------------------------------------------------------------------- *)
and process_abbrev (scope : EcScope.scope) (a : pabbrev located) =
EcScope.check_state `InTop "abbreviation" scope;
let scope = EcScope.Notations.add_abbrev scope a in
EcScope.notify scope `Info "added abbrev.: `%s'"
(unloc a.pl_desc.ab_name);
scope
(* -------------------------------------------------------------------- *)
and process_axiom (scope : EcScope.scope) (ax : paxiom located) =
EcScope.check_state `InTop "axiom" scope;
(* TODO: A: aybe rename, as this now also adds schemata. *)
let (name, scope) = EcScope.Ax.add scope (Pragma.get ()).pm_check ax in
name |> EcUtils.oiter
(fun x ->
match (unloc ax).pa_kind with
| PAxiom _ -> EcScope.notify scope `Info "added axiom: `%s'" x
| PLemma _ -> EcScope.notify scope `Info "added lemma: `%s'" x
| PSchema -> EcScope.notify scope `Info "added schema: `%s'" x);
scope
(* -------------------------------------------------------------------- *)
and process_th_open (scope : EcScope.scope) (loca, abs, name) =
EcScope.check_state `InTop "theory" scope;
EcScope.Theory.enter scope (if abs then `Abstract else `Concrete) (unloc name) loca
(* -------------------------------------------------------------------- *)
and process_th_close (scope : EcScope.scope) (clears, name) =
let name = unloc name in
EcScope.check_state `InTop "theory closing" scope;
if (fst (EcScope.name scope)) <> name then
EcScope.hierror
"active theory has name `%s', not `%s'"
(fst (EcScope.name scope)) name;
snd (EcScope.Theory.exit ~clears scope)
(* -------------------------------------------------------------------- *)
and process_th_clear (scope : EcScope.scope) clears =
EcScope.check_state `InTop "theory clear" scope;
EcScope.Theory.add_clears clears scope
(* -------------------------------------------------------------------- *)
and process_th_require1 ld scope (nm, (sysname, thname), io) =
EcScope.check_state `InTop "theory require" scope;
let sysname, thname = (unloc sysname, omap unloc thname) in
let thname = odfl sysname thname in
let nm = omap (fun x -> `Named (unloc x)) nm in
let nm =
if is_none nm && is_some (Loader.namespace ld)
then [Loader.namespace ld; None]
else [nm] in
match Loader.locate ~namespaces:nm sysname ld with
| None ->
EcScope.hierror "cannot locate theory `%s'" sysname
| Some (fnm, filename, kind) ->
if Loader.incontext filename ld then
EcScope.hierror "circular requires involving `%s'" sysname;
let dirname = Filename.dirname filename in
let subld = Loader.dup ?namespace:fnm ld in
Loader.push filename subld;
Loader.addidir ?namespace:fnm dirname subld;
let name = EcScope.{
rqd_name = thname;
rqd_kind = kind;
rqd_namespace = fnm;
rqd_digest = Digest.file filename;
rqd_direct = List.is_empty (Loader.context ld);
} in
let loader iscope =
let i_pragma = Pragma.get () in
try_finally (fun () ->
let commands = EcIo.parseall (EcIo.from_file filename) in
let commands = List.fold_left (process_internal subld) iscope commands in
commands)
(fun () -> Pragma.set i_pragma)
in
let kind = match kind with `Ec -> `Concrete | `EcA -> `Abstract in
let scope = EcScope.Theory.require scope (name, kind) loader in
match io with
| None -> scope
| Some `Export -> EcScope.Theory.export scope ([], name.EcScope.rqd_name)
| Some `Import -> EcScope.Theory.import scope ([], name.EcScope.rqd_name)
(* -------------------------------------------------------------------- *)
and process_th_require ld scope (nm, xs, io) =
List.fold_left
(fun scope x -> process_th_require1 ld scope (nm, x, io))
scope xs
(* -------------------------------------------------------------------- *)
and process_th_import (scope : EcScope.scope) (names : pqsymbol list) =
EcScope.check_state `InTop "theory import" scope;
List.fold_left EcScope.Theory.import scope (List.map unloc names)
(* -------------------------------------------------------------------- *)
and process_th_export (scope : EcScope.scope) (names : pqsymbol list) =
EcScope.check_state `InTop "theory export" scope;
List.fold_left EcScope.Theory.export scope (List.map unloc names)
(* -------------------------------------------------------------------- *)
and process_th_clone (scope : EcScope.scope) thcl =
EcScope.check_state `InTop "theory cloning" scope;
EcScope.Cloning.clone scope (Pragma.get ()).pm_check thcl
(* -------------------------------------------------------------------- *)
and process_mod_import (scope : EcScope.scope) mods =
EcScope.check_state `InTop "module var import" scope;
List.fold_left EcScope.Mod.import scope mods
(* -------------------------------------------------------------------- *)
and process_sct_open (scope : EcScope.scope) name =
EcScope.check_state `InTop "section opening" scope;
EcScope.Section.enter scope name
(* -------------------------------------------------------------------- *)
and process_sct_close (scope : EcScope.scope) name =
EcScope.check_state `InTop "section closing" scope;
EcScope.Section.exit scope name
(* -------------------------------------------------------------------- *)
and process_tactics (scope : EcScope.scope) t =
let mode = (Pragma.get ()).pm_check in
match t with
| `Actual t -> snd (EcScope.Tactics.process scope mode t)
| `Proof pm -> EcScope.Tactics.proof scope mode pm.pm_strict
(* -------------------------------------------------------------------- *)
and process_save (scope : EcScope.scope) ed =
let (oname, scope) =
match unloc ed with
| `Qed -> EcScope.Ax.save scope
| `Admit -> EcScope.Ax.admit scope
| `Abort -> (None, EcScope.Ax.abort scope)
in
oname |> EcUtils.oiter
(fun x -> EcScope.notify scope `Info "added lemma: `%s'" x);
scope
(* -------------------------------------------------------------------- *)
and process_realize (scope : EcScope.scope) pr =
let mode = (Pragma.get ()).pm_check in
let (name, scope) = EcScope.Ax.realize scope mode pr in
name |> EcUtils.oiter
(fun x -> EcScope.notify scope `Info "added lemma: `%s'" x);
scope
(* -------------------------------------------------------------------- *)
(* UC DSL *)
we make processing the ` prover ` command do nothing , so why3 does n't
have to be configured in order for ucdsl to ec_require files that
use this command ( we are n't checking the proofs of EasyCrypt files )
have to be configured in order for ucdsl to ec_require files that
use this command (we aren't checking the proofs of EasyCrypt files) *)
and process_proverinfo scope _ = scope
(*
and process_proverinfo scope pi =
let scope = EcScope.Prover.process scope pi in
scope
*)
(* -------------------------------------------------------------------- *)
and process_pragma (scope : EcScope.scope) opt =
let pragma_check mode =
match EcScope.goal scope with
| Some { EcScope.puc_mode = Some false } ->
EcScope.hierror "pragma [Proofs:*] in non-strict proof script";
| _ -> pragma_check mode
in
match unloc opt with
| x when x = Pragmas.Proofs.weak -> pragma_check `WeakCheck
| x when x = Pragmas.Proofs.check -> pragma_check `Check
| x when x = Pragmas.Proofs.report -> pragma_check `Report
| "noop" -> ()
| "compact" -> Gc.compact ()
| "reset" -> raise (Pragma `Reset)
| "restart" -> raise (Pragma `Restart)
| x ->
try apply_pragma x
with InvalidPragma _ ->
EcScope.notify scope `Warning "unknown pragma: `%s'" x
(* -------------------------------------------------------------------- *)
and process_option (scope : EcScope.scope) (name, value) =
match value with
| `Bool value when EcLocation.unloc name = EcGState.old_mem_restr ->
let gs = EcEnv.gstate (EcScope.env scope) in
EcGState.setflag (unloc name) value gs; scope
| (`Int _) as value ->
let gs = EcEnv.gstate (EcScope.env scope) in
EcGState.setvalue (unloc name) value gs; scope
| `Bool value -> begin
try EcScope.Options.set scope (unloc name) value
with EcScope.UnknownFlag _ ->
EcScope.hierror "unknown option: %s" (unloc name)
end
(* -------------------------------------------------------------------- *)
and process_addrw scope (local, base, names) =
EcScope.Auto.add_rw scope ~local ~base names
(* -------------------------------------------------------------------- *)
and process_reduction scope name =
EcScope.Reduction.add_reduction scope name
(* -------------------------------------------------------------------- *)
and process_hint scope hint =
EcScope.Auto.add_hint scope hint
(* -------------------------------------------------------------------- *)
and process_dump_why3 scope filename =
EcScope.dump_why3 scope filename; scope
(* -------------------------------------------------------------------- *)
and process_dump scope (source, tc) =
let open EcCoreGoal in
let input, (p1, p2) = source.tcd_source in
let goals, scope =
let mode = (Pragma.get ()).pm_check in
EcScope.Tactics.process scope mode tc
in
let wrerror fname =
EcScope.notify scope `Warning "cannot write `%s'" fname in
let tactic =
try File.read_from_file ~offset:p1 ~length:(p2-p1) input
with Invalid_argument _ -> "(* failed to read back script *)" in
let tactic = Printf.sprintf "%s.\n" (String.strip tactic) in
let ecfname = Printf.sprintf "%s.ec" source.tcd_output in
(try File.write_to_file ~output:ecfname tactic
with Invalid_argument _ -> wrerror ecfname);
goals |> oiter (fun (penv, (hd, hds)) ->
let goals =
List.map
(fun hd -> EcCoreGoal.FApi.get_pregoal_by_id hd penv)
(hd :: hds) in
List.iteri (fun i { g_hyps = hyps; g_concl = concl; } ->
let ecfname = Printf.sprintf "%s.%d.ec" source.tcd_output i in
try
let output = open_out_bin ecfname in
try_finally
(fun () ->
let fbuf = Format.formatter_of_out_channel output in
let ppe = EcPrinting.PPEnv.ofenv (EcEnv.LDecl.toenv hyps) in
source.tcd_width |> oiter (Format.pp_set_margin fbuf);
Format.fprintf fbuf "%a@?"
(EcPrinting.pp_goal ppe (Pragma.get ()).pm_g_prpo)
((EcEnv.LDecl.tohyps hyps, concl), `One (-1)))
(fun () -> close_out output)
with Sys_error _ -> wrerror ecfname)
goals);
scope
(* -------------------------------------------------------------------- *)
and process (ld : Loader.loader) (scope : EcScope.scope) g =
let loc = g.pl_loc in
let scope =
match
match g.pl_desc with
| Gtype t -> `Fct (fun scope -> process_types scope (List.map (mk_loc loc) t))
| Gtypeclass t -> `Fct (fun scope -> process_typeclass scope (mk_loc loc t))
| Gtycinstance t -> `Fct (fun scope -> process_tycinst scope (mk_loc loc t))
| Gmodule m -> `Fct (fun scope -> process_module scope m)
| Ginterface i -> `Fct (fun scope -> process_interface scope i)
| Goperator o -> `Fct (fun scope -> process_operator scope (mk_loc loc o))
| Gpredicate p -> `Fct (fun scope -> process_predicate scope (mk_loc loc p))
| Gnotation n -> `Fct (fun scope -> process_notation scope (mk_loc loc n))
| Gabbrev n -> `Fct (fun scope -> process_abbrev scope (mk_loc loc n))
| Gaxiom a -> `Fct (fun scope -> process_axiom scope (mk_loc loc a))
| GthOpen name -> `Fct (fun scope -> process_th_open scope name)
| GthClose info -> `Fct (fun scope -> process_th_close scope info)
| GthClear info -> `Fct (fun scope -> process_th_clear scope info)
| GthRequire name -> `Fct (fun scope -> process_th_require ld scope name)
| GthImport name -> `Fct (fun scope -> process_th_import scope name)
| GthExport name -> `Fct (fun scope -> process_th_export scope name)
| GthClone thcl -> `Fct (fun scope -> process_th_clone scope thcl)
| GModImport mods -> `Fct (fun scope -> process_mod_import scope mods)
| GsctOpen name -> `Fct (fun scope -> process_sct_open scope name)
| GsctClose name -> `Fct (fun scope -> process_sct_close scope name)
| Gprint p -> `Fct (fun scope -> process_print scope p; scope)
| Gsearch qs -> `Fct (fun scope -> process_search scope qs; scope)
| Glocate x -> `Fct (fun scope -> process_locate scope x; scope)
| Gtactics t -> `Fct (fun scope -> process_tactics scope t)
| Gtcdump info -> `Fct (fun scope -> process_dump scope info)
| Grealize p -> `Fct (fun scope -> process_realize scope p)
| Gprover_info pi -> `Fct (fun scope -> process_proverinfo scope pi)
| Gsave ed -> `Fct (fun scope -> process_save scope ed)
| Gpragma opt -> `State (fun scope -> process_pragma scope opt)
| Goption opt -> `Fct (fun scope -> process_option scope opt)
| Gaddrw hint -> `Fct (fun scope -> process_addrw scope hint)
| Greduction red -> `Fct (fun scope -> process_reduction scope red)
| Ghint hint -> `Fct (fun scope -> process_hint scope hint)
| GdumpWhy3 file -> `Fct (fun scope -> process_dump_why3 scope file)
with
| `Fct f -> Some (f scope)
| `State f -> f scope; None
in
scope
(* -------------------------------------------------------------------- *)
and process_internal ld scope g =
try odfl scope (process ld scope g.gl_action)
with e -> raise (EcScope.toperror_of_exn ~gloc:(loc g.gl_action) e)
(* -------------------------------------------------------------------- *)
let loader = Loader.create ()
let addidir ?namespace ?recursive (idir : string) =
Loader.addidir ?namespace ?recursive idir loader
let loadpath () =
List.map fst (Loader.aslist loader)
(* -------------------------------------------------------------------- *)
type checkmode = {
cm_checkall : bool;
cm_timeout : int;
cm_cpufactor : int;
cm_nprovers : int;
cm_provers : string list option;
cm_profile : bool;
cm_iterate : bool;
}
let initial ~checkmode ~boot =
let checkall = checkmode.cm_checkall in
let profile = checkmode.cm_profile in
let poptions = { EcScope.Prover.empty_options with
EcScope.Prover.po_timeout = Some checkmode.cm_timeout;
EcScope.Prover.po_cpufactor = Some checkmode.cm_cpufactor;
EcScope.Prover.po_nprovers = Some checkmode.cm_nprovers;
EcScope.Prover.po_provers = (checkmode.cm_provers, []);
EcScope.Prover.pl_iterate = Some (checkmode.cm_iterate);
} in
let perv = (None, (mk_loc _dummy EcCoreLib.i_Pervasive, None), Some `Export) in
let tactics = (None, (mk_loc _dummy "Tactics", None), Some `Export) in
let prelude = (None, (mk_loc _dummy "Logic", None), Some `Export) in
let loader = Loader.forsys loader in
let gstate = EcGState.from_flags [("profile", profile)] in
let scope = EcScope.empty gstate in
let scope = process_th_require1 loader scope perv in
let scope = if boot then scope else
List.fold_left (process_th_require1 loader)
scope [tactics; prelude] in
let scope = EcScope.Prover.set_default scope poptions in
let scope = if checkall then EcScope.Prover.full_check scope else scope in
EcScope.freeze scope
(* -------------------------------------------------------------------- *)
type context = {
ct_level : int;
ct_current : EcScope.scope;
ct_root : EcScope.scope;
ct_stack : (EcScope.scope list) option;
}
let context = ref (None : context option)
let rootctxt ?(undo = true) (scope : EcScope.scope) =
{ ct_level = 0;
ct_current = scope;
ct_root = scope;
ct_stack = if undo then Some [] else None; }
(* -------------------------------------------------------------------- *)
let pop_context context =
match context.ct_stack with
| None -> EcScope.hierror "undo stack disabled"
| Some stack ->
assert (not (List.is_empty stack));
{ ct_level = context.ct_level - 1;
ct_root = context.ct_root;
ct_current = List.hd stack;
ct_stack = Some (List.tl stack); }
(* -------------------------------------------------------------------- *)
let push_context scope context =
{ ct_level = context.ct_level + 1;
ct_root = context.ct_root;
ct_current = scope;
ct_stack = context.ct_stack
|> omap (fun st -> context.ct_current :: st); }
(* -------------------------------------------------------------------- *)
let initialize ~restart ~undo ~boot ~checkmode =
assert (restart || EcUtils.is_none !context);
if restart then Pragma.set dpragma;
context := Some (rootctxt ~undo (initial ~checkmode ~boot))
(* -------------------------------------------------------------------- *)
type notifier = EcGState.loglevel -> string Lazy.t -> unit
let addnotifier (notifier : notifier) =
assert (EcUtils.is_some !context);
let gstate = EcScope.gstate (oget !context).ct_root in
ignore (EcGState.add_notifier notifier gstate)
(* -------------------------------------------------------------------- *)
let current () =
(oget !context).ct_current
(* -------------------------------------------------------------------- *)
let uuid () : int =
(oget !context).ct_level
(* -------------------------------------------------------------------- *)
let mode () : string =
match (Pragma.get ()).pm_check with
| `Check -> "check"
| `WeakCheck -> "weakcheck"
| `Report -> "report"
(* -------------------------------------------------------------------- *)
let undo (olduuid : int) =
if olduuid < (uuid ()) then
for _ = (uuid ()) - 1 downto olduuid do
context := Some (pop_context (oget !context))
done
(* -------------------------------------------------------------------- *)
let reset () =
context := Some (rootctxt (oget !context).ct_root)
(* -------------------------------------------------------------------- *)
let process ?(timed = false) ?(break = false) (g : global_action located) : float option =
ignore break;
let current = oget !context in
let scope = current.ct_current in
try
let (tdelta, oscope) = EcUtils.timed (process loader scope) g in
oscope |> oiter (fun scope -> context := Some (push_context scope current));
if timed then
EcScope.notify scope `Info "time: %f" tdelta;
Some tdelta
with
| Pragma `Reset -> reset (); None
| Pragma `Restart -> raise Restart
(* -------------------------------------------------------------------- *)
let check_eco =
EcEco.check_eco (fun name -> Loader.locate name loader)
(* -------------------------------------------------------------------- *)
module S = EcScope
module L = EcBaseLogic
let pp_current_goal ?(all = false) stream =
let scope = current () in
match S.xgoal scope with
| None -> ()
| Some { S.puc_active = None; S.puc_cont = ct } ->
Format.fprintf stream "Remaining lemmas to prove:@\n%!";
List.iter
(fun ((_, ax), p, env) ->
let ppe = EcPrinting.PPEnv.ofenv (EcSection.env env)in
Format.fprintf stream " %s: %a@\n%!"
(EcPath.tostring p)
(EcPrinting.pp_form ppe) ax.EcDecl.ax_spec)
(fst ct)
| Some { S.puc_active = Some (puc, _) } -> begin
match puc.S.puc_jdg with
| S.PSNoCheck -> ()
| S.PSCheck pf -> begin
let ppe = EcPrinting.PPEnv.ofenv (S.env scope) in
match EcCoreGoal.opened pf with
| None -> Format.fprintf stream "No more goals@\n%!"
| Some (n, g) ->
let get_hc { EcCoreGoal.g_hyps; EcCoreGoal.g_concl } =
(EcEnv.LDecl.tohyps g_hyps, g_concl)
in
if all then
let subgoals = EcCoreGoal.all_opened pf in
let subgoals = odfl [] (List.otail subgoals) in
let subgoals = List.map get_hc subgoals in
EcPrinting.pp_goal ppe (Pragma.get ()).pm_g_prpo
stream (get_hc g, `All subgoals)
else
EcPrinting.pp_goal ppe (Pragma.get ()).pm_g_prpo
stream (get_hc g, `One n)
end
end
let pp_maybe_current_goal stream =
match (Pragma.get ()).pm_verbose with
| true -> pp_current_goal ~all:(Pragma.get ()).pm_g_prall stream
| false -> ()
UC DSL interface
let checkmode = {
cm_checkall = false;
cm_timeout = 0;
cm_cpufactor = 1;
cm_nprovers = 0;
cm_provers = None;
cm_profile = false;
cm_iterate = false;
}
let ucdsl_context : EcScope.scope list ref = ref []
let ucdsl_init () =
let scope = initial ~checkmode:checkmode ~boot:false in
ucdsl_context := [scope]
let ucdsl_addnotifier (notifier : notifier) =
assert (not (List.is_empty (! ucdsl_context)));
let gstate = EcScope.gstate (List.hd (! ucdsl_context)) in
ignore (EcGState.add_notifier notifier gstate)
let ucdsl_current () =
assert (not (List.is_empty (! ucdsl_context)));
List.hd (! ucdsl_context)
let ucdsl_update scope =
assert (not (List.is_empty (! ucdsl_context)));
let rest = List.tl (! ucdsl_context) in
ucdsl_context := scope :: rest
let ucdsl_require threq =
assert (not (List.is_empty (! ucdsl_context)));
let top_sc = List.hd (! ucdsl_context) in
let rest = List.tl (! ucdsl_context) in
let new_sc = process_th_require1 loader top_sc threq in
ucdsl_context := new_sc :: rest
let ucdsl_new () =
assert (not (List.is_empty (! ucdsl_context)));
let new_sc = EcScope.for_loading (List.hd (! ucdsl_context)) in
ucdsl_context := new_sc :: ! ucdsl_context
let ucdsl_end () =
assert (List.length (! ucdsl_context) >= 2);
let top_sc = List.hd (! ucdsl_context) in
let prev_sc = List.hd (List.tl (! ucdsl_context)) in
let rest = List.drop 2 (! ucdsl_context) in
let new_sc = EcScope.Theory.update_with_required prev_sc top_sc in
ucdsl_context := new_sc :: rest
| null | https://raw.githubusercontent.com/easyuc/EasyUC/0ee14ef8b024a8e7acde1035d06afecbdcaec990/uc-dsl/ucdsl-proj/src/ecCommands.ml | ocaml | --------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
true => display goal after each command
true => display all open goals
--------------------------------------------------------------------
---
---
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
TODO: A: aybe rename, as this now also adds schemata.
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
UC DSL
and process_proverinfo scope pi =
let scope = EcScope.Prover.process scope pi in
scope
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
-------------------------------------------------------------------- | A modification of src / ecCommands.ml of the EasyCrypt distribution
See " UC DSL " for changes
See "UC DSL" for changes
*)
open EcUtils
open EcLocation
open EcParsetree
module Sid = EcIdent.Sid
module Mx = EcPath.Mx
exception Restart
type pragma = {
pm_g_prpo : EcPrinting.prpo_display;
pm_check : [`Check | `WeakCheck | `Report];
}
let dpragma = {
pm_verbose = true ;
pm_g_prall = false ;
pm_g_prpo = EcPrinting.{ prpo_pr = false; prpo_po = false; };
pm_check = `Check;
}
module Pragma : sig
val get : unit -> pragma
val set : pragma -> unit
val upd : (pragma -> pragma) -> unit
end = struct
let pragma = ref dpragma
let notify () =
EcUserMessages.set_ppo
EcUserMessages.{ ppo_prpo = (!pragma).pm_g_prpo }
let () = notify ()
let get () = !pragma
let set x = pragma := x; notify ()
let upd f = set (f (get ()))
end
let pragma_verbose (b : bool) =
Pragma.upd (fun pragma -> { pragma with pm_verbose = b; })
let pragma_g_prall (b : bool) =
Pragma.upd (fun pragma -> { pragma with pm_g_prall = b; })
let pragma_g_pr_display (b : bool) =
Pragma.upd (fun pragma ->
{ pragma with pm_g_prpo =
EcPrinting.{ pragma.pm_g_prpo with prpo_pr = b; } })
let pragma_g_po_display (b : bool) =
Pragma.upd (fun pragma ->
{ pragma with pm_g_prpo =
EcPrinting.{ pragma.pm_g_prpo with prpo_po = b; } })
let pragma_check mode =
Pragma.upd (fun pragma -> { pragma with pm_check = mode; })
module Pragmas = struct
let silent = "silent"
let verbose = "verbose"
module Proofs = struct
let check = "Proofs:check"
let weak = "Proofs:weak"
let report = "Proofs:report"
end
module Goals = struct
let printall = "Goals:printall"
let printone = "Goals:printone"
end
module PrPo = struct
let prpo_pr_raw = "PrPo:pr:raw"
let prpo_pr_spl = "PrPo:pr:ands"
let prpo_po_raw = "PrPo:po:raw"
let prpo_po_spl = "PrPo:po:ands"
end
end
exception InvalidPragma of string
let apply_pragma (x : string) =
match x with
| x when x = Pragmas.silent -> pragma_verbose false
| x when x = Pragmas.verbose -> pragma_verbose true
| x when x = Pragmas.Proofs.check -> pragma_check `Check
| x when x = Pragmas.Proofs.weak -> pragma_check `WeakCheck
| x when x = Pragmas.Proofs.report -> pragma_check `Report
| x when x = Pragmas.Goals.printone -> pragma_g_prall false
| x when x = Pragmas.Goals.printall -> pragma_g_prall true
| x when x = Pragmas.PrPo.prpo_pr_raw -> pragma_g_pr_display false
| x when x = Pragmas.PrPo.prpo_pr_spl -> pragma_g_pr_display true
| x when x = Pragmas.PrPo.prpo_po_raw -> pragma_g_po_display false
| x when x = Pragmas.PrPo.prpo_po_spl -> pragma_g_po_display true
| x when x = Pragmas.Goals.printall -> pragma_g_prall true
| _ -> Printf.eprintf "%s\n%!" x; raise (InvalidPragma x)
module Loader : sig
type loader
type kind = EcLoader.kind
type idx_t = EcLoader.idx_t
type namespace = EcLoader.namespace
val create : unit -> loader
val forsys : loader -> loader
val dup : ?namespace:EcLoader.namespace -> loader -> loader
val namespace : loader -> EcLoader.namespace option
val addidir : ?namespace:namespace -> ?recursive:bool -> string -> loader -> unit
val aslist : loader -> ((namespace option * string) * idx_t) list
val locate : ?namespaces:namespace option list -> string ->
loader -> (namespace option * string * kind) option
val push : string -> loader -> unit
val pop : loader -> string option
val context : loader -> string list
val incontext : string -> loader -> bool
end = struct
type loader = {
mutable ld_stack : string list;
}
type kind = EcLoader.kind
type idx_t = EcLoader.idx_t
type namespace = EcLoader.namespace
module Path = BatPathGen.OfString
let norm p =
try Path.s (Path.normalize_in_tree (Path.p p))
with Path.Malformed_path -> p
let create () =
{ ld_core = EcLoader.create ();
ld_stack = [];
ld_namespace = None; }
let forsys (ld : loader) =
{ ld_core = EcLoader.forsys ld.ld_core;
ld_stack = ld.ld_stack;
ld_namespace = None; }
let dup ?namespace (ld : loader) =
{ ld_core = EcLoader.dup ld.ld_core;
ld_stack = ld.ld_stack;
ld_namespace =
match namespace with
| Some _ -> namespace
| None -> ld.ld_namespace; }
let namespace { ld_namespace = nm } = nm
let addidir ?namespace ?recursive (path : string) (ld : loader) =
EcLoader.addidir ?namespace ?recursive path ld.ld_core
let aslist (ld : loader) =
EcLoader.aslist ld.ld_core
let locate ?namespaces (path : string) (ld : loader) =
EcLoader.locate ?namespaces path ld.ld_core
let push (p : string) (ld : loader) =
ld.ld_stack <- norm p :: ld.ld_stack
let pop (ld : loader) =
match ld.ld_stack with
| [] -> None
| p :: tl -> ld.ld_stack <- tl; Some p
let context (ld : loader) =
ld.ld_stack
let incontext (p : string) (ld : loader) =
List.mem (norm p) ld.ld_stack
end
let process_search scope qs =
EcScope.Search.search scope qs
let process_locate scope x =
EcScope.Search.locate scope x
module HiPrinting = struct
let pr_glob fmt env pm =
let ppe = EcPrinting.PPEnv.ofenv env in
let (p, _) = EcTyping.trans_msymbol env pm in
let us = EcEnv.NormMp.mod_use env p in
Format.fprintf fmt "Globals [# = %d]:@."
(Sid.cardinal us.EcEnv.us_gl);
Sid.iter (fun id ->
Format.fprintf fmt " %s@." (EcIdent.name id))
us.EcEnv.us_gl;
Format.fprintf fmt "@.";
Format.fprintf fmt "Prog. variables [# = %d]:@."
(Mx.cardinal us.EcEnv.us_pv);
List.iter (fun (xp,_) ->
let pv = EcTypes.pv_glob xp in
let ty = EcEnv.Var.by_xpath xp env in
Format.fprintf fmt " @[%a : %a@]@."
(EcPrinting.pp_pv ppe) pv
(EcPrinting.pp_type ppe) ty)
(List.rev (Mx.bindings us.EcEnv.us_pv))
let pr_goal fmt scope n =
match EcScope.xgoal scope with
| None | Some { EcScope.puc_active = None} ->
EcScope.hierror "no active proof"
| Some { EcScope.puc_active = Some (puc, _) } -> begin
match puc.EcScope.puc_jdg with
| EcScope.PSNoCheck -> ()
| EcScope.PSCheck pf -> begin
let hds = EcCoreGoal.all_hd_opened pf in
let sz = List.length hds in
let ppe = EcPrinting.PPEnv.ofenv (EcScope.env scope) in
if n > sz then
EcScope.hierror "only %n goal(s) remaining" sz;
if n <= 0 then
EcScope.hierror "goal ID must be positive";
let penv = EcCoreGoal.proofenv_of_proof pf in
let goal = List.nth hds (n-1) in
let goal = EcCoreGoal.FApi.get_pregoal_by_id goal penv in
let goal = (EcEnv.LDecl.tohyps goal.EcCoreGoal.g_hyps,
goal.EcCoreGoal.g_concl) in
Format.fprintf fmt "Printing Goal %d\n\n%!" n;
EcPrinting.pp_goal ppe (Pragma.get ()).pm_g_prpo
fmt (goal, `One sz)
end
end
end
let process_pr fmt scope p =
let env = EcScope.env scope in
match p with
| Pr_ty qs -> EcPrinting.ObjectInfo.pr_ty fmt env (unloc qs)
| Pr_op qs -> EcPrinting.ObjectInfo.pr_op fmt env (unloc qs)
| Pr_pr qs -> EcPrinting.ObjectInfo.pr_op fmt env (unloc qs)
| Pr_th qs -> EcPrinting.ObjectInfo.pr_th fmt env (unloc qs)
| Pr_ax qs -> EcPrinting.ObjectInfo.pr_ax fmt env (unloc qs)
| Pr_sc qs -> EcPrinting.ObjectInfo.pr_sc fmt env (unloc qs)
| Pr_mod qs -> EcPrinting.ObjectInfo.pr_mod fmt env (unloc qs)
| Pr_mty qs -> EcPrinting.ObjectInfo.pr_mty fmt env (unloc qs)
| Pr_any qs -> EcPrinting.ObjectInfo.pr_any fmt env (unloc qs)
| Pr_db (`Rewrite qs) ->
EcPrinting.ObjectInfo.pr_rw fmt env (unloc qs)
| Pr_db (`Solve q) ->
EcPrinting.ObjectInfo.pr_at fmt env (unloc q)
| Pr_glob pm -> HiPrinting.pr_glob fmt env pm
| Pr_goal n -> HiPrinting.pr_goal fmt scope n
let check_opname_validity (scope : EcScope.scope) (x : string) =
if EcIo.is_binop x = `Invalid then
EcScope.notify scope `Warning
"operator `%s' cannot be used in prefix mode" x;
if EcIo.is_uniop x = `Invalid then
EcScope.notify scope `Warning
"operator `%s' cannot be used in infix mode" x
let process_print scope p =
process_pr Format.std_formatter scope p
exception Pragma of [`Reset | `Restart]
let rec process_type (scope : EcScope.scope) (tyd : ptydecl located) =
EcScope.check_state `InTop "type" scope;
let scope = EcScope.Ty.add scope tyd in
EcScope.notify scope `Info "added type: `%s'" (unloc tyd.pl_desc.pty_name);
scope
and process_types (scope : EcScope.scope) tyds =
List.fold_left process_type scope tyds
and process_typeclass (scope : EcScope.scope) (tcd : ptypeclass located) =
EcScope.check_state `InTop "type class" scope;
let scope = EcScope.Ty.add_class scope tcd in
EcScope.notify scope `Info "added type class: `%s'" (unloc tcd.pl_desc.ptc_name);
scope
and process_tycinst (scope : EcScope.scope) (tci : ptycinstance located) =
EcScope.check_state `InTop "type class instance" scope;
EcScope.Ty.add_instance scope (Pragma.get ()).pm_check tci
and process_module (scope : EcScope.scope) m =
EcScope.check_state `InTop "module" scope;
EcScope.Mod.add scope m
and process_interface (scope : EcScope.scope) intf =
EcScope.check_state `InTop "interface" scope;
EcScope.ModType.add scope intf
and process_operator (scope : EcScope.scope) (pop : poperator located) =
EcScope.check_state `InTop "operator" scope;
let op, axs, scope = EcScope.Op.add scope pop in
let ppe = EcPrinting.PPEnv.ofenv (EcScope.env scope) in
List.iter
(fun { pl_desc = name } ->
EcScope.notify scope `Info "added operator %s %a"
name (EcPrinting.pp_added_op ppe) op;
check_opname_validity scope name)
(pop.pl_desc.po_name :: pop.pl_desc.po_aliases);
List.iter (fun s -> EcScope.notify scope `Info "added axiom: `%s'" s) axs;
scope
and process_predicate (scope : EcScope.scope) (p : ppredicate located) =
EcScope.check_state `InTop "predicate" scope;
let op, scope = EcScope.Pred.add scope p in
let ppe = EcPrinting.PPEnv.ofenv (EcScope.env scope) in
EcScope.notify scope `Info "added predicate %s %a"
(unloc p.pl_desc.pp_name) (EcPrinting.pp_added_op ppe) op;
check_opname_validity scope (unloc p.pl_desc.pp_name);
scope
and process_notation (scope : EcScope.scope) (n : pnotation located) =
EcScope.check_state `InTop "notation" scope;
let scope = EcScope.Notations.add scope n in
EcScope.notify scope `Info "added notation: `%s'"
(unloc n.pl_desc.nt_name);
scope
and process_abbrev (scope : EcScope.scope) (a : pabbrev located) =
EcScope.check_state `InTop "abbreviation" scope;
let scope = EcScope.Notations.add_abbrev scope a in
EcScope.notify scope `Info "added abbrev.: `%s'"
(unloc a.pl_desc.ab_name);
scope
and process_axiom (scope : EcScope.scope) (ax : paxiom located) =
EcScope.check_state `InTop "axiom" scope;
let (name, scope) = EcScope.Ax.add scope (Pragma.get ()).pm_check ax in
name |> EcUtils.oiter
(fun x ->
match (unloc ax).pa_kind with
| PAxiom _ -> EcScope.notify scope `Info "added axiom: `%s'" x
| PLemma _ -> EcScope.notify scope `Info "added lemma: `%s'" x
| PSchema -> EcScope.notify scope `Info "added schema: `%s'" x);
scope
and process_th_open (scope : EcScope.scope) (loca, abs, name) =
EcScope.check_state `InTop "theory" scope;
EcScope.Theory.enter scope (if abs then `Abstract else `Concrete) (unloc name) loca
and process_th_close (scope : EcScope.scope) (clears, name) =
let name = unloc name in
EcScope.check_state `InTop "theory closing" scope;
if (fst (EcScope.name scope)) <> name then
EcScope.hierror
"active theory has name `%s', not `%s'"
(fst (EcScope.name scope)) name;
snd (EcScope.Theory.exit ~clears scope)
and process_th_clear (scope : EcScope.scope) clears =
EcScope.check_state `InTop "theory clear" scope;
EcScope.Theory.add_clears clears scope
and process_th_require1 ld scope (nm, (sysname, thname), io) =
EcScope.check_state `InTop "theory require" scope;
let sysname, thname = (unloc sysname, omap unloc thname) in
let thname = odfl sysname thname in
let nm = omap (fun x -> `Named (unloc x)) nm in
let nm =
if is_none nm && is_some (Loader.namespace ld)
then [Loader.namespace ld; None]
else [nm] in
match Loader.locate ~namespaces:nm sysname ld with
| None ->
EcScope.hierror "cannot locate theory `%s'" sysname
| Some (fnm, filename, kind) ->
if Loader.incontext filename ld then
EcScope.hierror "circular requires involving `%s'" sysname;
let dirname = Filename.dirname filename in
let subld = Loader.dup ?namespace:fnm ld in
Loader.push filename subld;
Loader.addidir ?namespace:fnm dirname subld;
let name = EcScope.{
rqd_name = thname;
rqd_kind = kind;
rqd_namespace = fnm;
rqd_digest = Digest.file filename;
rqd_direct = List.is_empty (Loader.context ld);
} in
let loader iscope =
let i_pragma = Pragma.get () in
try_finally (fun () ->
let commands = EcIo.parseall (EcIo.from_file filename) in
let commands = List.fold_left (process_internal subld) iscope commands in
commands)
(fun () -> Pragma.set i_pragma)
in
let kind = match kind with `Ec -> `Concrete | `EcA -> `Abstract in
let scope = EcScope.Theory.require scope (name, kind) loader in
match io with
| None -> scope
| Some `Export -> EcScope.Theory.export scope ([], name.EcScope.rqd_name)
| Some `Import -> EcScope.Theory.import scope ([], name.EcScope.rqd_name)
and process_th_require ld scope (nm, xs, io) =
List.fold_left
(fun scope x -> process_th_require1 ld scope (nm, x, io))
scope xs
and process_th_import (scope : EcScope.scope) (names : pqsymbol list) =
EcScope.check_state `InTop "theory import" scope;
List.fold_left EcScope.Theory.import scope (List.map unloc names)
and process_th_export (scope : EcScope.scope) (names : pqsymbol list) =
EcScope.check_state `InTop "theory export" scope;
List.fold_left EcScope.Theory.export scope (List.map unloc names)
and process_th_clone (scope : EcScope.scope) thcl =
EcScope.check_state `InTop "theory cloning" scope;
EcScope.Cloning.clone scope (Pragma.get ()).pm_check thcl
and process_mod_import (scope : EcScope.scope) mods =
EcScope.check_state `InTop "module var import" scope;
List.fold_left EcScope.Mod.import scope mods
and process_sct_open (scope : EcScope.scope) name =
EcScope.check_state `InTop "section opening" scope;
EcScope.Section.enter scope name
and process_sct_close (scope : EcScope.scope) name =
EcScope.check_state `InTop "section closing" scope;
EcScope.Section.exit scope name
and process_tactics (scope : EcScope.scope) t =
let mode = (Pragma.get ()).pm_check in
match t with
| `Actual t -> snd (EcScope.Tactics.process scope mode t)
| `Proof pm -> EcScope.Tactics.proof scope mode pm.pm_strict
and process_save (scope : EcScope.scope) ed =
let (oname, scope) =
match unloc ed with
| `Qed -> EcScope.Ax.save scope
| `Admit -> EcScope.Ax.admit scope
| `Abort -> (None, EcScope.Ax.abort scope)
in
oname |> EcUtils.oiter
(fun x -> EcScope.notify scope `Info "added lemma: `%s'" x);
scope
and process_realize (scope : EcScope.scope) pr =
let mode = (Pragma.get ()).pm_check in
let (name, scope) = EcScope.Ax.realize scope mode pr in
name |> EcUtils.oiter
(fun x -> EcScope.notify scope `Info "added lemma: `%s'" x);
scope
we make processing the ` prover ` command do nothing , so why3 does n't
have to be configured in order for ucdsl to ec_require files that
use this command ( we are n't checking the proofs of EasyCrypt files )
have to be configured in order for ucdsl to ec_require files that
use this command (we aren't checking the proofs of EasyCrypt files) *)
and process_proverinfo scope _ = scope
and process_pragma (scope : EcScope.scope) opt =
let pragma_check mode =
match EcScope.goal scope with
| Some { EcScope.puc_mode = Some false } ->
EcScope.hierror "pragma [Proofs:*] in non-strict proof script";
| _ -> pragma_check mode
in
match unloc opt with
| x when x = Pragmas.Proofs.weak -> pragma_check `WeakCheck
| x when x = Pragmas.Proofs.check -> pragma_check `Check
| x when x = Pragmas.Proofs.report -> pragma_check `Report
| "noop" -> ()
| "compact" -> Gc.compact ()
| "reset" -> raise (Pragma `Reset)
| "restart" -> raise (Pragma `Restart)
| x ->
try apply_pragma x
with InvalidPragma _ ->
EcScope.notify scope `Warning "unknown pragma: `%s'" x
and process_option (scope : EcScope.scope) (name, value) =
match value with
| `Bool value when EcLocation.unloc name = EcGState.old_mem_restr ->
let gs = EcEnv.gstate (EcScope.env scope) in
EcGState.setflag (unloc name) value gs; scope
| (`Int _) as value ->
let gs = EcEnv.gstate (EcScope.env scope) in
EcGState.setvalue (unloc name) value gs; scope
| `Bool value -> begin
try EcScope.Options.set scope (unloc name) value
with EcScope.UnknownFlag _ ->
EcScope.hierror "unknown option: %s" (unloc name)
end
and process_addrw scope (local, base, names) =
EcScope.Auto.add_rw scope ~local ~base names
and process_reduction scope name =
EcScope.Reduction.add_reduction scope name
and process_hint scope hint =
EcScope.Auto.add_hint scope hint
and process_dump_why3 scope filename =
EcScope.dump_why3 scope filename; scope
and process_dump scope (source, tc) =
let open EcCoreGoal in
let input, (p1, p2) = source.tcd_source in
let goals, scope =
let mode = (Pragma.get ()).pm_check in
EcScope.Tactics.process scope mode tc
in
let wrerror fname =
EcScope.notify scope `Warning "cannot write `%s'" fname in
let tactic =
try File.read_from_file ~offset:p1 ~length:(p2-p1) input
with Invalid_argument _ -> "(* failed to read back script *)" in
let tactic = Printf.sprintf "%s.\n" (String.strip tactic) in
let ecfname = Printf.sprintf "%s.ec" source.tcd_output in
(try File.write_to_file ~output:ecfname tactic
with Invalid_argument _ -> wrerror ecfname);
goals |> oiter (fun (penv, (hd, hds)) ->
let goals =
List.map
(fun hd -> EcCoreGoal.FApi.get_pregoal_by_id hd penv)
(hd :: hds) in
List.iteri (fun i { g_hyps = hyps; g_concl = concl; } ->
let ecfname = Printf.sprintf "%s.%d.ec" source.tcd_output i in
try
let output = open_out_bin ecfname in
try_finally
(fun () ->
let fbuf = Format.formatter_of_out_channel output in
let ppe = EcPrinting.PPEnv.ofenv (EcEnv.LDecl.toenv hyps) in
source.tcd_width |> oiter (Format.pp_set_margin fbuf);
Format.fprintf fbuf "%a@?"
(EcPrinting.pp_goal ppe (Pragma.get ()).pm_g_prpo)
((EcEnv.LDecl.tohyps hyps, concl), `One (-1)))
(fun () -> close_out output)
with Sys_error _ -> wrerror ecfname)
goals);
scope
and process (ld : Loader.loader) (scope : EcScope.scope) g =
let loc = g.pl_loc in
let scope =
match
match g.pl_desc with
| Gtype t -> `Fct (fun scope -> process_types scope (List.map (mk_loc loc) t))
| Gtypeclass t -> `Fct (fun scope -> process_typeclass scope (mk_loc loc t))
| Gtycinstance t -> `Fct (fun scope -> process_tycinst scope (mk_loc loc t))
| Gmodule m -> `Fct (fun scope -> process_module scope m)
| Ginterface i -> `Fct (fun scope -> process_interface scope i)
| Goperator o -> `Fct (fun scope -> process_operator scope (mk_loc loc o))
| Gpredicate p -> `Fct (fun scope -> process_predicate scope (mk_loc loc p))
| Gnotation n -> `Fct (fun scope -> process_notation scope (mk_loc loc n))
| Gabbrev n -> `Fct (fun scope -> process_abbrev scope (mk_loc loc n))
| Gaxiom a -> `Fct (fun scope -> process_axiom scope (mk_loc loc a))
| GthOpen name -> `Fct (fun scope -> process_th_open scope name)
| GthClose info -> `Fct (fun scope -> process_th_close scope info)
| GthClear info -> `Fct (fun scope -> process_th_clear scope info)
| GthRequire name -> `Fct (fun scope -> process_th_require ld scope name)
| GthImport name -> `Fct (fun scope -> process_th_import scope name)
| GthExport name -> `Fct (fun scope -> process_th_export scope name)
| GthClone thcl -> `Fct (fun scope -> process_th_clone scope thcl)
| GModImport mods -> `Fct (fun scope -> process_mod_import scope mods)
| GsctOpen name -> `Fct (fun scope -> process_sct_open scope name)
| GsctClose name -> `Fct (fun scope -> process_sct_close scope name)
| Gprint p -> `Fct (fun scope -> process_print scope p; scope)
| Gsearch qs -> `Fct (fun scope -> process_search scope qs; scope)
| Glocate x -> `Fct (fun scope -> process_locate scope x; scope)
| Gtactics t -> `Fct (fun scope -> process_tactics scope t)
| Gtcdump info -> `Fct (fun scope -> process_dump scope info)
| Grealize p -> `Fct (fun scope -> process_realize scope p)
| Gprover_info pi -> `Fct (fun scope -> process_proverinfo scope pi)
| Gsave ed -> `Fct (fun scope -> process_save scope ed)
| Gpragma opt -> `State (fun scope -> process_pragma scope opt)
| Goption opt -> `Fct (fun scope -> process_option scope opt)
| Gaddrw hint -> `Fct (fun scope -> process_addrw scope hint)
| Greduction red -> `Fct (fun scope -> process_reduction scope red)
| Ghint hint -> `Fct (fun scope -> process_hint scope hint)
| GdumpWhy3 file -> `Fct (fun scope -> process_dump_why3 scope file)
with
| `Fct f -> Some (f scope)
| `State f -> f scope; None
in
scope
and process_internal ld scope g =
try odfl scope (process ld scope g.gl_action)
with e -> raise (EcScope.toperror_of_exn ~gloc:(loc g.gl_action) e)
let loader = Loader.create ()
let addidir ?namespace ?recursive (idir : string) =
Loader.addidir ?namespace ?recursive idir loader
let loadpath () =
List.map fst (Loader.aslist loader)
type checkmode = {
cm_checkall : bool;
cm_timeout : int;
cm_cpufactor : int;
cm_nprovers : int;
cm_provers : string list option;
cm_profile : bool;
cm_iterate : bool;
}
let initial ~checkmode ~boot =
let checkall = checkmode.cm_checkall in
let profile = checkmode.cm_profile in
let poptions = { EcScope.Prover.empty_options with
EcScope.Prover.po_timeout = Some checkmode.cm_timeout;
EcScope.Prover.po_cpufactor = Some checkmode.cm_cpufactor;
EcScope.Prover.po_nprovers = Some checkmode.cm_nprovers;
EcScope.Prover.po_provers = (checkmode.cm_provers, []);
EcScope.Prover.pl_iterate = Some (checkmode.cm_iterate);
} in
let perv = (None, (mk_loc _dummy EcCoreLib.i_Pervasive, None), Some `Export) in
let tactics = (None, (mk_loc _dummy "Tactics", None), Some `Export) in
let prelude = (None, (mk_loc _dummy "Logic", None), Some `Export) in
let loader = Loader.forsys loader in
let gstate = EcGState.from_flags [("profile", profile)] in
let scope = EcScope.empty gstate in
let scope = process_th_require1 loader scope perv in
let scope = if boot then scope else
List.fold_left (process_th_require1 loader)
scope [tactics; prelude] in
let scope = EcScope.Prover.set_default scope poptions in
let scope = if checkall then EcScope.Prover.full_check scope else scope in
EcScope.freeze scope
type context = {
ct_level : int;
ct_current : EcScope.scope;
ct_root : EcScope.scope;
ct_stack : (EcScope.scope list) option;
}
let context = ref (None : context option)
let rootctxt ?(undo = true) (scope : EcScope.scope) =
{ ct_level = 0;
ct_current = scope;
ct_root = scope;
ct_stack = if undo then Some [] else None; }
let pop_context context =
match context.ct_stack with
| None -> EcScope.hierror "undo stack disabled"
| Some stack ->
assert (not (List.is_empty stack));
{ ct_level = context.ct_level - 1;
ct_root = context.ct_root;
ct_current = List.hd stack;
ct_stack = Some (List.tl stack); }
let push_context scope context =
{ ct_level = context.ct_level + 1;
ct_root = context.ct_root;
ct_current = scope;
ct_stack = context.ct_stack
|> omap (fun st -> context.ct_current :: st); }
let initialize ~restart ~undo ~boot ~checkmode =
assert (restart || EcUtils.is_none !context);
if restart then Pragma.set dpragma;
context := Some (rootctxt ~undo (initial ~checkmode ~boot))
type notifier = EcGState.loglevel -> string Lazy.t -> unit
let addnotifier (notifier : notifier) =
assert (EcUtils.is_some !context);
let gstate = EcScope.gstate (oget !context).ct_root in
ignore (EcGState.add_notifier notifier gstate)
let current () =
(oget !context).ct_current
let uuid () : int =
(oget !context).ct_level
let mode () : string =
match (Pragma.get ()).pm_check with
| `Check -> "check"
| `WeakCheck -> "weakcheck"
| `Report -> "report"
let undo (olduuid : int) =
if olduuid < (uuid ()) then
for _ = (uuid ()) - 1 downto olduuid do
context := Some (pop_context (oget !context))
done
let reset () =
context := Some (rootctxt (oget !context).ct_root)
let process ?(timed = false) ?(break = false) (g : global_action located) : float option =
ignore break;
let current = oget !context in
let scope = current.ct_current in
try
let (tdelta, oscope) = EcUtils.timed (process loader scope) g in
oscope |> oiter (fun scope -> context := Some (push_context scope current));
if timed then
EcScope.notify scope `Info "time: %f" tdelta;
Some tdelta
with
| Pragma `Reset -> reset (); None
| Pragma `Restart -> raise Restart
let check_eco =
EcEco.check_eco (fun name -> Loader.locate name loader)
module S = EcScope
module L = EcBaseLogic
let pp_current_goal ?(all = false) stream =
let scope = current () in
match S.xgoal scope with
| None -> ()
| Some { S.puc_active = None; S.puc_cont = ct } ->
Format.fprintf stream "Remaining lemmas to prove:@\n%!";
List.iter
(fun ((_, ax), p, env) ->
let ppe = EcPrinting.PPEnv.ofenv (EcSection.env env)in
Format.fprintf stream " %s: %a@\n%!"
(EcPath.tostring p)
(EcPrinting.pp_form ppe) ax.EcDecl.ax_spec)
(fst ct)
| Some { S.puc_active = Some (puc, _) } -> begin
match puc.S.puc_jdg with
| S.PSNoCheck -> ()
| S.PSCheck pf -> begin
let ppe = EcPrinting.PPEnv.ofenv (S.env scope) in
match EcCoreGoal.opened pf with
| None -> Format.fprintf stream "No more goals@\n%!"
| Some (n, g) ->
let get_hc { EcCoreGoal.g_hyps; EcCoreGoal.g_concl } =
(EcEnv.LDecl.tohyps g_hyps, g_concl)
in
if all then
let subgoals = EcCoreGoal.all_opened pf in
let subgoals = odfl [] (List.otail subgoals) in
let subgoals = List.map get_hc subgoals in
EcPrinting.pp_goal ppe (Pragma.get ()).pm_g_prpo
stream (get_hc g, `All subgoals)
else
EcPrinting.pp_goal ppe (Pragma.get ()).pm_g_prpo
stream (get_hc g, `One n)
end
end
let pp_maybe_current_goal stream =
match (Pragma.get ()).pm_verbose with
| true -> pp_current_goal ~all:(Pragma.get ()).pm_g_prall stream
| false -> ()
UC DSL interface
let checkmode = {
cm_checkall = false;
cm_timeout = 0;
cm_cpufactor = 1;
cm_nprovers = 0;
cm_provers = None;
cm_profile = false;
cm_iterate = false;
}
let ucdsl_context : EcScope.scope list ref = ref []
let ucdsl_init () =
let scope = initial ~checkmode:checkmode ~boot:false in
ucdsl_context := [scope]
let ucdsl_addnotifier (notifier : notifier) =
assert (not (List.is_empty (! ucdsl_context)));
let gstate = EcScope.gstate (List.hd (! ucdsl_context)) in
ignore (EcGState.add_notifier notifier gstate)
let ucdsl_current () =
assert (not (List.is_empty (! ucdsl_context)));
List.hd (! ucdsl_context)
let ucdsl_update scope =
assert (not (List.is_empty (! ucdsl_context)));
let rest = List.tl (! ucdsl_context) in
ucdsl_context := scope :: rest
let ucdsl_require threq =
assert (not (List.is_empty (! ucdsl_context)));
let top_sc = List.hd (! ucdsl_context) in
let rest = List.tl (! ucdsl_context) in
let new_sc = process_th_require1 loader top_sc threq in
ucdsl_context := new_sc :: rest
let ucdsl_new () =
assert (not (List.is_empty (! ucdsl_context)));
let new_sc = EcScope.for_loading (List.hd (! ucdsl_context)) in
ucdsl_context := new_sc :: ! ucdsl_context
let ucdsl_end () =
assert (List.length (! ucdsl_context) >= 2);
let top_sc = List.hd (! ucdsl_context) in
let prev_sc = List.hd (List.tl (! ucdsl_context)) in
let rest = List.drop 2 (! ucdsl_context) in
let new_sc = EcScope.Theory.update_with_required prev_sc top_sc in
ucdsl_context := new_sc :: rest
|
75a5795a37816cbbfdbca1869434b00d8bd7fae61f77770e36f5066c819b0b2a | Racket-Cookbooks/Plot-cookbook | cosandderiv.rkt | #lang racket ; draw a graph of cos
and deriv^3(cos )
(define ((deriv f) x)
(/ (- (f x) (f (- x 0.001))) 0.001))
(define (thrice f) (lambda (x) (f (f (f x)))))
(plot (list (function ((thrice deriv) sin) -5 5)
(function cos -5 5 #:color 'blue))) | null | https://raw.githubusercontent.com/Racket-Cookbooks/Plot-cookbook/dfe8a81a6c7a3ae7296ad4e15bf5be9a99f04b6a/examples/cosandderiv/cosandderiv.rkt | racket | draw a graph of cos | and deriv^3(cos )
(define ((deriv f) x)
(/ (- (f x) (f (- x 0.001))) 0.001))
(define (thrice f) (lambda (x) (f (f (f x)))))
(plot (list (function ((thrice deriv) sin) -5 5)
(function cos -5 5 #:color 'blue))) |
e2efb4800b2e6fe38c7791221ebc7dadd286fc7afb2080f3ba93d79e7634abcd | LaurentMazare/ocaml-matplotlib | pyplot.mli | val xlim : left:float -> right:float -> unit
val ylim : bottom:float -> top:float -> unit
val xlabel : string -> unit
val ylabel : string -> unit
val grid : bool -> unit
val title : string -> unit
val plot
: ?label:string
-> ?color:Mpl.Color.t
-> ?linewidth:float
-> ?linestyle:Mpl.Linestyle.t
-> ?xs:float array
-> float array
-> unit
val semilogy
: ?label:string
-> ?color:Mpl.Color.t
-> ?linewidth:float
-> ?linestyle:Mpl.Linestyle.t
-> ?xs:float array
-> float array
-> unit
val semilogx
: ?label:string
-> ?color:Mpl.Color.t
-> ?linewidth:float
-> ?linestyle:Mpl.Linestyle.t
-> ?xs:float array
-> float array
-> unit
val loglog
: ?label:string
-> ?color:Mpl.Color.t
-> ?linewidth:float
-> ?linestyle:Mpl.Linestyle.t
-> ?xs:float array
-> float array
-> unit
val fill_between
: ?color:Mpl.Color.t
-> ?alpha:float
-> float array
-> float array
-> float array
-> unit
val hist
: ?label:string
-> ?color:Mpl.Color.t
-> ?bins:int
-> ?orientation:[ `horizontal | `vertical ]
-> ?histtype:[ `bar | `barstacked | `step | `stepfilled ]
-> ?xs:float array list
-> float array
-> unit
val scatter
: ?s:float
-> ?c:Mpl.Color.t
(* Possible markers:
'o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd', 'P', 'X'
*)
-> ?marker:char
-> ?alpha:float
-> ?linewidths:float
-> (float * float) array
-> unit
val imshow : ?cmap:string -> Mpl.Imshow_data.t -> unit
val legend : ?labels:(string array) -> ?loc:Mpl.Loc.t -> unit -> unit
| null | https://raw.githubusercontent.com/LaurentMazare/ocaml-matplotlib/d9d47ff63794c56c3ff1022bba7246344f2ec326/src/matplotlib/pyplot.mli | ocaml | Possible markers:
'o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd', 'P', 'X'
| val xlim : left:float -> right:float -> unit
val ylim : bottom:float -> top:float -> unit
val xlabel : string -> unit
val ylabel : string -> unit
val grid : bool -> unit
val title : string -> unit
val plot
: ?label:string
-> ?color:Mpl.Color.t
-> ?linewidth:float
-> ?linestyle:Mpl.Linestyle.t
-> ?xs:float array
-> float array
-> unit
val semilogy
: ?label:string
-> ?color:Mpl.Color.t
-> ?linewidth:float
-> ?linestyle:Mpl.Linestyle.t
-> ?xs:float array
-> float array
-> unit
val semilogx
: ?label:string
-> ?color:Mpl.Color.t
-> ?linewidth:float
-> ?linestyle:Mpl.Linestyle.t
-> ?xs:float array
-> float array
-> unit
val loglog
: ?label:string
-> ?color:Mpl.Color.t
-> ?linewidth:float
-> ?linestyle:Mpl.Linestyle.t
-> ?xs:float array
-> float array
-> unit
val fill_between
: ?color:Mpl.Color.t
-> ?alpha:float
-> float array
-> float array
-> float array
-> unit
val hist
: ?label:string
-> ?color:Mpl.Color.t
-> ?bins:int
-> ?orientation:[ `horizontal | `vertical ]
-> ?histtype:[ `bar | `barstacked | `step | `stepfilled ]
-> ?xs:float array list
-> float array
-> unit
val scatter
: ?s:float
-> ?c:Mpl.Color.t
-> ?marker:char
-> ?alpha:float
-> ?linewidths:float
-> (float * float) array
-> unit
val imshow : ?cmap:string -> Mpl.Imshow_data.t -> unit
val legend : ?labels:(string array) -> ?loc:Mpl.Loc.t -> unit -> unit
|
d6df15f7a268e7e409e0a1f819e0eb4fd379b788657a7e8efc25d84506cda8ab | zwizwa/erl_tools | gdb.erl | ( c ) 2018 -- see LICENSE file
-module(gdb).
Start GDB through TCP GDB RSP , providing a Port handler
Start GDB attaching to host Pid
Start GDB , upload file , exit
,cmd_sink/3 %% Send command, forwared responses to sink.
,cmd/3 %% Send command, return formatted response.
,set/4 %% Set a variable or struct member
,send/2, sync/2 %% For blocking interaction
Retreive values from status messages ( ad - hoc )
,msg_proplist/1 %% Hack, gathers all bindings
,msg_parse/1 %% Proper parser
,open_mi/1 %% Low level
]).
GDB Machine Interface ( MI ) .
%%
Interact with GDB from erlang .
open_port/2 with proper arguments . Expects script that starts
%% with -i=mi argument.
open_mi(GdbMi) ->
log:info("GdbMI = ~p~n", [GdbMi]),
open_port({spawn, GdbMi}, [{line, 1024}, use_stdio]).
open_os_pid(GdbMi, OsPid, Elf, Sink) ->
P = open_mi(GdbMi),
ok = sync(P, Sink),
cmd_sink(P, tools:format("file ~s", [Elf]), Sink),
cmd_sink(P, tools:format("attach ~p", [OsPid]), Sink),
P.
open(GdbMi, TargetHost, TargetPort, Elf, Sink) ->
P = open_mi(GdbMi),
ok = sync(P, Sink),
cmd_sink_file(P, Elf, Sink),
cmd_sink(P, tools:format("target remote ~s:~p", [TargetHost, TargetPort]), Sink),
P.
cmd_sink_file(_, none, _) -> ok;
cmd_sink_file(P, Elf, Sink) -> cmd_sink(P, tools:format("file ~s", [Elf]), Sink).
%% Ask connected dev node to push image here.
%% Assumes host name is set up correctly so dev node can find us, as
GDB uses plain TCP to connect .
upload({pull, DevNode}, Gdb, TargetPort, Elf, Sink) ->
{ok, TargetHost} = inet:gethostname(),
rpc:call(DevNode, gdb, upload, [TargetHost, Gdb, TargetPort, Elf, Sink]);
%% Upload ELF through gdb -i=mi
upload(TargetHost, Gdb, TargetPort, Elf, Sink) ->
P = open(Gdb, TargetHost, TargetPort, Elf, Sink),
Rv = cmd_sink(P, "load", Sink),
_Rv = cmd_sink(P, "compare-sections", Sink),
quit(P, Sink),
Rv.
, ensuring it has actually quit by catching the monitor
%% message. Note that 'quit' doesn't send any feedback, so add a
%% timeout and be loud about failing.
quit(P, _Sink) ->
Ref = erlang:monitor(port, P),
ok = send(P, "quit"),
receive
{'DOWN',Ref,port,_,_}=_Msg ->
%% log:info("~p~n",[_Msg]),
ok
after
2000 ->
throw(gdb_quit_timeout)
end,
ok.
%% Send command, send results to sink, and wait for (gdb) prompt.
cmd_sink(Port, Cmd, Sink) ->
ok = send(Port, Cmd),
ok = sync(Port, Sink),
ok.
send(Port, Cmd) ->
log:info("gdb: send: ~p~n", [Cmd]),
Port ! {self(), {command, Cmd++"\n"}}, ok.
sync(Port,Sink) ->
receive
{Port, {data, {eol, [$(,$g,$d,$b,$)|_]}}} ->
%% log:info("sync ok~n"),
Sink(eof),
ok;
{Port, {data, {eol, Line}}} ->
Sink({data, untag(Line)}),
sync(Port,Sink);
{Port, Anything} ->
Error = {error, Anything},
Sink(Error),
Sink(eof),
Error
after
This worked ok for which seems to be a bit more
%% responsive than openocd. Note sure what to do here. Just
%% up the timeout?
2000
10000 ->
log:info("gdb:sync timeout\n"),
{error, timeout}
end.
%% -Output-Syntax.html#GDB_002fMI-Output-Syntax
untag(Line) ->
%% log:info("untag: ~p~n",[Line]),
case Line of
[$^|S] -> {result,S};
[$+|S] -> {status,S};
[$&|S] -> {log,S};
[$*|S] -> {exec,S};
[$=|S] -> {notify,S};
[$~|S] -> {console,S};
Other -> {other, Other}
end.
non - sink version of cmd_sink/3 .
cmd(Port, Cmd, list) ->
sink:gen_to_list(fun(Sink) -> gdb:cmd_sink(Port, Cmd, Sink) end);
cmd(Port, Cmd, console) ->
cmd_console(Port, Cmd);
cmd(Port, Cmd, result) ->
hd(tools:filter_tag(result,cmd(Port, Cmd, list))).
GDB mi access is useful for poking at firmware images from Erlang ,
%% without having to expose a specific interface to do so. Note that
getting information out of the image is best done with direct GDB
RSP calls ; this here is only one - directionl . I.e. this only
%% "sends" a message. Rely on firmware mechanism to produce a response.
%% Note: A previous attempt to parse the expressions printed by gdb
failed due to lack of simple structure in gdb 's output ( i.e. it is
%% real work to make that work properly..).
%% Path is a list of atoms, and is mapped to a (nested) structure
%% member reference address or a single value.
set(P, Path, Val, Sink) when is_list(Path) ->
Dotted = string:join(lists:map(fun atom_to_list/1, Path),"."),
Cmd = tools:format("set ~s = ~p", [Dotted, Val]),
%%tools:info("gdb:set ~p~n", [Cmd]),
cmd(P,Cmd,Sink);
set(P, Var, Val, Sink) when is_atom(Var) ->
set(P, [Var], Val, Sink).
Run command , return IO list of console output . Note that using the
%% erlang scanner is a dirty hack, but seems to work. Don't use this
%% in production code!
cmd_console(P, Cmd) ->
tools:filter_tag(ok,[console_clean(Msg) || Msg<-gdb:cmd(P,Cmd,list)]).
console_clean({console, QuotedString}) ->
{ok,[{string,_,String}],_} = erl_scan:string(QuotedString), {ok, String};
console_clean(Other) -> {error, Other}.
%% There is currently no real parser, but since the structures are
%% fixed it is possible to use regular expressions to fish out what is
%% needed.
msg_get({status,Str},Tag) when is_binary(Tag) ->
Re = tools:format("download.*~s=\"(.*?)\"",[Tag]),
case re:run(Str, Re, [{capture,all_but_first,binary}]) of
{match,[Val]} -> {ok, Val};
Other -> {error, Other}
end.
%% ([email protected])15> re:run(S,"download.*section-sent=\"(.*?)\"",[{capture,all,list}]).
%% Very Ad-hoc. Works fine for integers, but doesn't work for
%% multi-line results.
%% unpack_binding(Str) ->
%% case erl_scan:string(Str) of
%% {ok,[{string,1,[$$|Binding]}],1} ->
%% case re:split(Binding, <<" = ">>) of
[ , ] - > { ok , , } ;
%% _ -> error
%% end;
%% _ -> error
%% end.
test() -> "download,{section=\".text\",section-sent=\"1440\",section-size=\"34032\",total-sent=\"1676\",total-size=\"625300\"}".
tok_fold(Str) ->
parse:bimodal_tokenize(
#{ %% Used by tokenizer
$" => quote,
$\\ => escape,
%% Left in output stream
${ => open,
$} => close,
$, => comma,
$= => equal,
%% Escaped characters
{escape, $r} => 13,
{escape, $n} => 10
},
source:from_list(Str)).
msg_proplist(test) ->
msg_proplist(test());
%% A simple hack to avoid a real parser, using just a bimodal
%% tokenizer. We don't care about the nesting of the data structure,
%% but only want the key,value bindings, so just scan for
[ { atom , K},equal,{atom , V } ] in the token stream .
msg_proplist(Str) ->
Fold = tok_fold(Str),
T = fun(X) -> list_to_atom(X) end,
{_,_,Rv} =
Fold(
fun({atom,V},{equal,{atom,K},L}) -> {x,x,[{T(K),V}|L]};
(C,{B,_,L}) -> {C,B,L} %% shift delay line
end,
{x,x,[]}),
Rv.
%% But a good enough parser isn't actually that difficult. Work with
concrete lists as lazy lists are hard to express in Erlang .
msg_parse(test) ->
msg_parse(test());
msg_parse({tok,Tokens}) ->
p(Tokens, [], []);
msg_parse(Str) ->
msg_parse({tok,fold:to_list(tok_fold(Str))}).
r(Q) -> lists:reverse(Q).
%% I: input
%% Q: current queue
%% S: stack of queues
( 1 )
p([open |I], Q, S) -> p(I, [], [Q|S]);
p([close |I], Q1, [[{eq,K}|Q2]|S]) -> p(I, [{K,r(Q1)}|Q2], S);
p([close |I], Q1, [Q2|S]) -> p(I, [r(Q1)|Q2], S);
p([{atom,V} |I], [{eq,K}|Q], S) -> p(I, [{K,V}|Q], S);
p([{atom,A} |I], Q, S) -> p(I, [A|Q], S);
p([equal |I], [K|Q], S) -> p(I, [{eq,K}|Q], S);
( 2 )
p([], Q, []) -> r(Q);
p(Input, Queue, Stack) -> error({parse,Input,Queue,Stack}).
( 1 ) leaves empty atoms inbetween other tokens . This is
%% convenient for some things, and easy to filter out here.
( 2 ) FIXME : shortcut . this will not catch some bad syntax but is
%% good enough in case we know the input is well-formed. We only need
%% it during tokenization.
%% Note that {Q,S} is a representation of the continuation. S is
always a stack of Qs , but there are two kinds of Qs :
%% - list the hole at the end of a list
- { eq , K } the hole in the second slot of the pair
| null | https://raw.githubusercontent.com/zwizwa/erl_tools/affd4060ab5b963e0cc8fcfd4a1ca5023aa518d3/src/gdb.erl | erlang | Send command, forwared responses to sink.
Send command, return formatted response.
Set a variable or struct member
For blocking interaction
Hack, gathers all bindings
Proper parser
Low level
with -i=mi argument.
Ask connected dev node to push image here.
Assumes host name is set up correctly so dev node can find us, as
Upload ELF through gdb -i=mi
message. Note that 'quit' doesn't send any feedback, so add a
timeout and be loud about failing.
log:info("~p~n",[_Msg]),
Send command, send results to sink, and wait for (gdb) prompt.
log:info("sync ok~n"),
responsive than openocd. Note sure what to do here. Just
up the timeout?
-Output-Syntax.html#GDB_002fMI-Output-Syntax
log:info("untag: ~p~n",[Line]),
without having to expose a specific interface to do so. Note that
"sends" a message. Rely on firmware mechanism to produce a response.
Note: A previous attempt to parse the expressions printed by gdb
real work to make that work properly..).
Path is a list of atoms, and is mapped to a (nested) structure
member reference address or a single value.
tools:info("gdb:set ~p~n", [Cmd]),
erlang scanner is a dirty hack, but seems to work. Don't use this
in production code!
There is currently no real parser, but since the structures are
fixed it is possible to use regular expressions to fish out what is
needed.
([email protected])15> re:run(S,"download.*section-sent=\"(.*?)\"",[{capture,all,list}]).
Very Ad-hoc. Works fine for integers, but doesn't work for
multi-line results.
unpack_binding(Str) ->
case erl_scan:string(Str) of
{ok,[{string,1,[$$|Binding]}],1} ->
case re:split(Binding, <<" = ">>) of
_ -> error
end;
_ -> error
end.
Used by tokenizer
Left in output stream
Escaped characters
A simple hack to avoid a real parser, using just a bimodal
tokenizer. We don't care about the nesting of the data structure,
but only want the key,value bindings, so just scan for
shift delay line
But a good enough parser isn't actually that difficult. Work with
I: input
Q: current queue
S: stack of queues
convenient for some things, and easy to filter out here.
good enough in case we know the input is well-formed. We only need
it during tokenization.
Note that {Q,S} is a representation of the continuation. S is
- list the hole at the end of a list | ( c ) 2018 -- see LICENSE file
-module(gdb).
Start GDB through TCP GDB RSP , providing a Port handler
Start GDB attaching to host Pid
Start GDB , upload file , exit
Retreive values from status messages ( ad - hoc )
]).
GDB Machine Interface ( MI ) .
Interact with GDB from erlang .
open_port/2 with proper arguments . Expects script that starts
open_mi(GdbMi) ->
log:info("GdbMI = ~p~n", [GdbMi]),
open_port({spawn, GdbMi}, [{line, 1024}, use_stdio]).
open_os_pid(GdbMi, OsPid, Elf, Sink) ->
P = open_mi(GdbMi),
ok = sync(P, Sink),
cmd_sink(P, tools:format("file ~s", [Elf]), Sink),
cmd_sink(P, tools:format("attach ~p", [OsPid]), Sink),
P.
open(GdbMi, TargetHost, TargetPort, Elf, Sink) ->
P = open_mi(GdbMi),
ok = sync(P, Sink),
cmd_sink_file(P, Elf, Sink),
cmd_sink(P, tools:format("target remote ~s:~p", [TargetHost, TargetPort]), Sink),
P.
cmd_sink_file(_, none, _) -> ok;
cmd_sink_file(P, Elf, Sink) -> cmd_sink(P, tools:format("file ~s", [Elf]), Sink).
GDB uses plain TCP to connect .
upload({pull, DevNode}, Gdb, TargetPort, Elf, Sink) ->
{ok, TargetHost} = inet:gethostname(),
rpc:call(DevNode, gdb, upload, [TargetHost, Gdb, TargetPort, Elf, Sink]);
upload(TargetHost, Gdb, TargetPort, Elf, Sink) ->
P = open(Gdb, TargetHost, TargetPort, Elf, Sink),
Rv = cmd_sink(P, "load", Sink),
_Rv = cmd_sink(P, "compare-sections", Sink),
quit(P, Sink),
Rv.
, ensuring it has actually quit by catching the monitor
quit(P, _Sink) ->
Ref = erlang:monitor(port, P),
ok = send(P, "quit"),
receive
{'DOWN',Ref,port,_,_}=_Msg ->
ok
after
2000 ->
throw(gdb_quit_timeout)
end,
ok.
cmd_sink(Port, Cmd, Sink) ->
ok = send(Port, Cmd),
ok = sync(Port, Sink),
ok.
send(Port, Cmd) ->
log:info("gdb: send: ~p~n", [Cmd]),
Port ! {self(), {command, Cmd++"\n"}}, ok.
sync(Port,Sink) ->
receive
{Port, {data, {eol, [$(,$g,$d,$b,$)|_]}}} ->
Sink(eof),
ok;
{Port, {data, {eol, Line}}} ->
Sink({data, untag(Line)}),
sync(Port,Sink);
{Port, Anything} ->
Error = {error, Anything},
Sink(Error),
Sink(eof),
Error
after
This worked ok for which seems to be a bit more
2000
10000 ->
log:info("gdb:sync timeout\n"),
{error, timeout}
end.
untag(Line) ->
case Line of
[$^|S] -> {result,S};
[$+|S] -> {status,S};
[$&|S] -> {log,S};
[$*|S] -> {exec,S};
[$=|S] -> {notify,S};
[$~|S] -> {console,S};
Other -> {other, Other}
end.
non - sink version of cmd_sink/3 .
cmd(Port, Cmd, list) ->
sink:gen_to_list(fun(Sink) -> gdb:cmd_sink(Port, Cmd, Sink) end);
cmd(Port, Cmd, console) ->
cmd_console(Port, Cmd);
cmd(Port, Cmd, result) ->
hd(tools:filter_tag(result,cmd(Port, Cmd, list))).
GDB mi access is useful for poking at firmware images from Erlang ,
getting information out of the image is best done with direct GDB
RSP calls ; this here is only one - directionl . I.e. this only
failed due to lack of simple structure in gdb 's output ( i.e. it is
set(P, Path, Val, Sink) when is_list(Path) ->
Dotted = string:join(lists:map(fun atom_to_list/1, Path),"."),
Cmd = tools:format("set ~s = ~p", [Dotted, Val]),
cmd(P,Cmd,Sink);
set(P, Var, Val, Sink) when is_atom(Var) ->
set(P, [Var], Val, Sink).
Run command , return IO list of console output . Note that using the
cmd_console(P, Cmd) ->
tools:filter_tag(ok,[console_clean(Msg) || Msg<-gdb:cmd(P,Cmd,list)]).
console_clean({console, QuotedString}) ->
{ok,[{string,_,String}],_} = erl_scan:string(QuotedString), {ok, String};
console_clean(Other) -> {error, Other}.
msg_get({status,Str},Tag) when is_binary(Tag) ->
Re = tools:format("download.*~s=\"(.*?)\"",[Tag]),
case re:run(Str, Re, [{capture,all_but_first,binary}]) of
{match,[Val]} -> {ok, Val};
Other -> {error, Other}
end.
[ , ] - > { ok , , } ;
test() -> "download,{section=\".text\",section-sent=\"1440\",section-size=\"34032\",total-sent=\"1676\",total-size=\"625300\"}".
tok_fold(Str) ->
parse:bimodal_tokenize(
$" => quote,
$\\ => escape,
${ => open,
$} => close,
$, => comma,
$= => equal,
{escape, $r} => 13,
{escape, $n} => 10
},
source:from_list(Str)).
msg_proplist(test) ->
msg_proplist(test());
[ { atom , K},equal,{atom , V } ] in the token stream .
msg_proplist(Str) ->
Fold = tok_fold(Str),
T = fun(X) -> list_to_atom(X) end,
{_,_,Rv} =
Fold(
fun({atom,V},{equal,{atom,K},L}) -> {x,x,[{T(K),V}|L]};
end,
{x,x,[]}),
Rv.
concrete lists as lazy lists are hard to express in Erlang .
msg_parse(test) ->
msg_parse(test());
msg_parse({tok,Tokens}) ->
p(Tokens, [], []);
msg_parse(Str) ->
msg_parse({tok,fold:to_list(tok_fold(Str))}).
r(Q) -> lists:reverse(Q).
( 1 )
p([open |I], Q, S) -> p(I, [], [Q|S]);
p([close |I], Q1, [[{eq,K}|Q2]|S]) -> p(I, [{K,r(Q1)}|Q2], S);
p([close |I], Q1, [Q2|S]) -> p(I, [r(Q1)|Q2], S);
p([{atom,V} |I], [{eq,K}|Q], S) -> p(I, [{K,V}|Q], S);
p([{atom,A} |I], Q, S) -> p(I, [A|Q], S);
p([equal |I], [K|Q], S) -> p(I, [{eq,K}|Q], S);
( 2 )
p([], Q, []) -> r(Q);
p(Input, Queue, Stack) -> error({parse,Input,Queue,Stack}).
( 1 ) leaves empty atoms inbetween other tokens . This is
( 2 ) FIXME : shortcut . this will not catch some bad syntax but is
always a stack of Qs , but there are two kinds of Qs :
- { eq , K } the hole in the second slot of the pair
|
21b339e171ce47cfd4d206c29484e6d341b6349a80ae6939f6c37e1d08ffedde | arttuka/reagent-material-ui | curtains_closed.cljs | (ns reagent-mui.icons.curtains-closed
"Imports @mui/icons-material/CurtainsClosed as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def curtains-closed (create-svg-icon (e "path" #js {"d" "M20 19V3H4v16H2v2h20v-2h-2zM11 5h2v14h-2V5z"})
"CurtainsClosed"))
| null | https://raw.githubusercontent.com/arttuka/reagent-material-ui/c7cd0d7c661ab9df5b0aed0213a6653a9a3f28ea/src/icons/reagent_mui/icons/curtains_closed.cljs | clojure | (ns reagent-mui.icons.curtains-closed
"Imports @mui/icons-material/CurtainsClosed as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def curtains-closed (create-svg-icon (e "path" #js {"d" "M20 19V3H4v16H2v2h20v-2h-2zM11 5h2v14h-2V5z"})
"CurtainsClosed"))
|
|
fa2278f779f42827989c7025044ce082efb324b776398b6893494b8ad42ff003 | tommaisey/aeon | le.help.scm | ;; (le a b)
;; See gt
| null | https://raw.githubusercontent.com/tommaisey/aeon/80744a7235425c47a061ec8324d923c53ebedf15/libs/third-party/sc3/rsc3/help/ugen/binary-ops/le.help.scm | scheme | (le a b)
See gt | |
ca454f4e061acc1c62b7c0e9662d45b42b4c58103213f87a16ef608efaa3e7ef | google/ormolu | sig-pattern-out.hs | f = do
x :: a <- g
f = do
(x, y)
:: (a, b) <-
g
| null | https://raw.githubusercontent.com/google/ormolu/ffdf145bbdf917d54a3ef4951fc2655e35847ff0/data/examples/declaration/value/function/pattern/sig-pattern-out.hs | haskell | f = do
x :: a <- g
f = do
(x, y)
:: (a, b) <-
g
|
|
a9e9e4357ad7404ab7785fd92b3091697d861017049cd624b83ada1e99211046 | JacquesCarette/Drasil | AST.hs | -- | Defines a Makefile abstract syntax tree.
module Build.Drasil.Make.AST where
import Build.Drasil.Make.MakeString (MakeString)
-- * Types
-- | A Makefile is made up of Makefile rules.
newtype Makefile = M [Rule]
-- | A Makefile Rule needs a target, dependencies, type, and commands.
data Rule = R Target Dependencies Type [Command]
| A command is made up of ' MakeString 's and command operators .
data Command = C MakeString [CommandOpts]
-- | Ignore the return code from the system.
data CommandOpts =
IgnoreReturnCode deriving Eq
-- | Type of rule, either abstract or file-oriented.
data Type = Abstract
| File deriving Eq
| A Makefile target is made from a ' MakeString ' .
type Target = MakeString
| Dependencies are made up of 0 or more ' Target 's .
type Dependencies = [Target]
-- * Constructors
-- | Creates a Rule which results in a file being created.
mkFile :: Target -> Dependencies -> [Command] -> Rule
mkFile t d = R t d File
-- | Creates an abstract Rule not associated to a specific file.
mkRule :: Target -> Dependencies -> [Command] -> Rule
mkRule t d = R t d Abstract
| Creates a Command which fails the make process if it does not return zero .
mkCheckedCommand :: MakeString -> Command
mkCheckedCommand = flip C []
-- | Creates a command which executes and ignores the return code.
mkCommand :: MakeString -> Command
mkCommand = flip C [IgnoreReturnCode]
| null | https://raw.githubusercontent.com/JacquesCarette/Drasil/92dddf7a545ba5029f99ad5c5eddcd8dad56a2d8/code/drasil-build/lib/Build/Drasil/Make/AST.hs | haskell | | Defines a Makefile abstract syntax tree.
* Types
| A Makefile is made up of Makefile rules.
| A Makefile Rule needs a target, dependencies, type, and commands.
| Ignore the return code from the system.
| Type of rule, either abstract or file-oriented.
* Constructors
| Creates a Rule which results in a file being created.
| Creates an abstract Rule not associated to a specific file.
| Creates a command which executes and ignores the return code. | module Build.Drasil.Make.AST where
import Build.Drasil.Make.MakeString (MakeString)
newtype Makefile = M [Rule]
data Rule = R Target Dependencies Type [Command]
| A command is made up of ' MakeString 's and command operators .
data Command = C MakeString [CommandOpts]
data CommandOpts =
IgnoreReturnCode deriving Eq
data Type = Abstract
| File deriving Eq
| A Makefile target is made from a ' MakeString ' .
type Target = MakeString
| Dependencies are made up of 0 or more ' Target 's .
type Dependencies = [Target]
mkFile :: Target -> Dependencies -> [Command] -> Rule
mkFile t d = R t d File
mkRule :: Target -> Dependencies -> [Command] -> Rule
mkRule t d = R t d Abstract
| Creates a Command which fails the make process if it does not return zero .
mkCheckedCommand :: MakeString -> Command
mkCheckedCommand = flip C []
mkCommand :: MakeString -> Command
mkCommand = flip C [IgnoreReturnCode]
|
9668a097aac4365362c3ee5ddfd3ed209d582f06a2af39587d3d93d8effb04ce | clj-commons/rewrite-clj | stringz.cljc | (ns ^:no-doc rewrite-clj.node.stringz
(:require [clojure.string :as string]
[clojure.tools.reader.edn :as edn]
[rewrite-clj.node.protocols :as node] ))
#?(:clj (set! *warn-on-reflection* true))
;; ## Node
(defn- wrap-string [s]
(str "\"" s "\""))
(defn- join-lines [lines]
(string/join "\n" lines))
(defrecord StringNode [lines]
node/Node
(tag [_node]
(if (next lines)
:multi-line
:token))
(node-type [_node] :string)
(printable-only? [_node] false)
(sexpr* [_node _opts]
(join-lines
(map
(comp edn/read-string wrap-string)
lines)))
(length [_node]
(+ 2 (reduce + (map count lines))))
(string [_node]
(wrap-string (join-lines lines)))
Object
(toString [node]
(node/string node)))
(node/make-printable! StringNode)
# # Constructors
(defn string-node
"Create node representing a string value where `lines` can be a sequence of strings or a single string.
When `lines` is a sequence, the resulting node `tag` will be `:multi-line`, otherwise `:token`.
`:multi-line` refers to a single string in your source that appears over multiple lines, for example:
```Clojure
(def s \"foo
bar
baz\")
```
It does not apply to a string that appears on a single line that includes escaped newlines, for example:
```Clojure
(def s \"foo\\nbar\\n\\baz\")
```
Naive examples (see example on escaping below):
```Clojure
(require '[rewrite-clj.node :as n])
(-> (n/string-node \"hello\")
n/string)
;; => \"\\\"hello\\\"\"
(-> (n/string-node [\"line1\" \"\" \"line3\"])
n/string)
;; => \"\\\"line1\\n\\nline3\\\"\"
```
This function was originally written to serve the rewrite-clj parser.
Escaping and wrapping expectations are non-obvious.
- characters within strings are assumed to be escaped
- but the string should not wrapped with `\\\"`
Here's an example of conforming to these expectations for a string that has escape sequences.
(Best to view this on cljdoc, docstring string escaping is confusing).
```Clojure
(require '[clojure.string :as string])
(defn pr-str-unwrapped [s]
(apply str (-> s pr-str next butlast)))
(-> \"hey \\\" man\"
pr-str-unwrapped
n/string-node
n/string)
;; => \"\\\"hey \\\\\\\" man\\\"\"
```
To construct strings appearing on a single line, consider [[token-node]].
It will handle escaping for you."
[lines]
(if (string? lines)
(->StringNode [lines])
(->StringNode lines)))
| null | https://raw.githubusercontent.com/clj-commons/rewrite-clj/621fd5dbc0861807da9ff854bfc3df541f79446f/src/rewrite_clj/node/stringz.cljc | clojure | ## Node
=> \"\\\"hello\\\"\"
=> \"\\\"line1\\n\\nline3\\\"\"
=> \"\\\"hey \\\\\\\" man\\\"\" | (ns ^:no-doc rewrite-clj.node.stringz
(:require [clojure.string :as string]
[clojure.tools.reader.edn :as edn]
[rewrite-clj.node.protocols :as node] ))
#?(:clj (set! *warn-on-reflection* true))
(defn- wrap-string [s]
(str "\"" s "\""))
(defn- join-lines [lines]
(string/join "\n" lines))
(defrecord StringNode [lines]
node/Node
(tag [_node]
(if (next lines)
:multi-line
:token))
(node-type [_node] :string)
(printable-only? [_node] false)
(sexpr* [_node _opts]
(join-lines
(map
(comp edn/read-string wrap-string)
lines)))
(length [_node]
(+ 2 (reduce + (map count lines))))
(string [_node]
(wrap-string (join-lines lines)))
Object
(toString [node]
(node/string node)))
(node/make-printable! StringNode)
# # Constructors
(defn string-node
"Create node representing a string value where `lines` can be a sequence of strings or a single string.
When `lines` is a sequence, the resulting node `tag` will be `:multi-line`, otherwise `:token`.
`:multi-line` refers to a single string in your source that appears over multiple lines, for example:
```Clojure
(def s \"foo
bar
baz\")
```
It does not apply to a string that appears on a single line that includes escaped newlines, for example:
```Clojure
(def s \"foo\\nbar\\n\\baz\")
```
Naive examples (see example on escaping below):
```Clojure
(require '[rewrite-clj.node :as n])
(-> (n/string-node \"hello\")
n/string)
(-> (n/string-node [\"line1\" \"\" \"line3\"])
n/string)
```
This function was originally written to serve the rewrite-clj parser.
Escaping and wrapping expectations are non-obvious.
- characters within strings are assumed to be escaped
- but the string should not wrapped with `\\\"`
Here's an example of conforming to these expectations for a string that has escape sequences.
(Best to view this on cljdoc, docstring string escaping is confusing).
```Clojure
(require '[clojure.string :as string])
(defn pr-str-unwrapped [s]
(apply str (-> s pr-str next butlast)))
(-> \"hey \\\" man\"
pr-str-unwrapped
n/string-node
n/string)
```
To construct strings appearing on a single line, consider [[token-node]].
It will handle escaping for you."
[lines]
(if (string? lines)
(->StringNode [lines])
(->StringNode lines)))
|
08f2ca530d8a731341e1a068f27080c457d88f03908d4278bbe137d3016fa22b | startalkIM/ejabberd | mod_carboncopy_mnesia.erl | %%%-------------------------------------------------------------------
@author < >
( C ) 2016 ,
%%% @doc
%%%
%%% @end
Created : 15 Apr 2016 by < >
%%%-------------------------------------------------------------------
-module(mod_carboncopy_mnesia).
-behaviour(mod_carboncopy).
%% API
-export([init/2, enable/4, disable/3, list/2]).
-include("mod_carboncopy.hrl").
%%%===================================================================
%%% API
%%%===================================================================
init(_Host, _Opts) ->
Fields = record_info(fields, carboncopy),
try mnesia:table_info(carboncopy, attributes) of
Fields ->
ok;
_ ->
%% recreate..
mnesia:delete_table(carboncopy)
catch _:_Error ->
%% probably table don't exist
ok
end,
mnesia:create_table(carboncopy,
[{ram_copies, [node()]},
{attributes, record_info(fields, carboncopy)},
{type, bag}]),
mnesia:add_table_copy(carboncopy, node(), ram_copies).
enable(LUser, LServer, LResource, NS) ->
try mnesia:dirty_write(
#carboncopy{us = {LUser, LServer},
resource = LResource,
version = NS}) of
ok -> ok
catch _:Error ->
{error, Error}
end.
disable(LUser, LServer, LResource) ->
ToDelete = mnesia:dirty_match_object(
#carboncopy{us = {LUser, LServer},
resource = LResource,
version = '_'}),
try lists:foreach(fun mnesia:dirty_delete_object/1, ToDelete) of
ok -> ok
catch _:Error ->
{error, Error}
end.
list(LUser, LServer) ->
mnesia:dirty_select(
carboncopy,
[{#carboncopy{us = {LUser, LServer}, resource = '$2', version = '$3'},
[], [{{'$2','$3'}}]}]).
%%%===================================================================
Internal functions
%%%===================================================================
| null | https://raw.githubusercontent.com/startalkIM/ejabberd/718d86cd2f5681099fad14dab5f2541ddc612c8b/src/mod_carboncopy_mnesia.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
API
===================================================================
API
===================================================================
recreate..
probably table don't exist
===================================================================
=================================================================== | @author < >
( C ) 2016 ,
Created : 15 Apr 2016 by < >
-module(mod_carboncopy_mnesia).
-behaviour(mod_carboncopy).
-export([init/2, enable/4, disable/3, list/2]).
-include("mod_carboncopy.hrl").
init(_Host, _Opts) ->
Fields = record_info(fields, carboncopy),
try mnesia:table_info(carboncopy, attributes) of
Fields ->
ok;
_ ->
mnesia:delete_table(carboncopy)
catch _:_Error ->
ok
end,
mnesia:create_table(carboncopy,
[{ram_copies, [node()]},
{attributes, record_info(fields, carboncopy)},
{type, bag}]),
mnesia:add_table_copy(carboncopy, node(), ram_copies).
enable(LUser, LServer, LResource, NS) ->
try mnesia:dirty_write(
#carboncopy{us = {LUser, LServer},
resource = LResource,
version = NS}) of
ok -> ok
catch _:Error ->
{error, Error}
end.
disable(LUser, LServer, LResource) ->
ToDelete = mnesia:dirty_match_object(
#carboncopy{us = {LUser, LServer},
resource = LResource,
version = '_'}),
try lists:foreach(fun mnesia:dirty_delete_object/1, ToDelete) of
ok -> ok
catch _:Error ->
{error, Error}
end.
list(LUser, LServer) ->
mnesia:dirty_select(
carboncopy,
[{#carboncopy{us = {LUser, LServer}, resource = '$2', version = '$3'},
[], [{{'$2','$3'}}]}]).
Internal functions
|
470bdef8ad374f6c25427faaac3da347c007c981c4d65176070a9def9cdc9d7f | DSiSc/why3 | Macrogen_printing.ml |
open Format
open Macrogen_decls
open Macrogen_params
module rec X : module type of Macrogen_printing_sig = X
include X
module Helper = functor (P:Parameters) -> struct
open P
let (<|) f x y = f y x
let (<<) f x = f x
let indent = pp_open_box <| indent
let string_printer s = fprintf <| "%s" <| s
let params_printer fmt =
List.iter (fun tn -> fprintf fmt "@ 'a%s" << var_name dm tn) dm.var_params
let level tn blv = try TMap.find tn blv with Not_found -> 0
let inc_level tn blv = TMap.add tn ( 1 + level tn blv ) blv
let tindex_printer tn = fprintf <| "%d" <| (tn:TName.t:>int)
let tname_printer tn = fprintf <| "%s" <| type_name dm tn
let rec rpapply_printer op middle times fmt = match times with
| 0 -> fprintf fmt "%t" middle
| n -> fprintf fmt "%t(%t@ %t)@]" indent op
<< rpapply_printer op middle (n-1)
let options_printer = rpapply_printer << string_printer "option"
let somes_printer = rpapply_printer << string_printer "Some"
let csomes_printer =
rpapply_printer << string_printer "compose some"
<< string_printer "identity"
let list_printer f l fmt =
List.iter (fun x -> f x fmt) l
let sep_list_printer f s l fmt =
let _ = List.fold_left (fun acc x -> (if acc
then s fmt ) ; f x fmt ; true ) false l in ()
let binding_type_printer ?(blevels=TMap.empty) p tn =
options_printer (fprintf <| "'%t%t" <| p <| tindex_printer tn)
(level tn blevels)
let type_app_printer ?(blevels=TMap.empty) p tn fmt =
fprintf fmt "%t%t%t@ %t@]" indent << tname_printer tn << params_printer
<< sep_list_printer (fun tn -> binding_type_printer ~blevels p tn)
(fprintf <| "@ ") (binder_vars dm tn)
let type_printer ?(blevels=TMap.empty) p ty fmt = match ty with
| ITVar x -> fprintf fmt "'a%s" << var_name dm x
| ITDecl tn -> type_app_printer ~blevels p tn fmt
let make_first_case_printer p1 p2 =
let a = ref true in
fun fmt ->
if !a
then ( a:=false ; p1 fmt )
else p2 fmt
let rec_printer s =
make_first_case_printer ( fprintf <| s ) ( fprintf <| "with" )
let rec_fun_printer () = rec_printer "function"
let rec_type_printer () = rec_printer "type"
let rec_val_printer () = rec_printer "let rec"
let rec_ind_printer () = rec_printer "inductive"
let match_variables ?(blevels=TMap.empty) ?(vbase=string_printer "v")
(cn,bl,tl) =
let process_type blevels (vars,cnt) ty =
let vprinter fmt = fprintf fmt "%t%d" vbase cnt in
((vprinter,blevels,ty)::vars,cnt+1) in
let process_types blevels = List.fold_left (process_type blevels) in
let (vars,blevels,cnt) =
List.fold_left (fun (vars,blevels,cnt) (bo,tys) ->
let nblevels = inc_level bo blevels in
let vars,cnt = process_types blevels (vars,cnt) tys in
(vars,nblevels,cnt) ) ( [] , blevels , 0 ) bl in
let (vars,_) = process_types blevels (vars,cnt) tl in
List.rev vars
let cons_case_printer ?(blevels=TMap.empty) ?(vbase=string_printer "v")
case (cn,bl,tl) fmt =
let vars = match_variables ~blevels ~vbase (cn,bl,tl) in
fprintf fmt "%t| %t%s%t@] ->@ %t%t@]@]" indent indent << cons_name dm cn
<< list_printer (fun (vp,_,_) fmt -> fprintf fmt "@ %t" vp) vars
<< indent << case vars
let var_case_printer ?(vbase=string_printer "v") case tn fmt =
let vname fmt = fprintf fmt "%t0" vbase in
fprintf fmt "%t| %t%t@ %t0@] ->@ %t%t@]@]" indent indent
<< variable_name tn << vbase << indent << case vname
let match_printer ?(blevels=TMap.empty) ?(vbase=string_printer "v")
tn vcase ccase mt fmt =
match type_def dm tn with
| ITypeAssumption _ -> assert false
| ITypeDef ( c , _ ) ->
fprintf fmt "%tmatch %t with" indent mt ;
(if c.var_present
then fprintf fmt "@ %t" << var_case_printer ~vbase vcase tn);
fprintf fmt "%t@]@ end"
<< list_printer (fun cs fmt ->
fprintf fmt "@ %t%t@]" indent
<< cons_case_printer ~blevels ~vbase ( ccase cs ) cs) c.cons_list
let make_for_defs f =
TMap.iter (fun tn -> function
| ITypeAssumption _ -> ()
| ITypeDef ( c , v ) -> f tn c v) dm.type_decls
let make_for_bdefs f =
make_for_defs (fun tn c -> function
| [] -> ()
| v -> f tn c v)
let make_for_vdefs f =
make_for_defs (fun tn c v ->
if c.var_present
then f tn c v
else ())
let lemma_cons_case case _ vars fmt =
fprintf fmt "%t()"
<< list_printer (fun (vname,blevels,ty) fmt ->
match ty with
| ITVar _ -> ()
| ITDecl tn -> fprintf fmt "%t ;@ "
<< case vname blevels tn ) vars
let blemma_cons_case case _ vars fmt =
fprintf fmt "%t()"
<< list_printer (fun (vname,blevels,ty) fmt ->
match ty with
| ITVar _ -> ()
| ITDecl tn -> match binder_vars dm tn with
| [] -> ()
| _ -> fprintf fmt "%t ;@ "
<< case vname blevels tn ) vars
let reconstruct_cons_case case (cn,_,_) vars fmt =
fprintf fmt "%t%s%t@]" indent << cons_name dm cn
<< list_printer (fun (vname,blevels,ty) fmt ->
match ty with
| ITVar _ -> fprintf fmt "@ %t" vname
| ITDecl tn -> match binder_vars dm tn with
| [] -> fprintf fmt "@ %t" vname
| _ -> fprintf fmt "@ %t(%t)@]" indent
<< case vname blevels tn ) vars
let lift_printer sub sp blevels tn fmt =
let lift = if sub
then slift_name tn
else fprintf <| "olift" in
let middle = rpapply_printer lift sp << level tn blevels in
if sub
then fprintf fmt "%t(%t@ %t%t)@]" indent << rename_subst_name tn
<< middle << list_printer (fun tn' fmt ->
if tn = tn'
then fprintf fmt "@ identity"
else fprintf fmt "@ %t"
(csomes_printer << level tn' blevels))
(binder_vars dm tn)
else middle fmt
let subst_type_printer sub ?(blevels=TMap.empty) p1 p2 tn fmt =
let p' p tn fmt = fprintf fmt "'%t%t" p << tindex_printer tn in
fprintf fmt "%t%t ->" indent
(options_printer << p' p1 tn << level tn blevels) ;
if sub
then fprintf fmt "@ %t(%t)@]@]" indent << type_app_printer ~blevels p2 tn
else fprintf fmt "@ %t@]"
(options_printer << p' p2 tn << level tn blevels)
let print_composition sub1 sub2 tn p1 p2 fmt =
if sub1
then begin
fprintf fmt "%t%t@ %t%t@]"
indent
(if sub2 then subst_compose_name tn else rename_subst_name tn) p1
<< list_printer (fun tn fmt ->
fprintf fmt "@ %t" << p2 tn
) (binder_vars dm tn)
end else fprintf fmt "%trcompose@ %t@ %t@]" indent p1 << p2 tn
let typed_identity_printer sub b tn fmt =
let name = if sub
then subst_identity_name tn
else string_printer "identity" in
fprintf fmt "(%t%t :@ %t@])" indent name
<< subst_type_printer sub b b tn
let typed_sor_printer p b tn fmt =
fprintf fmt "(%t%t%t@ %t@] :@ %t@])" indent indent
<< subst_of_rename_name tn << p << type_app_printer b tn
end
module MakePP = functor (P0:Parameters) -> struct
module P = P0
module H = Helper(P)
end
| null | https://raw.githubusercontent.com/DSiSc/why3/8ba9c2287224b53075adc51544bc377bc8ea5c75/examples/prover/macro_generator/Macrogen_printing.ml | ocaml |
open Format
open Macrogen_decls
open Macrogen_params
module rec X : module type of Macrogen_printing_sig = X
include X
module Helper = functor (P:Parameters) -> struct
open P
let (<|) f x y = f y x
let (<<) f x = f x
let indent = pp_open_box <| indent
let string_printer s = fprintf <| "%s" <| s
let params_printer fmt =
List.iter (fun tn -> fprintf fmt "@ 'a%s" << var_name dm tn) dm.var_params
let level tn blv = try TMap.find tn blv with Not_found -> 0
let inc_level tn blv = TMap.add tn ( 1 + level tn blv ) blv
let tindex_printer tn = fprintf <| "%d" <| (tn:TName.t:>int)
let tname_printer tn = fprintf <| "%s" <| type_name dm tn
let rec rpapply_printer op middle times fmt = match times with
| 0 -> fprintf fmt "%t" middle
| n -> fprintf fmt "%t(%t@ %t)@]" indent op
<< rpapply_printer op middle (n-1)
let options_printer = rpapply_printer << string_printer "option"
let somes_printer = rpapply_printer << string_printer "Some"
let csomes_printer =
rpapply_printer << string_printer "compose some"
<< string_printer "identity"
let list_printer f l fmt =
List.iter (fun x -> f x fmt) l
let sep_list_printer f s l fmt =
let _ = List.fold_left (fun acc x -> (if acc
then s fmt ) ; f x fmt ; true ) false l in ()
let binding_type_printer ?(blevels=TMap.empty) p tn =
options_printer (fprintf <| "'%t%t" <| p <| tindex_printer tn)
(level tn blevels)
let type_app_printer ?(blevels=TMap.empty) p tn fmt =
fprintf fmt "%t%t%t@ %t@]" indent << tname_printer tn << params_printer
<< sep_list_printer (fun tn -> binding_type_printer ~blevels p tn)
(fprintf <| "@ ") (binder_vars dm tn)
let type_printer ?(blevels=TMap.empty) p ty fmt = match ty with
| ITVar x -> fprintf fmt "'a%s" << var_name dm x
| ITDecl tn -> type_app_printer ~blevels p tn fmt
let make_first_case_printer p1 p2 =
let a = ref true in
fun fmt ->
if !a
then ( a:=false ; p1 fmt )
else p2 fmt
let rec_printer s =
make_first_case_printer ( fprintf <| s ) ( fprintf <| "with" )
let rec_fun_printer () = rec_printer "function"
let rec_type_printer () = rec_printer "type"
let rec_val_printer () = rec_printer "let rec"
let rec_ind_printer () = rec_printer "inductive"
let match_variables ?(blevels=TMap.empty) ?(vbase=string_printer "v")
(cn,bl,tl) =
let process_type blevels (vars,cnt) ty =
let vprinter fmt = fprintf fmt "%t%d" vbase cnt in
((vprinter,blevels,ty)::vars,cnt+1) in
let process_types blevels = List.fold_left (process_type blevels) in
let (vars,blevels,cnt) =
List.fold_left (fun (vars,blevels,cnt) (bo,tys) ->
let nblevels = inc_level bo blevels in
let vars,cnt = process_types blevels (vars,cnt) tys in
(vars,nblevels,cnt) ) ( [] , blevels , 0 ) bl in
let (vars,_) = process_types blevels (vars,cnt) tl in
List.rev vars
let cons_case_printer ?(blevels=TMap.empty) ?(vbase=string_printer "v")
case (cn,bl,tl) fmt =
let vars = match_variables ~blevels ~vbase (cn,bl,tl) in
fprintf fmt "%t| %t%s%t@] ->@ %t%t@]@]" indent indent << cons_name dm cn
<< list_printer (fun (vp,_,_) fmt -> fprintf fmt "@ %t" vp) vars
<< indent << case vars
let var_case_printer ?(vbase=string_printer "v") case tn fmt =
let vname fmt = fprintf fmt "%t0" vbase in
fprintf fmt "%t| %t%t@ %t0@] ->@ %t%t@]@]" indent indent
<< variable_name tn << vbase << indent << case vname
let match_printer ?(blevels=TMap.empty) ?(vbase=string_printer "v")
tn vcase ccase mt fmt =
match type_def dm tn with
| ITypeAssumption _ -> assert false
| ITypeDef ( c , _ ) ->
fprintf fmt "%tmatch %t with" indent mt ;
(if c.var_present
then fprintf fmt "@ %t" << var_case_printer ~vbase vcase tn);
fprintf fmt "%t@]@ end"
<< list_printer (fun cs fmt ->
fprintf fmt "@ %t%t@]" indent
<< cons_case_printer ~blevels ~vbase ( ccase cs ) cs) c.cons_list
let make_for_defs f =
TMap.iter (fun tn -> function
| ITypeAssumption _ -> ()
| ITypeDef ( c , v ) -> f tn c v) dm.type_decls
let make_for_bdefs f =
make_for_defs (fun tn c -> function
| [] -> ()
| v -> f tn c v)
let make_for_vdefs f =
make_for_defs (fun tn c v ->
if c.var_present
then f tn c v
else ())
let lemma_cons_case case _ vars fmt =
fprintf fmt "%t()"
<< list_printer (fun (vname,blevels,ty) fmt ->
match ty with
| ITVar _ -> ()
| ITDecl tn -> fprintf fmt "%t ;@ "
<< case vname blevels tn ) vars
let blemma_cons_case case _ vars fmt =
fprintf fmt "%t()"
<< list_printer (fun (vname,blevels,ty) fmt ->
match ty with
| ITVar _ -> ()
| ITDecl tn -> match binder_vars dm tn with
| [] -> ()
| _ -> fprintf fmt "%t ;@ "
<< case vname blevels tn ) vars
let reconstruct_cons_case case (cn,_,_) vars fmt =
fprintf fmt "%t%s%t@]" indent << cons_name dm cn
<< list_printer (fun (vname,blevels,ty) fmt ->
match ty with
| ITVar _ -> fprintf fmt "@ %t" vname
| ITDecl tn -> match binder_vars dm tn with
| [] -> fprintf fmt "@ %t" vname
| _ -> fprintf fmt "@ %t(%t)@]" indent
<< case vname blevels tn ) vars
let lift_printer sub sp blevels tn fmt =
let lift = if sub
then slift_name tn
else fprintf <| "olift" in
let middle = rpapply_printer lift sp << level tn blevels in
if sub
then fprintf fmt "%t(%t@ %t%t)@]" indent << rename_subst_name tn
<< middle << list_printer (fun tn' fmt ->
if tn = tn'
then fprintf fmt "@ identity"
else fprintf fmt "@ %t"
(csomes_printer << level tn' blevels))
(binder_vars dm tn)
else middle fmt
let subst_type_printer sub ?(blevels=TMap.empty) p1 p2 tn fmt =
let p' p tn fmt = fprintf fmt "'%t%t" p << tindex_printer tn in
fprintf fmt "%t%t ->" indent
(options_printer << p' p1 tn << level tn blevels) ;
if sub
then fprintf fmt "@ %t(%t)@]@]" indent << type_app_printer ~blevels p2 tn
else fprintf fmt "@ %t@]"
(options_printer << p' p2 tn << level tn blevels)
let print_composition sub1 sub2 tn p1 p2 fmt =
if sub1
then begin
fprintf fmt "%t%t@ %t%t@]"
indent
(if sub2 then subst_compose_name tn else rename_subst_name tn) p1
<< list_printer (fun tn fmt ->
fprintf fmt "@ %t" << p2 tn
) (binder_vars dm tn)
end else fprintf fmt "%trcompose@ %t@ %t@]" indent p1 << p2 tn
let typed_identity_printer sub b tn fmt =
let name = if sub
then subst_identity_name tn
else string_printer "identity" in
fprintf fmt "(%t%t :@ %t@])" indent name
<< subst_type_printer sub b b tn
let typed_sor_printer p b tn fmt =
fprintf fmt "(%t%t%t@ %t@] :@ %t@])" indent indent
<< subst_of_rename_name tn << p << type_app_printer b tn
end
module MakePP = functor (P0:Parameters) -> struct
module P = P0
module H = Helper(P)
end
|
|
e4a4af9d65cdd40dc1135a77d6a2190ff36908db5e644a9d6a2fa370de12bd21 | Eduap-com/WordMat | bernstein.lisp | Author
University of Nebraska at Kearney
;; Copyright (C) 2011,2021 Barton Willis
;; This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
(in-package :maxima)
($load "bernstein_utilities.mac")
;; When bernstein_explicit is non-nil, bernstein_poly(k,n,x) simplifies to
;; binomial(n,k) * x^k (1-x)^(n-k) regardless of the values of k or n;
(defmvar $bernstein_explicit nil)
numerical ( complex rational , float , or big float ) evaluation of polynomials
(in-package #-gcl #:bigfloat #+gcl "BIGFLOAT")
(defun bernstein-poly (k n x)
(* (to (maxima::opcons 'maxima::%binomial n k)) (expt x k) (expt (- 1 x) (- n k))))
(in-package :maxima)
(defun $bernstein_poly (k n x) (simplify (list '(%bernstein_poly) k n x)))
(defprop $bernstein_poly %bernstein_poly alias)
(defprop $bernstein_poly %bernstein_poly verb)
(defprop %bernstein_poly $bernstein_poly reversealias)
(defprop %bernstein_poly $bernstein_poly noun)
(setf (get '%bernstein_poly 'conjugate-function)
#'(lambda (e)
(let ((k (car e))
(n (cadr e))
(x (caddr e)))
(if (and ($featurep k '$integer) ($featurep n '$integer))
(opcons '%bernstein_poly k n (opcons '$conjugate x))
(list (list '$conjugate 'simp) (take '(%bernstein_poly) k n x))))))
integrate(bernstein_poly(k , n , ) = hypergeometric([k+1,k - n],[k+2],x)*x^(k+1)/(k+1 )
(defun bernstein-integral (k n x)
(div
(mul
(opcons '%binomial n k)
(opcons 'mexpt x (add 1 k))
(opcons '$hypergeometric
(opcons 'mlist (add 1 k) (sub k n))
(opcons 'mlist (add 2 k))
x))
(add 1 k)))
(putprop '%bernstein_poly `((k n x) nil nil ,#'bernstein-integral) 'integral)
(putprop '$bernstein_poly `((k n x) nil nil ,#'bernstein-integral) 'integral)
(defun bernstein-poly-simp (e y z)
(declare (ignore y))
(let* ((fn (car (pop e)))
(k (if (consp e) (simpcheck (pop e) z) (wna-err fn)))
(n (if (consp e) (simpcheck (pop e) z) (wna-err fn)))
(x (if (consp e) (simpcheck (pop e) z) (wna-err fn))))
(if (consp e) (wna-err fn))
(cond ((and (integerp k) (integerp n) (>= k 0) (>= n k)
(complex-number-p x #'(lambda (s) (or (integerp s) ($ratnump s) (floatp s) ($bfloatp s)))))
(maxima::to (bigfloat::bernstein-poly (bigfloat::to k) (bigfloat::to n) (bigfloat::to x))))
((zerop1 x) (opcons '%kron_delta k 0))
((onep1 x) (opcons '%kron_delta k n))
((or $bernstein_explicit (and (integerp k) (integerp n)))
(if (and (integerp k) (integerp n) (or (< k 0) (> k n))) (mul 0 x)
(mul (opcons '%binomial n k) (opcons 'mexpt x k) (opcons 'mexpt (sub 1 x) (sub n k)))))
(t (list (list fn 'simp) k n x)))))
(setf (get '%bernstein_poly 'operators) #'bernstein-poly-simp)
(defprop %bernstein_poly
((k n x)
((mtimes) ((%bernstein_poly) k n x)
((mplus)
((mtimes) -1
((mqapply) (($psi array) 0) ((mplus) 1 k)))
((mqapply) (($psi array) 0)
((mplus) 1 ((mtimes) -1 k) n))
((mtimes) -1
((%log) ((mplus) 1 ((mtimes) -1 x))))
((%log) x)))
((mtimes)((%bernstein_poly) k n x)
((mplus)
((mqapply) (($psi array) 0) ((mplus) 1 n))
((mtimes) -1
((mqapply) (($psi array) 0)
((mplus) 1 ((mtimes) -1 k) n)))
((%log) ((mplus) 1 ((mtimes) -1 x)))))
((mtimes)
((mplus)
((%bernstein_poly) ((mplus) -1 k) ((mplus) -1 n) x)
((mtimes) -1
((%bernstein_poly) k ((mplus) -1 n) x))) n))
grad)
(defun $bernstein_approx (e vars n)
(if (not ($listp vars)) (merror "The second argument to bernstein_approx must be a list"))
(setq vars (margs vars))
(if (some #'(lambda (s) (not ($mapatom s))) vars)
(merror "The second argument to bernstein_approx must be a list of atoms"))
(if (or (not (integerp n)) (< n 1)) (merror "The third argument to bernstein_approx must be a positive integer"))
(let* ((k (length vars))
(d (make-list k :initial-element 0))
(nn (make-list k :initial-element n))
(carry) (acc 0) (m) (x))
(setq m (expt (+ n 1) k))
(setq nn (cons '(mlist) nn))
(dotimes (i m)
(setq acc (add acc
(mul
(opcons '%multibernstein_poly (cons '(mlist) d) nn (cons '(mlist) vars))
($substitute (cons '(mlist) (mapcar #'(lambda (s x) (opcons 'mequal x (div s n))) d vars)) e))))
(setq carry 1)
(dotimes (j k)
(setq x (+ carry (nth j d)))
(if (> x n) (setq x 0 carry 1) (setq carry 0))
(setf (nth j d) x)))
acc))
(defun $multibernstein_poly (k n x) (simplify (list '(%multibernstein_poly) k n x)))
(defprop $multibernstein_poly %multibernstein_poly alias)
(defprop $multibernstein_poly %multibernstein_poly verb)
(defprop %multibernstein_poly $multibernstein_poly reversealias)
(defprop %multibernstein_poly $multibernstein_poly noun)
(defun multi-bernstein-poly-simp (e y z)
(declare (ignore y))
(let*
((fn (car (pop e)))
(k (if (consp e) (simpcheck (pop e) z) (wna-err fn)))
(n (if (consp e) (simpcheck (pop e) z) (wna-err fn)))
(x (if (consp e) (simpcheck (pop e) z) (wna-err fn))))
(if (consp e) (wna-err fn))
(if (or (not (and ($listp k) ($listp n) ($listp x))) (/= ($length k) ($length n)) (/= ($length n) ($length x)))
(merror "Each argument to multibernstein_poly must be an equal length list"))
(muln (mapcar #'(lambda (a b z) (opcons '%bernstein_poly a b z)) (margs k) (margs n) (margs x)) t)))
(setf (get '%multibernstein_poly 'operators) #'multi-bernstein-poly-simp)
| null | https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/share/bernstein/bernstein.lisp | lisp | Copyright (C) 2011,2021 Barton Willis
This program is free software; you can redistribute it and/or modify
either version 2 of the License , or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
When bernstein_explicit is non-nil, bernstein_poly(k,n,x) simplifies to
binomial(n,k) * x^k (1-x)^(n-k) regardless of the values of k or n; | Author
University of Nebraska at Kearney
it under the terms of the GNU General Public License as published by
(in-package :maxima)
($load "bernstein_utilities.mac")
(defmvar $bernstein_explicit nil)
numerical ( complex rational , float , or big float ) evaluation of polynomials
(in-package #-gcl #:bigfloat #+gcl "BIGFLOAT")
(defun bernstein-poly (k n x)
(* (to (maxima::opcons 'maxima::%binomial n k)) (expt x k) (expt (- 1 x) (- n k))))
(in-package :maxima)
(defun $bernstein_poly (k n x) (simplify (list '(%bernstein_poly) k n x)))
(defprop $bernstein_poly %bernstein_poly alias)
(defprop $bernstein_poly %bernstein_poly verb)
(defprop %bernstein_poly $bernstein_poly reversealias)
(defprop %bernstein_poly $bernstein_poly noun)
(setf (get '%bernstein_poly 'conjugate-function)
#'(lambda (e)
(let ((k (car e))
(n (cadr e))
(x (caddr e)))
(if (and ($featurep k '$integer) ($featurep n '$integer))
(opcons '%bernstein_poly k n (opcons '$conjugate x))
(list (list '$conjugate 'simp) (take '(%bernstein_poly) k n x))))))
integrate(bernstein_poly(k , n , ) = hypergeometric([k+1,k - n],[k+2],x)*x^(k+1)/(k+1 )
(defun bernstein-integral (k n x)
(div
(mul
(opcons '%binomial n k)
(opcons 'mexpt x (add 1 k))
(opcons '$hypergeometric
(opcons 'mlist (add 1 k) (sub k n))
(opcons 'mlist (add 2 k))
x))
(add 1 k)))
(putprop '%bernstein_poly `((k n x) nil nil ,#'bernstein-integral) 'integral)
(putprop '$bernstein_poly `((k n x) nil nil ,#'bernstein-integral) 'integral)
(defun bernstein-poly-simp (e y z)
(declare (ignore y))
(let* ((fn (car (pop e)))
(k (if (consp e) (simpcheck (pop e) z) (wna-err fn)))
(n (if (consp e) (simpcheck (pop e) z) (wna-err fn)))
(x (if (consp e) (simpcheck (pop e) z) (wna-err fn))))
(if (consp e) (wna-err fn))
(cond ((and (integerp k) (integerp n) (>= k 0) (>= n k)
(complex-number-p x #'(lambda (s) (or (integerp s) ($ratnump s) (floatp s) ($bfloatp s)))))
(maxima::to (bigfloat::bernstein-poly (bigfloat::to k) (bigfloat::to n) (bigfloat::to x))))
((zerop1 x) (opcons '%kron_delta k 0))
((onep1 x) (opcons '%kron_delta k n))
((or $bernstein_explicit (and (integerp k) (integerp n)))
(if (and (integerp k) (integerp n) (or (< k 0) (> k n))) (mul 0 x)
(mul (opcons '%binomial n k) (opcons 'mexpt x k) (opcons 'mexpt (sub 1 x) (sub n k)))))
(t (list (list fn 'simp) k n x)))))
(setf (get '%bernstein_poly 'operators) #'bernstein-poly-simp)
(defprop %bernstein_poly
((k n x)
((mtimes) ((%bernstein_poly) k n x)
((mplus)
((mtimes) -1
((mqapply) (($psi array) 0) ((mplus) 1 k)))
((mqapply) (($psi array) 0)
((mplus) 1 ((mtimes) -1 k) n))
((mtimes) -1
((%log) ((mplus) 1 ((mtimes) -1 x))))
((%log) x)))
((mtimes)((%bernstein_poly) k n x)
((mplus)
((mqapply) (($psi array) 0) ((mplus) 1 n))
((mtimes) -1
((mqapply) (($psi array) 0)
((mplus) 1 ((mtimes) -1 k) n)))
((%log) ((mplus) 1 ((mtimes) -1 x)))))
((mtimes)
((mplus)
((%bernstein_poly) ((mplus) -1 k) ((mplus) -1 n) x)
((mtimes) -1
((%bernstein_poly) k ((mplus) -1 n) x))) n))
grad)
(defun $bernstein_approx (e vars n)
(if (not ($listp vars)) (merror "The second argument to bernstein_approx must be a list"))
(setq vars (margs vars))
(if (some #'(lambda (s) (not ($mapatom s))) vars)
(merror "The second argument to bernstein_approx must be a list of atoms"))
(if (or (not (integerp n)) (< n 1)) (merror "The third argument to bernstein_approx must be a positive integer"))
(let* ((k (length vars))
(d (make-list k :initial-element 0))
(nn (make-list k :initial-element n))
(carry) (acc 0) (m) (x))
(setq m (expt (+ n 1) k))
(setq nn (cons '(mlist) nn))
(dotimes (i m)
(setq acc (add acc
(mul
(opcons '%multibernstein_poly (cons '(mlist) d) nn (cons '(mlist) vars))
($substitute (cons '(mlist) (mapcar #'(lambda (s x) (opcons 'mequal x (div s n))) d vars)) e))))
(setq carry 1)
(dotimes (j k)
(setq x (+ carry (nth j d)))
(if (> x n) (setq x 0 carry 1) (setq carry 0))
(setf (nth j d) x)))
acc))
(defun $multibernstein_poly (k n x) (simplify (list '(%multibernstein_poly) k n x)))
(defprop $multibernstein_poly %multibernstein_poly alias)
(defprop $multibernstein_poly %multibernstein_poly verb)
(defprop %multibernstein_poly $multibernstein_poly reversealias)
(defprop %multibernstein_poly $multibernstein_poly noun)
(defun multi-bernstein-poly-simp (e y z)
(declare (ignore y))
(let*
((fn (car (pop e)))
(k (if (consp e) (simpcheck (pop e) z) (wna-err fn)))
(n (if (consp e) (simpcheck (pop e) z) (wna-err fn)))
(x (if (consp e) (simpcheck (pop e) z) (wna-err fn))))
(if (consp e) (wna-err fn))
(if (or (not (and ($listp k) ($listp n) ($listp x))) (/= ($length k) ($length n)) (/= ($length n) ($length x)))
(merror "Each argument to multibernstein_poly must be an equal length list"))
(muln (mapcar #'(lambda (a b z) (opcons '%bernstein_poly a b z)) (margs k) (margs n) (margs x)) t)))
(setf (get '%multibernstein_poly 'operators) #'multi-bernstein-poly-simp)
|
b1148eb22c268e600c96a59d40b7f47acd89b24510f867a5418c07d57b4f5731 | barrucadu/hledger-scripts | hledger-to-influxdb.hs | #!/usr/bin/env stack
stack script
--nix --no - nix - pure --nix - packages zlib
--resolver lts-16.16
--package containers , Decimal , , influxdb , text , time
--nix --no-nix-pure --nix-packages zlib
--resolver lts-16.16
--package containers,Decimal,hledger-lib,influxdb,text,time
-}
# OPTIONS_GHC -Wall #
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Control.Arrow ((***), second)
import Data.Decimal (Decimal)
import Data.Foldable (for_)
import Data.Function (on)
import Data.List (foldl', inits, mapAccumL, nub, sortOn)
import Data.List.NonEmpty (NonEmpty(..), groupBy)
import qualified Data.Map as M
import Data.String (IsString, fromString)
import qualified Data.Text as T
import Data.Time.Calendar (Day, addDays, toGregorian, fromGregorian)
import Data.Time.Clock (UTCTime (..))
import Database.InfluxDB as I
import Hledger.Data.Types as H
import Hledger.Read as H
main :: IO ()
main = do
measurements <- toMeasurements <$> H.defaultJournal
for_ measurements (uncurry writeMeasurement)
writeMeasurement :: T.Text -> [I.Line UTCTime] -> IO ()
writeMeasurement name ms = do
putStrLn (T.unpack name <> " (" <> show (length ms) <> " measurements)")
for_ (zip [1..] chunks) $ \(i, chunk) -> do
putStrLn (" " <> show i <> " / " <> show numChunks)
I.writeBatch (I.writeParams "finance") chunk
where
chunks = chunksOf chunkSize ms
numChunks = length chunks
chunkSize = 200 -- picked by trial and error, needs shrinking occasionally
toMeasurements :: H.Journal -> [(T.Text, [I.Line UTCTime])]
toMeasurements journal =
[ ("Normal-value daily aggregate transactions", measurements nvalue dailies)
, ("Cost-value daily aggregate transactions", measurements cvalue dailies)
, ("Market-value daily aggregate transactions", measurements mvalue dailies)
, ("Normal-value period aggregate transactions", measurements (periodToInflux marketValues) periods)
, ("Counts", measurements countToInflux txns)
, ("Commodities", measurements priceToInflux prices)
]
where
marketValues = marketValue (buildPrices prices)
nvalue = balancesToInflux normalValue "normal"
cvalue = balancesToInflux costValue "cost"
mvalue = toInflux accountKey marketValues (toValueDeltas normalValue) "market"
one transaction per day , with empty days getting an empty transaction
dailies :: [H.Transaction]
dailies =
let allTxns = sortOn H.tdate (txns ++ emptyTransactionsFromTo startDate endDate)
squish ts@(t:|_) = t { H.tpostings = concatMap H.tpostings ts }
in map squish (groupBy ((==) `on` H.tdate) allTxns)
-- transactions grouped by period, excluding the final period
periods :: [NonEmpty H.Transaction]
periods = init $ groupBy ((==) `on` (periodOf . H.tdate)) txns
-- this isn't just `map` as it includes all accounts in all
-- measurements - even those from before the account existed (with a
value of 0 )
measurements toL xs =
let go start = mapAccumL toL start xs
initialAccounts = M.map (const 0) (fst (go M.empty))
in snd (go initialAccounts)
balancesToInflux = toInflux accountKey (\_ ac q -> [(ac, q)]) . toValueDeltas
countToInflux =
let toCount txn =
[ (showStatus status, if H.tstatus txn == status then 1 else 0)
| status <- [minBound .. maxBound]
]
in toInflux fromText (\_ ac q -> [(ac, q)]) toCount "count"
startDate, endDate :: Day
startDate = H.tdate (head txns)
endDate = H.tdate (last txns)
txns :: [H.Transaction]
txns = sortOn H.tdate (H.jtxns journal)
prices :: [H.PriceDirective]
prices = H.jpricedirectives journal
toInflux
:: Ord k
=> (k -> I.Key)
-> (Day -> k -> Decimal -> [(k, Decimal)])
-> (H.Transaction -> [(k, Decimal)])
-> I.Measurement
-> M.Map k Decimal
-> H.Transaction
-> (M.Map k Decimal, I.Line UTCTime)
toInflux toKey transform deltaf key state txn =
(state', Line key M.empty fields (Just time))
where
time = UTCTime (H.tdate txn) 0
fields = toFields state'
state' = M.unionWith (+) state deltas
deltas = M.fromList (deltaf txn)
toFields =
M.fromList
. map (toKey *** (I.FieldFloat . doub))
. sumSame
. concatMap (uncurry (transform (H.tdate txn)))
. M.toList
priceToInflux
:: M.Map (H.CommoditySymbol, H.CommoditySymbol) Decimal
-> H.PriceDirective
-> ( M.Map (H.CommoditySymbol, H.CommoditySymbol) Decimal
, I.Line UTCTime
)
priceToInflux state (H.PriceDirective day c (H.Amount c' q' _ _ _)) =
(state', Line "commodities" M.empty fields (Just (UTCTime day 0)))
where
fields = toFields state'
state' = M.insert (c, c') q' state
toFields = M.fromList . map (priceKey *** (I.FieldFloat . doub)) . M.toList
-- note: this doesn't count (eg) the "income" generated by taking out
-- a loan, or the "expense" incurred in paying a part of it back; it's
-- purely transactions which touch `income:` and `expenses:`
periodToInflux
:: (Day -> (AccountName, CommoditySymbol) -> Decimal -> [((AccountName, CommoditySymbol), Decimal)])
-> s
-> NonEmpty H.Transaction
-> (s, I.Line UTCTime)
periodToInflux marketValues s (t:|ts) = (s, Line "period" M.empty fields (Just time))
where
time = UTCTime (periodOf (H.tdate t)) 0
fields = toFields $ foldl' toPeriodDelta M.empty (t:ts)
toFields = M.fromList . map (accountKey *** (I.FieldFloat . doub)) . M.toList
toPeriodDelta :: M.Map (H.AccountName, H.CommoditySymbol) Decimal -> H.Transaction -> M.Map (H.AccountName, H.CommoditySymbol) Decimal
toPeriodDelta acc txn =
let deltas :: [((AccountName, CommoditySymbol), Decimal)]
deltas = concatMap (\(ac,q) -> marketValues (H.tdate txn) ac q) (toValueDeltas normalValue txn)
incomeDeltas = deltasFor "income" deltas
allAssetsDeltas = deltasFor "assets" deltas
allExpensesDeltas = deltasFor "expenses" deltas
grossExpensesDeltas = deltasFor "expenses:gross" deltas
zero assetsDeltas if incomeDeltas are missing ( i.e. only count income )
assetsDeltas = if null incomeDeltas then [] else allAssetsDeltas
-- subtract expenses:gross from expenses (i.e. only count post-tax expenses)
expensesDeltas = sumSame (allExpensesDeltas ++ map (\((_,c),v) -> (("expenses",c),-v)) grossExpensesDeltas)
in M.unionWith (+) acc . M.fromList $ assetsDeltas ++ expensesDeltas
deltasFor a0 = filter $ \((a,_),_) -> a == a0
toValueDeltas
:: (H.MixedAmount -> [(H.CommoditySymbol, Decimal)])
-> H.Transaction
-> [((H.AccountName, H.CommoditySymbol), Decimal)]
toValueDeltas getValue txn =
let postings = concatMap explodeAccount (H.tpostings txn)
accounts = nub (map H.paccount postings)
in [ ((a, cur), val)
| a <- accounts
, let ps = filter ((== a) . H.paccount) postings
, (cur, val) <- sumSame (concatMap (getValue . H.pamount) ps)
]
showStatus :: H.Status -> T.Text
showStatus H.Cleared = "cleared"
showStatus H.Pending = "pending"
showStatus H.Unmarked = "uncleared"
accountKey :: (H.AccountName, H.CommoditySymbol) -> I.Key
accountKey (a, c) = fromText $ a <> "[" <> c <> "]"
priceKey :: (H.CommoditySymbol, H.CommoditySymbol) -> I.Key
priceKey (c, c') = fromText $ c <> "[" <> c' <> "]"
-------------------------------------------------------------------------------
-- * Amounts
-- | The \"normal\" value of an amount: the main commodity.
normalValue :: H.MixedAmount -> [(H.CommoditySymbol, Decimal)]
normalValue (H.Mixed amounts) = map go amounts
where go (H.Amount c q _ _ _) = (c, q)
| The \"cost\ " value of an amount : the bit after the \"@\ " or
-- \"@@\" (if given), or the normal amount otherwise.
costValue :: H.MixedAmount -> [(H.CommoditySymbol, Decimal)]
costValue (H.Mixed amounts) = map go amounts
where
go (H.Amount _ q _ _ (Just (H.UnitPrice a))) = second (* q) (go a)
go (H.Amount _ q _ _ (Just (H.TotalPrice a))) = second (* signum q) (go a)
go (H.Amount c q _ _ _) = (c, q)
| The \"market\ " value of an amount , as of a given day .
--
-- Unlike 'normalValue' and 'costValue', this takes a single commodity
-- rather than a 'H.MixedAmount'.
marketValue
:: [(Day, Graph H.CommoditySymbol Decimal)]
-> Day
-> (H.AccountName, H.CommoditySymbol)
-> Decimal
-> [((H.AccountName, H.CommoditySymbol), Decimal)]
marketValue prices day (a, c) q =
[ ((a, c'), factor * q) | (c', factor) <- factors ]
where
factors = case map snd . dropWhile ((> day) . fst) $ prices of
(g:_) -> findFactors c g
[] -> [(c, 1)]
-------------------------------------------------------------------------------
-- * Exchange rates
-- | Build a set of exchange rate graphs.
buildPrices :: [H.PriceDirective] -> [(Day, Graph H.CommoditySymbol Decimal)]
buildPrices prices0 =
reverse . map (second close) . graphs empty . sortOn fst $ prices
where
prices = [ (d, (c, c', q)) | H.PriceDirective d c (H.Amount c' q _ _ _) <- prices0 ]
graphs g ((day, (c, c', q)):rest) =
let g' = addEdge const c c' q . addNode c' . addNode c $ g
in case rest of
((day', _):_) | day == day' -> graphs g' rest
_ -> (day, g') : graphs g' rest
graphs _ [] = []
close =
transitiveClosure (*) . symmetricClosure (1 /) . reflexiveClosure 1
-- | Find all the exchange rates for a commodity.
findFactors
:: H.CommoditySymbol
-> Graph H.CommoditySymbol Decimal
-> [(H.CommoditySymbol, Decimal)]
findFactors c = M.assocs . M.findWithDefault (M.singleton c 1) c
-------------------------------------------------------------------------------
-- * Miscellaneous
| Explode one posting into one posting per account .
--
eg , a posting involving " assets : cash " produces two postings , one
-- involving "assets:cash" and the other involving "assests".
explodeAccount :: H.Posting -> [H.Posting]
explodeAccount p =
[ p { H.paccount = a }
| a <- tail . map (T.intercalate ":") . inits . T.splitOn ":" $ H.paccount p
]
| Take a list of pairs , group by first element , and sum second
elements . The pairs in the result list all have unique first
-- elements.
sumSame :: (Ord k, Num v) => [(k, v)] -> [(k, v)]
sumSame = go . sortOn fst
where
go ((k1, v1):(k2, v2):rest) | k1 == k2 = go ((k1, v1 + v2) : rest)
| otherwise = (k1, v1) : go ((k2, v2) : rest)
go xs = xs
-- | Convert a 'Decimal' to a 'Double'.
doub :: Decimal -> Double
doub = fromRational . toRational
-- | Convert a @Text@ to a string-like thing.
fromText :: IsString s => T.Text -> s
fromText = fromString . T.unpack
-- | Split a list unto chunks
chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf n xs = take n xs : chunksOf n (drop n xs)
-- | Get the period date of a 'Day'
periodOf :: Day -> Day
periodOf day =
let (y, m, _) = toGregorian day
in fromGregorian y m 15
| Empty transactions from YYYY-01 - 01 up to the given day
emptyTransactionsFromTo :: Day -> Day -> [H.Transaction]
emptyTransactionsFromTo start0 end = go start
where
year = (\(y,_,_) -> y) (toGregorian start0)
start = fromGregorian year 1 1
go d = txn d : if d < end then go (addDays 1 d) else []
txn d = H.Transaction 0 "" (H.GenericSourcePos "" 0 0) d Nothing H.Unmarked "" "" "" [] []
-------------------------------------------------------------------------------
-- * Graph utilities
| A directed graph with nodes of type @n@ and edge labels of type
-- @l@. Parallel edges are not allowed.
type Graph n l = M.Map n (M.Map n l)
-- | A graph with no nodes or edges.
empty :: Ord n => Graph n l
empty = M.empty
-- | Add a node to a graph, if not already present.
addNode :: Ord n => n -> Graph n l -> Graph n l
addNode n = M.insertWith (\_ old -> old) n M.empty
-- | Add an edge to a graph, combining edges if they exist.
--
-- If the source node doesn't exist, does not change the graph.
addEdge
:: Ord n
=> (l -> l -> l) -- ^ Function to combine edge labels.
-> n -- ^ Source node.
-> n -- ^ Target node.
-> l -- ^ New label.
-> Graph n l
-> Graph n l
addEdge combine from to label graph = case M.lookup from graph of
Just edges ->
let edges' = M.insertWith combine to label edges
in M.insert from edges' graph
Nothing -> graph
-- | Take the reflexive closure by adding edges with the given label
-- where missing.
reflexiveClosure :: Ord n => l -> Graph n l -> Graph n l
reflexiveClosure label graph = foldr
(.)
id
[ addEdge (\_ old -> old) nA nA label | nA <- M.keys graph ]
graph
-- | Take the symmetric closure by adding new edges, transforming
-- existing labels.
symmetricClosure :: Ord n => (l -> l) -> Graph n l -> Graph n l
symmetricClosure mk graph = foldr
(.)
id
[ addEdge (\_ old -> old) nB nA (mk lAB)
| (nA, edges) <- M.assocs graph
, (nB, lAB ) <- M.assocs edges
]
graph
-- | Take the transitive closure by adding new edges, combining
-- existing labels.
transitiveClosure :: (Ord n, Eq l) => (l -> l -> l) -> Graph n l -> Graph n l
transitiveClosure combine = fixEq step
where
fixEq f = find . iterate f
where
find (a1:a2:as) | a1 == a2 = a1
| otherwise = find (a2 : as)
find _ = error "unreachable"
step graph = foldr
(.)
id
[ addEdge (\_ old -> old) nA nC (combine lAB lBC)
| (nA, edges) <- M.assocs graph
, (nB, lAB ) <- M.assocs edges
, (nC, lBC ) <- M.assocs (M.findWithDefault M.empty nB graph)
]
graph
| null | https://raw.githubusercontent.com/barrucadu/hledger-scripts/7a9084d60071355436eb6c3b3a2622153c35a88e/hledger-to-influxdb.hs | haskell | nix --no - nix - pure --nix - packages zlib
resolver lts-16.16
package containers , Decimal , , influxdb , text , time
nix --no-nix-pure --nix-packages zlib
resolver lts-16.16
package containers,Decimal,hledger-lib,influxdb,text,time
# LANGUAGE OverloadedStrings #
picked by trial and error, needs shrinking occasionally
transactions grouped by period, excluding the final period
this isn't just `map` as it includes all accounts in all
measurements - even those from before the account existed (with a
note: this doesn't count (eg) the "income" generated by taking out
a loan, or the "expense" incurred in paying a part of it back; it's
purely transactions which touch `income:` and `expenses:`
subtract expenses:gross from expenses (i.e. only count post-tax expenses)
-----------------------------------------------------------------------------
* Amounts
| The \"normal\" value of an amount: the main commodity.
\"@@\" (if given), or the normal amount otherwise.
Unlike 'normalValue' and 'costValue', this takes a single commodity
rather than a 'H.MixedAmount'.
-----------------------------------------------------------------------------
* Exchange rates
| Build a set of exchange rate graphs.
| Find all the exchange rates for a commodity.
-----------------------------------------------------------------------------
* Miscellaneous
involving "assets:cash" and the other involving "assests".
elements.
| Convert a 'Decimal' to a 'Double'.
| Convert a @Text@ to a string-like thing.
| Split a list unto chunks
| Get the period date of a 'Day'
-----------------------------------------------------------------------------
* Graph utilities
@l@. Parallel edges are not allowed.
| A graph with no nodes or edges.
| Add a node to a graph, if not already present.
| Add an edge to a graph, combining edges if they exist.
If the source node doesn't exist, does not change the graph.
^ Function to combine edge labels.
^ Source node.
^ Target node.
^ New label.
| Take the reflexive closure by adding edges with the given label
where missing.
| Take the symmetric closure by adding new edges, transforming
existing labels.
| Take the transitive closure by adding new edges, combining
existing labels. | #!/usr/bin/env stack
stack script
-}
# OPTIONS_GHC -Wall #
module Main (main) where
import Control.Arrow ((***), second)
import Data.Decimal (Decimal)
import Data.Foldable (for_)
import Data.Function (on)
import Data.List (foldl', inits, mapAccumL, nub, sortOn)
import Data.List.NonEmpty (NonEmpty(..), groupBy)
import qualified Data.Map as M
import Data.String (IsString, fromString)
import qualified Data.Text as T
import Data.Time.Calendar (Day, addDays, toGregorian, fromGregorian)
import Data.Time.Clock (UTCTime (..))
import Database.InfluxDB as I
import Hledger.Data.Types as H
import Hledger.Read as H
main :: IO ()
main = do
measurements <- toMeasurements <$> H.defaultJournal
for_ measurements (uncurry writeMeasurement)
writeMeasurement :: T.Text -> [I.Line UTCTime] -> IO ()
writeMeasurement name ms = do
putStrLn (T.unpack name <> " (" <> show (length ms) <> " measurements)")
for_ (zip [1..] chunks) $ \(i, chunk) -> do
putStrLn (" " <> show i <> " / " <> show numChunks)
I.writeBatch (I.writeParams "finance") chunk
where
chunks = chunksOf chunkSize ms
numChunks = length chunks
toMeasurements :: H.Journal -> [(T.Text, [I.Line UTCTime])]
toMeasurements journal =
[ ("Normal-value daily aggregate transactions", measurements nvalue dailies)
, ("Cost-value daily aggregate transactions", measurements cvalue dailies)
, ("Market-value daily aggregate transactions", measurements mvalue dailies)
, ("Normal-value period aggregate transactions", measurements (periodToInflux marketValues) periods)
, ("Counts", measurements countToInflux txns)
, ("Commodities", measurements priceToInflux prices)
]
where
marketValues = marketValue (buildPrices prices)
nvalue = balancesToInflux normalValue "normal"
cvalue = balancesToInflux costValue "cost"
mvalue = toInflux accountKey marketValues (toValueDeltas normalValue) "market"
one transaction per day , with empty days getting an empty transaction
dailies :: [H.Transaction]
dailies =
let allTxns = sortOn H.tdate (txns ++ emptyTransactionsFromTo startDate endDate)
squish ts@(t:|_) = t { H.tpostings = concatMap H.tpostings ts }
in map squish (groupBy ((==) `on` H.tdate) allTxns)
periods :: [NonEmpty H.Transaction]
periods = init $ groupBy ((==) `on` (periodOf . H.tdate)) txns
value of 0 )
measurements toL xs =
let go start = mapAccumL toL start xs
initialAccounts = M.map (const 0) (fst (go M.empty))
in snd (go initialAccounts)
balancesToInflux = toInflux accountKey (\_ ac q -> [(ac, q)]) . toValueDeltas
countToInflux =
let toCount txn =
[ (showStatus status, if H.tstatus txn == status then 1 else 0)
| status <- [minBound .. maxBound]
]
in toInflux fromText (\_ ac q -> [(ac, q)]) toCount "count"
startDate, endDate :: Day
startDate = H.tdate (head txns)
endDate = H.tdate (last txns)
txns :: [H.Transaction]
txns = sortOn H.tdate (H.jtxns journal)
prices :: [H.PriceDirective]
prices = H.jpricedirectives journal
toInflux
:: Ord k
=> (k -> I.Key)
-> (Day -> k -> Decimal -> [(k, Decimal)])
-> (H.Transaction -> [(k, Decimal)])
-> I.Measurement
-> M.Map k Decimal
-> H.Transaction
-> (M.Map k Decimal, I.Line UTCTime)
toInflux toKey transform deltaf key state txn =
(state', Line key M.empty fields (Just time))
where
time = UTCTime (H.tdate txn) 0
fields = toFields state'
state' = M.unionWith (+) state deltas
deltas = M.fromList (deltaf txn)
toFields =
M.fromList
. map (toKey *** (I.FieldFloat . doub))
. sumSame
. concatMap (uncurry (transform (H.tdate txn)))
. M.toList
priceToInflux
:: M.Map (H.CommoditySymbol, H.CommoditySymbol) Decimal
-> H.PriceDirective
-> ( M.Map (H.CommoditySymbol, H.CommoditySymbol) Decimal
, I.Line UTCTime
)
priceToInflux state (H.PriceDirective day c (H.Amount c' q' _ _ _)) =
(state', Line "commodities" M.empty fields (Just (UTCTime day 0)))
where
fields = toFields state'
state' = M.insert (c, c') q' state
toFields = M.fromList . map (priceKey *** (I.FieldFloat . doub)) . M.toList
periodToInflux
:: (Day -> (AccountName, CommoditySymbol) -> Decimal -> [((AccountName, CommoditySymbol), Decimal)])
-> s
-> NonEmpty H.Transaction
-> (s, I.Line UTCTime)
periodToInflux marketValues s (t:|ts) = (s, Line "period" M.empty fields (Just time))
where
time = UTCTime (periodOf (H.tdate t)) 0
fields = toFields $ foldl' toPeriodDelta M.empty (t:ts)
toFields = M.fromList . map (accountKey *** (I.FieldFloat . doub)) . M.toList
toPeriodDelta :: M.Map (H.AccountName, H.CommoditySymbol) Decimal -> H.Transaction -> M.Map (H.AccountName, H.CommoditySymbol) Decimal
toPeriodDelta acc txn =
let deltas :: [((AccountName, CommoditySymbol), Decimal)]
deltas = concatMap (\(ac,q) -> marketValues (H.tdate txn) ac q) (toValueDeltas normalValue txn)
incomeDeltas = deltasFor "income" deltas
allAssetsDeltas = deltasFor "assets" deltas
allExpensesDeltas = deltasFor "expenses" deltas
grossExpensesDeltas = deltasFor "expenses:gross" deltas
zero assetsDeltas if incomeDeltas are missing ( i.e. only count income )
assetsDeltas = if null incomeDeltas then [] else allAssetsDeltas
expensesDeltas = sumSame (allExpensesDeltas ++ map (\((_,c),v) -> (("expenses",c),-v)) grossExpensesDeltas)
in M.unionWith (+) acc . M.fromList $ assetsDeltas ++ expensesDeltas
deltasFor a0 = filter $ \((a,_),_) -> a == a0
toValueDeltas
:: (H.MixedAmount -> [(H.CommoditySymbol, Decimal)])
-> H.Transaction
-> [((H.AccountName, H.CommoditySymbol), Decimal)]
toValueDeltas getValue txn =
let postings = concatMap explodeAccount (H.tpostings txn)
accounts = nub (map H.paccount postings)
in [ ((a, cur), val)
| a <- accounts
, let ps = filter ((== a) . H.paccount) postings
, (cur, val) <- sumSame (concatMap (getValue . H.pamount) ps)
]
showStatus :: H.Status -> T.Text
showStatus H.Cleared = "cleared"
showStatus H.Pending = "pending"
showStatus H.Unmarked = "uncleared"
accountKey :: (H.AccountName, H.CommoditySymbol) -> I.Key
accountKey (a, c) = fromText $ a <> "[" <> c <> "]"
priceKey :: (H.CommoditySymbol, H.CommoditySymbol) -> I.Key
priceKey (c, c') = fromText $ c <> "[" <> c' <> "]"
normalValue :: H.MixedAmount -> [(H.CommoditySymbol, Decimal)]
normalValue (H.Mixed amounts) = map go amounts
where go (H.Amount c q _ _ _) = (c, q)
| The \"cost\ " value of an amount : the bit after the \"@\ " or
costValue :: H.MixedAmount -> [(H.CommoditySymbol, Decimal)]
costValue (H.Mixed amounts) = map go amounts
where
go (H.Amount _ q _ _ (Just (H.UnitPrice a))) = second (* q) (go a)
go (H.Amount _ q _ _ (Just (H.TotalPrice a))) = second (* signum q) (go a)
go (H.Amount c q _ _ _) = (c, q)
| The \"market\ " value of an amount , as of a given day .
marketValue
:: [(Day, Graph H.CommoditySymbol Decimal)]
-> Day
-> (H.AccountName, H.CommoditySymbol)
-> Decimal
-> [((H.AccountName, H.CommoditySymbol), Decimal)]
marketValue prices day (a, c) q =
[ ((a, c'), factor * q) | (c', factor) <- factors ]
where
factors = case map snd . dropWhile ((> day) . fst) $ prices of
(g:_) -> findFactors c g
[] -> [(c, 1)]
buildPrices :: [H.PriceDirective] -> [(Day, Graph H.CommoditySymbol Decimal)]
buildPrices prices0 =
reverse . map (second close) . graphs empty . sortOn fst $ prices
where
prices = [ (d, (c, c', q)) | H.PriceDirective d c (H.Amount c' q _ _ _) <- prices0 ]
graphs g ((day, (c, c', q)):rest) =
let g' = addEdge const c c' q . addNode c' . addNode c $ g
in case rest of
((day', _):_) | day == day' -> graphs g' rest
_ -> (day, g') : graphs g' rest
graphs _ [] = []
close =
transitiveClosure (*) . symmetricClosure (1 /) . reflexiveClosure 1
findFactors
:: H.CommoditySymbol
-> Graph H.CommoditySymbol Decimal
-> [(H.CommoditySymbol, Decimal)]
findFactors c = M.assocs . M.findWithDefault (M.singleton c 1) c
| Explode one posting into one posting per account .
eg , a posting involving " assets : cash " produces two postings , one
explodeAccount :: H.Posting -> [H.Posting]
explodeAccount p =
[ p { H.paccount = a }
| a <- tail . map (T.intercalate ":") . inits . T.splitOn ":" $ H.paccount p
]
| Take a list of pairs , group by first element , and sum second
elements . The pairs in the result list all have unique first
sumSame :: (Ord k, Num v) => [(k, v)] -> [(k, v)]
sumSame = go . sortOn fst
where
go ((k1, v1):(k2, v2):rest) | k1 == k2 = go ((k1, v1 + v2) : rest)
| otherwise = (k1, v1) : go ((k2, v2) : rest)
go xs = xs
doub :: Decimal -> Double
doub = fromRational . toRational
fromText :: IsString s => T.Text -> s
fromText = fromString . T.unpack
chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf n xs = take n xs : chunksOf n (drop n xs)
periodOf :: Day -> Day
periodOf day =
let (y, m, _) = toGregorian day
in fromGregorian y m 15
| Empty transactions from YYYY-01 - 01 up to the given day
emptyTransactionsFromTo :: Day -> Day -> [H.Transaction]
emptyTransactionsFromTo start0 end = go start
where
year = (\(y,_,_) -> y) (toGregorian start0)
start = fromGregorian year 1 1
go d = txn d : if d < end then go (addDays 1 d) else []
txn d = H.Transaction 0 "" (H.GenericSourcePos "" 0 0) d Nothing H.Unmarked "" "" "" [] []
| A directed graph with nodes of type @n@ and edge labels of type
type Graph n l = M.Map n (M.Map n l)
empty :: Ord n => Graph n l
empty = M.empty
addNode :: Ord n => n -> Graph n l -> Graph n l
addNode n = M.insertWith (\_ old -> old) n M.empty
addEdge
:: Ord n
-> Graph n l
-> Graph n l
addEdge combine from to label graph = case M.lookup from graph of
Just edges ->
let edges' = M.insertWith combine to label edges
in M.insert from edges' graph
Nothing -> graph
reflexiveClosure :: Ord n => l -> Graph n l -> Graph n l
reflexiveClosure label graph = foldr
(.)
id
[ addEdge (\_ old -> old) nA nA label | nA <- M.keys graph ]
graph
symmetricClosure :: Ord n => (l -> l) -> Graph n l -> Graph n l
symmetricClosure mk graph = foldr
(.)
id
[ addEdge (\_ old -> old) nB nA (mk lAB)
| (nA, edges) <- M.assocs graph
, (nB, lAB ) <- M.assocs edges
]
graph
transitiveClosure :: (Ord n, Eq l) => (l -> l -> l) -> Graph n l -> Graph n l
transitiveClosure combine = fixEq step
where
fixEq f = find . iterate f
where
find (a1:a2:as) | a1 == a2 = a1
| otherwise = find (a2 : as)
find _ = error "unreachable"
step graph = foldr
(.)
id
[ addEdge (\_ old -> old) nA nC (combine lAB lBC)
| (nA, edges) <- M.assocs graph
, (nB, lAB ) <- M.assocs edges
, (nC, lBC ) <- M.assocs (M.findWithDefault M.empty nB graph)
]
graph
|
b73d6f063e60cda2335ab12a31638d8b85db9213b776dc6e0240b6df4defddcd | joinr/clclojure | evaltest.lisp | ;;quick test to see if we get compiler support for our
;;eval hack...
(ql:quickload :cl-package-locks)
(load "eval.lisp")
(defstruct blah (x))
(defparameter b (make-blah :x 2))
(defmethod clclojure.eval:custom-eval
((obj blah))
(list :this-is-custom (blah-x obj)))
(clclojure.eval:enable-custom-eval)
(defparameter custom (eval b))
;;(:THIS-IS-CUSTOM 2)
(clclojure.eval:disable-custom-eval)
(defparameter normal (eval b))
# S(BLAH :X 2 )
| null | https://raw.githubusercontent.com/joinr/clclojure/8b51214891c4da6dfbec393dffac70846ee1d0c5/tests/evaltest.lisp | lisp | quick test to see if we get compiler support for our
eval hack...
(:THIS-IS-CUSTOM 2) | (ql:quickload :cl-package-locks)
(load "eval.lisp")
(defstruct blah (x))
(defparameter b (make-blah :x 2))
(defmethod clclojure.eval:custom-eval
((obj blah))
(list :this-is-custom (blah-x obj)))
(clclojure.eval:enable-custom-eval)
(defparameter custom (eval b))
(clclojure.eval:disable-custom-eval)
(defparameter normal (eval b))
# S(BLAH :X 2 )
|
bb4fb72501a82d3541399145d673057bef1a173c93c673f0562fbc3c6ed5ff56 | olsner/sedition | RedundantBranches.hs | # LANGUAGE FlexibleInstances , GADTs , TypeFamilies , StandaloneDeriving , CPP , ScopedTypeVariables , FlexibleContexts #
module RedundantBranches (redundantBranchesPass) where
import Compiler.Hoopl as H
-- import Debug.Trace
import IR
type RBFact = WithTopAndBot (Insn O C)
lattice :: DataflowLattice RBFact
lattice = addPoints "Redundant branches" join
where
join _ (OldFact old) (NewFact new)
= if new == old then (NoChange, new)
else (SomeChange, new)
transfer :: BwdTransfer Insn RBFact
transfer = mkBTransfer3 first middle last
where
first :: Insn C O -> RBFact -> RBFact
-- C O
first (Label _) f = f
-- O O
middle :: Insn O O -> RBFact -> RBFact
middle _ _ = Top
-- O C
last :: Insn O C -> FactBase RBFact -> RBFact
last insn _ = PElem insn
rewrite :: FuelMonad m => BwdRewrite m Insn RBFact
rewrite = deepBwdRw rw
where
rw :: FuelMonad m => Insn e x -> Fact x RBFact -> m (Maybe (Graph Insn e x))
-- Do just one change at a time so that optimization fuel applies.
rw i@(If p tl fl) f | Just tl' <- label tl f = rwLast i (If p tl' fl)
| Just fl' <- label fl f = rwLast i (If p tl fl')
-- Branch to an if with the same condition, so we can
skip one step ahead .
| Just (If p' tl' _) <- insn tl f, p == p'
= rwLast i (If p tl' fl)
| Just (If p' _ fl') <- insn fl f, p == p'
= rwLast i (If p tl fl')
rw i@(Fork l1 l2) f | Just l1' <- label l1 f = rwLast i (Fork l1' l2)
| Just l2' <- label l2 f = rwLast i (Fork l1 l2')
rw i@(Branch t) f = rwInsn i t f
rw _ _ = return Nothing
rwLast :: FuelMonad m => Insn O C -> Insn O C -> m (Maybe (Graph Insn O C))
rwLast _old new = return (Just (mkLast new))
rwInsn old l f | Just i <- insn l f = rwLast old i
| otherwise = return Nothing
insn l f | Just (PElem i) <- mapLookup l f = Just i
| otherwise = Nothing
label :: Label -> FactBase RBFact -> Maybe Label
label l f | Just (PElem (Branch l')) <- mapLookup l f = Just l'
| otherwise = Nothing
simplifySameIfs :: FuelMonad m => BwdRewrite m Insn RBFact
simplifySameIfs = deepBwdRw rw
where
rw :: FuelMonad m => Insn e x -> Fact x RBFact -> m (Maybe (Graph Insn e x))
rw (If _ tl fl) _ | tl == fl = return (Just (mkLast (Branch tl)))
rw _ _ = return Nothing
redundantBranchesPass :: FuelMonad m => BwdPass m Insn RBFact
redundantBranchesPass = BwdPass
{ bp_lattice = lattice
, bp_transfer = transfer
, bp_rewrite = rewrite `thenBwdRw` simplifySameIfs }
| null | https://raw.githubusercontent.com/olsner/sedition/483e283289a84764eec71c39dd66b017b8b00bf8/RedundantBranches.hs | haskell | import Debug.Trace
C O
O O
O C
Do just one change at a time so that optimization fuel applies.
Branch to an if with the same condition, so we can | # LANGUAGE FlexibleInstances , GADTs , TypeFamilies , StandaloneDeriving , CPP , ScopedTypeVariables , FlexibleContexts #
module RedundantBranches (redundantBranchesPass) where
import Compiler.Hoopl as H
import IR
type RBFact = WithTopAndBot (Insn O C)
lattice :: DataflowLattice RBFact
lattice = addPoints "Redundant branches" join
where
join _ (OldFact old) (NewFact new)
= if new == old then (NoChange, new)
else (SomeChange, new)
transfer :: BwdTransfer Insn RBFact
transfer = mkBTransfer3 first middle last
where
first :: Insn C O -> RBFact -> RBFact
first (Label _) f = f
middle :: Insn O O -> RBFact -> RBFact
middle _ _ = Top
last :: Insn O C -> FactBase RBFact -> RBFact
last insn _ = PElem insn
rewrite :: FuelMonad m => BwdRewrite m Insn RBFact
rewrite = deepBwdRw rw
where
rw :: FuelMonad m => Insn e x -> Fact x RBFact -> m (Maybe (Graph Insn e x))
rw i@(If p tl fl) f | Just tl' <- label tl f = rwLast i (If p tl' fl)
| Just fl' <- label fl f = rwLast i (If p tl fl')
skip one step ahead .
| Just (If p' tl' _) <- insn tl f, p == p'
= rwLast i (If p tl' fl)
| Just (If p' _ fl') <- insn fl f, p == p'
= rwLast i (If p tl fl')
rw i@(Fork l1 l2) f | Just l1' <- label l1 f = rwLast i (Fork l1' l2)
| Just l2' <- label l2 f = rwLast i (Fork l1 l2')
rw i@(Branch t) f = rwInsn i t f
rw _ _ = return Nothing
rwLast :: FuelMonad m => Insn O C -> Insn O C -> m (Maybe (Graph Insn O C))
rwLast _old new = return (Just (mkLast new))
rwInsn old l f | Just i <- insn l f = rwLast old i
| otherwise = return Nothing
insn l f | Just (PElem i) <- mapLookup l f = Just i
| otherwise = Nothing
label :: Label -> FactBase RBFact -> Maybe Label
label l f | Just (PElem (Branch l')) <- mapLookup l f = Just l'
| otherwise = Nothing
simplifySameIfs :: FuelMonad m => BwdRewrite m Insn RBFact
simplifySameIfs = deepBwdRw rw
where
rw :: FuelMonad m => Insn e x -> Fact x RBFact -> m (Maybe (Graph Insn e x))
rw (If _ tl fl) _ | tl == fl = return (Just (mkLast (Branch tl)))
rw _ _ = return Nothing
redundantBranchesPass :: FuelMonad m => BwdPass m Insn RBFact
redundantBranchesPass = BwdPass
{ bp_lattice = lattice
, bp_transfer = transfer
, bp_rewrite = rewrite `thenBwdRw` simplifySameIfs }
|
ad37ba1fae8bab6fd6e8295e9f03e9f780fcc4e69ca22bf4f6c5a22675803787 | jepsen-io/jepsen | project.clj | (defproject jepsen "0.3.2-SNAPSHOT"
:description "Distributed systems testing framework."
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.11.1"]
[org.clojure/data.fressian "1.0.0"]
[org.clojure/tools.logging "1.2.4"]
[org.clojure/tools.cli "1.0.214"]
[spootnik/unilog "0.7.31"]
[elle "0.1.6"]
[clj-time "0.15.2"]
[io.jepsen/history "0.1.0"]
[jepsen.txn "0.1.2"]
[knossos "0.3.9"]
[clj-ssh "0.5.14"]
[gnuplot "0.1.3"]
[http-kit "2.6.0"]
[ring "1.9.6"]
[com.hierynomus/sshj "0.34.0"]
[com.jcraft/jsch.agentproxy.connector-factory "0.0.9"]
[com.jcraft/jsch.agentproxy.sshj "0.0.9"
:exclusions [net.schmizz/sshj]]
[org.bouncycastle/bcprov-jdk15on "1.70"]
[hiccup "1.0.5"]
[metametadata/multiset "0.1.1"]
[byte-streams "0.2.5-alpha2"]
[slingshot "0.12.2"]
[org.clojure/data.codec "0.1.1"]
[fipp "0.6.26"]]
:java-source-paths ["src"]
:javac-options ["-target" "11" "-source" "11"]
:main jepsen.cli
:plugins [[lein-localrepo "0.5.4"]
[lein-codox "0.10.8"]
[jonase/eastwood "0.3.10"]]
:jvm-opts ["-Xmx32g"
"-Djava.awt.headless=true"
"-server"]
:test-selectors {:default (fn [m]
(not (or (:perf m)
(:integration m)
(:logging m))))
:focus :focus
:perf :perf
:logging :logging
:integration :integration}
:codox {:output-path "doc/"
:source-uri "-io/jepsen/blob/v{version}/jepsen/{filepath}#L{line}"
:metadata {:doc/format :markdown}}
:profiles {:uberjar {:aot :all}
:dev {; experimenting with faster startup
;:aot [jepsen.core]
:dependencies [[org.clojure/test.check "1.1.1"]]
:jvm-opts ["-Xmx32g"
"-server"
"-XX:-OmitStackTraceInFastThrow"]}})
| null | https://raw.githubusercontent.com/jepsen-io/jepsen/cfd1421a0ee2a7e6095b1f3cab8a6dbd844f696f/jepsen/project.clj | clojure | experimenting with faster startup
:aot [jepsen.core] | (defproject jepsen "0.3.2-SNAPSHOT"
:description "Distributed systems testing framework."
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.11.1"]
[org.clojure/data.fressian "1.0.0"]
[org.clojure/tools.logging "1.2.4"]
[org.clojure/tools.cli "1.0.214"]
[spootnik/unilog "0.7.31"]
[elle "0.1.6"]
[clj-time "0.15.2"]
[io.jepsen/history "0.1.0"]
[jepsen.txn "0.1.2"]
[knossos "0.3.9"]
[clj-ssh "0.5.14"]
[gnuplot "0.1.3"]
[http-kit "2.6.0"]
[ring "1.9.6"]
[com.hierynomus/sshj "0.34.0"]
[com.jcraft/jsch.agentproxy.connector-factory "0.0.9"]
[com.jcraft/jsch.agentproxy.sshj "0.0.9"
:exclusions [net.schmizz/sshj]]
[org.bouncycastle/bcprov-jdk15on "1.70"]
[hiccup "1.0.5"]
[metametadata/multiset "0.1.1"]
[byte-streams "0.2.5-alpha2"]
[slingshot "0.12.2"]
[org.clojure/data.codec "0.1.1"]
[fipp "0.6.26"]]
:java-source-paths ["src"]
:javac-options ["-target" "11" "-source" "11"]
:main jepsen.cli
:plugins [[lein-localrepo "0.5.4"]
[lein-codox "0.10.8"]
[jonase/eastwood "0.3.10"]]
:jvm-opts ["-Xmx32g"
"-Djava.awt.headless=true"
"-server"]
:test-selectors {:default (fn [m]
(not (or (:perf m)
(:integration m)
(:logging m))))
:focus :focus
:perf :perf
:logging :logging
:integration :integration}
:codox {:output-path "doc/"
:source-uri "-io/jepsen/blob/v{version}/jepsen/{filepath}#L{line}"
:metadata {:doc/format :markdown}}
:profiles {:uberjar {:aot :all}
:dependencies [[org.clojure/test.check "1.1.1"]]
:jvm-opts ["-Xmx32g"
"-server"
"-XX:-OmitStackTraceInFastThrow"]}})
|
e8372f8e4a8f2675c14eabae91e8cbd2e573db33e8cdcec68bc0e626a951a3c1 | project-oak/hafnium-verification | infer.mli |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
(** Top-level driver that orchestrates build system integration, frontends, and backend *)
| null | https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/infer.mli | ocaml | * Top-level driver that orchestrates build system integration, frontends, and backend |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
|
137e7beb923fef9c3c27f469479f004936c856c03168d005efe23c3f85c1b43a | csicar/pskt | CLI.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module CLI where
import Version
import Prelude hiding (print)
import Control.Monad (when)
import qualified Control.Monad.Parallel as Par
import Data.Aeson
import Data.Aeson.Types hiding (Parser)
import Data.Char
import Data.Foldable (for_)
import Data.Traversable (forM)
import Data.FileEmbed (embedFile)
import Data.List (delete, intercalate, isPrefixOf, nub, partition)
import Data.Maybe
import Data.Monoid ((<>))
import Data.Version
import Control.Monad.Supply
import Control.Monad.Supply.Class
import Text.Printf
import qualified System.FilePath.Glob as G
import qualified Data.Text.Lazy.IO as TIO
import System.Environment
import System.Directory (copyFile, createDirectoryIfMissing, doesDirectoryExist, doesFileExist, getCurrentDirectory, getModificationTime)
import System.FilePath ((</>), takeFileName, joinPath, searchPathSeparator, splitDirectories, takeDirectory)
import System.Process
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as L
import qualified Data.Text.Lazy.Encoding as L
import qualified Data.ByteString as B
import Development.GitRev
import Data.Text.Prettyprint.Doc.Render.Text (renderLazy)
import Language.PureScript.AST.Literals
import Language.PureScript.CoreFn
import Language.PureScript.CoreFn.FromJSON
import Language.PureScript.Names (runModuleName)
import CodeGen.CoreImp
import CodeGen.KtCore
import CodeGen.Printer
import Data.Text.Prettyprint.Doc.Util (putDocW)
import Data.Text.Prettyprint.Doc (pretty)
import Data.Text.Prettyprint.Doc.Render.Text (renderIO)
import System.IO (openFile, IOMode(..), hClose, print)
import Protolude (unsnoc)
import Data.List.Extra (split, notNull)
import Options.Applicative (many, auto, argument, showDefault, metavar, help, option, long, short, Parser, ParserInfo, header, progDesc, fullDesc, helper, info, switch, value, str, (<**>))
import Text.Pretty.Simple (pPrint)
import Version
import Development.Shake
import Development.Shake.Command
import Development.Shake.FilePath
import Development.Shake.Util
parseJson :: Text -> Value
parseJson text
| Just fileJson <- decode . L.encodeUtf8 $ L.fromStrict text = fileJson
| otherwise = error "Bad json"
jsonToModule :: Value -> Module Ann
jsonToModule value =
case parse moduleFromJSON value of
Success (_, r) -> r
_ -> error "failed"
data CliOptions = CliOptions
{ printVersion :: Bool
, printCoreFn :: Bool
, printTranspiled :: Bool
, runProgram :: String
, foreigns :: [FilePath]
}
cli :: Parser CliOptions
cli = CliOptions
<$> switch
( long "print-version"
<> short 'v'
<> help "print PsKT version"
)
<*> switch
( long "print-corefn"
<> help "print debug info about read corefn"
)
<*> switch
( long "print-transpiled"
<> help "print debug info about transpiled files"
)
<*> option str
( long "run"
<> help "also run the transpiled program: The entry point needs to have type `:: Effect _`. Example: `-- run Main.main`"
<> value ""
)
<*> many
( option str
( long "foreigns"
<> help "folders containing foreign files. The matching files are passed to kotlinc and copied to the `output` folder"
)
)
-- Adding program help text to the parser
optsParserInfo :: ParserInfo CliOptions
optsParserInfo = info (cli <**> helper)
( fullDesc
<> progDesc ("pskt " <> versionString)
<> header "PureScript Transpiler to Kotlin using CoreFn"
)
shakeOpts = shakeOptions
{ shakeFiles="output/pskt"
, shakeProgress = progressSimple
, shakeThreads = 0 -- automatically choose number of threads
, shakeVersion = versionString
}
getModuleNames = fmap (takeFileName . takeDirectory) <$> getDirectoryFiles "" ["output/*/corefn.json"]
compile :: CliOptions -> IO ()
compile opts = shake shakeOpts $ do
action $ do
when (printVersion opts) $ putNormal $ "PsKt Version: " <> versionString
cs <- getModuleNames
let kotlinFiles = ["output/pskt" </> c <.> "kt" | c <- cs]
need ["foreigns"]
need ["output/pskt/PsRuntime.kt"]
need kotlinFiles
case runProgram opts of
"" -> pure ()
mainMod -> do
need ["output/pskt/entryPoint" </> mainMod <.> "kt"]
let jarFile = "output/pskt" </> mainMod <.> "jar"
need [jarFile]
command_ [] "java" ["-jar", jarFile]
"output/pskt/*.jar" %> \out -> do
let modName = takeBaseName out
ktFiles <- fmap (\mod -> "output/pskt" </> mod <.> "kt") <$> getModuleNames
need ktFiles
need ["output/pskt/entryPoint" </> modName <.> "kt"]
command_
[AddEnv "JAVA_OPTS" "-Xmx2G -Xms256M"]
"kotlinc" $
["output/pskt/PsRuntime.kt", "output/pskt/entryPoint" </> modName <.>"kt"]
++ ktFiles
++ ["output/pskt/foreigns" ]
++ ["-include-runtime", "-d", out]
++ ["-nowarn"]
"output/pskt/entryPoint/*.kt" %> \out -> do
let modName = takeBaseName out
let Just (start, end) = unsnoc $ split (=='.') $ modName
writeFileLines out
[ "@file:Suppress(\"UNCHECKED_CAST\", \"USELESS_CAST\")"
, "import Foreign.PsRuntime.appRun;"
, ""
, "fun main() {"
, " PS."<> intercalate "." start <> ".Module."<> end <> ".appRun()"
, "}"
]
"output/pskt/PsRuntime.kt" %> \out ->
writeFileChanged out $ unlines
[ "@file:Suppress(\"UNCHECKED_CAST\", \"USELESS_CAST\")"
, "package Foreign.PsRuntime;"
, ""
, "fun Any.app(arg: Any): Any {"
, " return (this as (Any) -> Any)(arg)"
, "}"
, ""
, "fun Any.appRun() = (this as () -> Any)()"
]
phony "foreigns" $ do
let foreignOut = "output/pskt/foreigns/"
foreignFiles <- forM (foreigns opts) $ \folder -> do
files <- getDirectoryFiles folder ["*.kt"]
return $ (\file -> (fileToModule file, folder </> file)) <$> files
for_ (concat foreignFiles) $ \(modName, file) ->
copyFileChanged file (foreignOut </> modName <.> "kt")
"output/pskt/*.kt" %> \out -> do
let modName = takeBaseName out
processFile opts out ("output" </> modName </> "corefn.json")
fileToModule :: FilePath -> String
fileToModule path = replaceSlash <$> path
where
replaceSlash '/' = '.'
replaceSlash char = char
processFile :: CliOptions -> FilePath -> FilePath -> Action ()
processFile opts outFile path = do
jsonText <- T.pack <$> readFile' path
let mod = jsonToModule $ parseJson jsonText
let modName = runModuleName $ moduleName mod
if printCoreFn opts then pPrint mod else pure ()
let moduleKt = moduleToKt' mod
-- pPrint moduleKt
outputFile <- liftIO $ openFile outFile WriteMode
putNormal $ "Transpiling " <> T.unpack modName
let moduleDoc = moduleToText mod
liftIO $ renderIO outputFile moduleDoc
liftIO $ hClose outputFile
liftIO $ if printTranspiled opts then TIO.putStrLn $ renderLazy moduleDoc else pure ()
| null | https://raw.githubusercontent.com/csicar/pskt/aa0d5df52e9579abd38061c6ab891489ebf295c4/src/CLI.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
Adding program help text to the parser
automatically choose number of threads
pPrint moduleKt | module CLI where
import Version
import Prelude hiding (print)
import Control.Monad (when)
import qualified Control.Monad.Parallel as Par
import Data.Aeson
import Data.Aeson.Types hiding (Parser)
import Data.Char
import Data.Foldable (for_)
import Data.Traversable (forM)
import Data.FileEmbed (embedFile)
import Data.List (delete, intercalate, isPrefixOf, nub, partition)
import Data.Maybe
import Data.Monoid ((<>))
import Data.Version
import Control.Monad.Supply
import Control.Monad.Supply.Class
import Text.Printf
import qualified System.FilePath.Glob as G
import qualified Data.Text.Lazy.IO as TIO
import System.Environment
import System.Directory (copyFile, createDirectoryIfMissing, doesDirectoryExist, doesFileExist, getCurrentDirectory, getModificationTime)
import System.FilePath ((</>), takeFileName, joinPath, searchPathSeparator, splitDirectories, takeDirectory)
import System.Process
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as L
import qualified Data.Text.Lazy.Encoding as L
import qualified Data.ByteString as B
import Development.GitRev
import Data.Text.Prettyprint.Doc.Render.Text (renderLazy)
import Language.PureScript.AST.Literals
import Language.PureScript.CoreFn
import Language.PureScript.CoreFn.FromJSON
import Language.PureScript.Names (runModuleName)
import CodeGen.CoreImp
import CodeGen.KtCore
import CodeGen.Printer
import Data.Text.Prettyprint.Doc.Util (putDocW)
import Data.Text.Prettyprint.Doc (pretty)
import Data.Text.Prettyprint.Doc.Render.Text (renderIO)
import System.IO (openFile, IOMode(..), hClose, print)
import Protolude (unsnoc)
import Data.List.Extra (split, notNull)
import Options.Applicative (many, auto, argument, showDefault, metavar, help, option, long, short, Parser, ParserInfo, header, progDesc, fullDesc, helper, info, switch, value, str, (<**>))
import Text.Pretty.Simple (pPrint)
import Version
import Development.Shake
import Development.Shake.Command
import Development.Shake.FilePath
import Development.Shake.Util
parseJson :: Text -> Value
parseJson text
| Just fileJson <- decode . L.encodeUtf8 $ L.fromStrict text = fileJson
| otherwise = error "Bad json"
jsonToModule :: Value -> Module Ann
jsonToModule value =
case parse moduleFromJSON value of
Success (_, r) -> r
_ -> error "failed"
data CliOptions = CliOptions
{ printVersion :: Bool
, printCoreFn :: Bool
, printTranspiled :: Bool
, runProgram :: String
, foreigns :: [FilePath]
}
cli :: Parser CliOptions
cli = CliOptions
<$> switch
( long "print-version"
<> short 'v'
<> help "print PsKT version"
)
<*> switch
( long "print-corefn"
<> help "print debug info about read corefn"
)
<*> switch
( long "print-transpiled"
<> help "print debug info about transpiled files"
)
<*> option str
( long "run"
<> help "also run the transpiled program: The entry point needs to have type `:: Effect _`. Example: `-- run Main.main`"
<> value ""
)
<*> many
( option str
( long "foreigns"
<> help "folders containing foreign files. The matching files are passed to kotlinc and copied to the `output` folder"
)
)
optsParserInfo :: ParserInfo CliOptions
optsParserInfo = info (cli <**> helper)
( fullDesc
<> progDesc ("pskt " <> versionString)
<> header "PureScript Transpiler to Kotlin using CoreFn"
)
shakeOpts = shakeOptions
{ shakeFiles="output/pskt"
, shakeProgress = progressSimple
, shakeVersion = versionString
}
getModuleNames = fmap (takeFileName . takeDirectory) <$> getDirectoryFiles "" ["output/*/corefn.json"]
compile :: CliOptions -> IO ()
compile opts = shake shakeOpts $ do
action $ do
when (printVersion opts) $ putNormal $ "PsKt Version: " <> versionString
cs <- getModuleNames
let kotlinFiles = ["output/pskt" </> c <.> "kt" | c <- cs]
need ["foreigns"]
need ["output/pskt/PsRuntime.kt"]
need kotlinFiles
case runProgram opts of
"" -> pure ()
mainMod -> do
need ["output/pskt/entryPoint" </> mainMod <.> "kt"]
let jarFile = "output/pskt" </> mainMod <.> "jar"
need [jarFile]
command_ [] "java" ["-jar", jarFile]
"output/pskt/*.jar" %> \out -> do
let modName = takeBaseName out
ktFiles <- fmap (\mod -> "output/pskt" </> mod <.> "kt") <$> getModuleNames
need ktFiles
need ["output/pskt/entryPoint" </> modName <.> "kt"]
command_
[AddEnv "JAVA_OPTS" "-Xmx2G -Xms256M"]
"kotlinc" $
["output/pskt/PsRuntime.kt", "output/pskt/entryPoint" </> modName <.>"kt"]
++ ktFiles
++ ["output/pskt/foreigns" ]
++ ["-include-runtime", "-d", out]
++ ["-nowarn"]
"output/pskt/entryPoint/*.kt" %> \out -> do
let modName = takeBaseName out
let Just (start, end) = unsnoc $ split (=='.') $ modName
writeFileLines out
[ "@file:Suppress(\"UNCHECKED_CAST\", \"USELESS_CAST\")"
, "import Foreign.PsRuntime.appRun;"
, ""
, "fun main() {"
, " PS."<> intercalate "." start <> ".Module."<> end <> ".appRun()"
, "}"
]
"output/pskt/PsRuntime.kt" %> \out ->
writeFileChanged out $ unlines
[ "@file:Suppress(\"UNCHECKED_CAST\", \"USELESS_CAST\")"
, "package Foreign.PsRuntime;"
, ""
, "fun Any.app(arg: Any): Any {"
, " return (this as (Any) -> Any)(arg)"
, "}"
, ""
, "fun Any.appRun() = (this as () -> Any)()"
]
phony "foreigns" $ do
let foreignOut = "output/pskt/foreigns/"
foreignFiles <- forM (foreigns opts) $ \folder -> do
files <- getDirectoryFiles folder ["*.kt"]
return $ (\file -> (fileToModule file, folder </> file)) <$> files
for_ (concat foreignFiles) $ \(modName, file) ->
copyFileChanged file (foreignOut </> modName <.> "kt")
"output/pskt/*.kt" %> \out -> do
let modName = takeBaseName out
processFile opts out ("output" </> modName </> "corefn.json")
fileToModule :: FilePath -> String
fileToModule path = replaceSlash <$> path
where
replaceSlash '/' = '.'
replaceSlash char = char
processFile :: CliOptions -> FilePath -> FilePath -> Action ()
processFile opts outFile path = do
jsonText <- T.pack <$> readFile' path
let mod = jsonToModule $ parseJson jsonText
let modName = runModuleName $ moduleName mod
if printCoreFn opts then pPrint mod else pure ()
let moduleKt = moduleToKt' mod
outputFile <- liftIO $ openFile outFile WriteMode
putNormal $ "Transpiling " <> T.unpack modName
let moduleDoc = moduleToText mod
liftIO $ renderIO outputFile moduleDoc
liftIO $ hClose outputFile
liftIO $ if printTranspiled opts then TIO.putStrLn $ renderLazy moduleDoc else pure ()
|
056647267e27c5fb7572595cacb15580b25d9220013e4360e11286c1ef622c9f | gogins/csound-extended-nudruz | whirl.lisp | ;;;; N U D R U Z C S O U N D F F I E X A M P L E S
August 2018
#|
Contrary to CM documentation, the events function does not return a usable seq object.
The generated score is placed into the seq that is passed to events.
|#
(require :asdf)
(require :fomus)
(require :nudruz)
(load "example-csd.lisp")
(in-package :cm)
(defparameter csound-seq (new seq :name "csound-test"))
(events (whirl 10 .1 .5 20 10 50 harms) csound-seq)
(defparameter *piano-part*
(new fomus:part
:name "Xing"
:partid 0
:instr '(:piano :staves 2)))
(defparameter partids (make-hash-table))
(setf (gethash 0 partids) 0)
(defparameter voices (make-hash-table))
(defparameter voicelist 1)
(setf (gethash 0 voices) voicelist)
(seq-to-lilypond csound-seq "whirl.ly" *piano-part* partids voices :title "Whirl" :composer "Drew Krause")
(render-with-csd csound-seq csd-text :channel-offset 22 :velocity-scale 100 :csd-filename "whirl.csd")
(quit)
| null | https://raw.githubusercontent.com/gogins/csound-extended-nudruz/4551d54890f4adbadc5db8f46cc24af8e92fb9e9/examples/whirl.lisp | lisp | N U D R U Z C S O U N D F F I E X A M P L E S
Contrary to CM documentation, the events function does not return a usable seq object.
The generated score is placed into the seq that is passed to events.
|
August 2018
(require :asdf)
(require :fomus)
(require :nudruz)
(load "example-csd.lisp")
(in-package :cm)
(defparameter csound-seq (new seq :name "csound-test"))
(events (whirl 10 .1 .5 20 10 50 harms) csound-seq)
(defparameter *piano-part*
(new fomus:part
:name "Xing"
:partid 0
:instr '(:piano :staves 2)))
(defparameter partids (make-hash-table))
(setf (gethash 0 partids) 0)
(defparameter voices (make-hash-table))
(defparameter voicelist 1)
(setf (gethash 0 voices) voicelist)
(seq-to-lilypond csound-seq "whirl.ly" *piano-part* partids voices :title "Whirl" :composer "Drew Krause")
(render-with-csd csound-seq csd-text :channel-offset 22 :velocity-scale 100 :csd-filename "whirl.csd")
(quit)
|
a620816f7d9019ec654f6a9ecc28d0fd2294db82b3c2fb27ef2bea12fc964170 | diku-dk/futhark | GraphRep.hs | | A graph representation of a sequence of statements
-- (i.e. a 'Body'), built to handle fusion. Could perhaps be made
-- more general. An important property is that it does not handle
-- "nested bodies" (e.g. 'Match'); these are represented as single
-- nodes.
--
-- This is all implemented on top of the graph representation provided
-- by the @fgl@ package ("Data.Graph.Inductive"). The graph provided
-- by this package allows nodes and edges to have arbitrarily-typed
" labels " . It is these labels ( ' EdgeT ' , ' NodeT ' ) that we use to
contain - specific information . An edge goes * from * uses of
-- variables to the node that produces that variable. There are also
-- edges that do not represent normal data dependencies, but other
-- things. This means that a node can have multiple edges for the
-- same name, indicating different kinds of dependencies.
module Futhark.Optimise.Fusion.GraphRep
( -- * Data structure
EdgeT (..),
NodeT (..),
DepContext,
DepGraphAug,
DepGraph (..),
DepNode,
-- * Queries
getName,
nodeFromLNode,
mergedContext,
mapAcross,
edgesBetween,
reachable,
applyAugs,
depsFromEdge,
contractEdge,
isRealNode,
isCons,
isDep,
isInf,
-- * Construction
mkDepGraph,
mkDepGraphForFun,
pprg,
)
where
import Control.Monad.Reader
import Data.Bifunctor (bimap)
import Data.Foldable (foldlM)
import Data.Graph.Inductive.Dot qualified as G
import Data.Graph.Inductive.Graph qualified as G
import Data.Graph.Inductive.Query.DFS qualified as Q
import Data.Graph.Inductive.Tree qualified as G
import Data.List qualified as L
import Data.Map.Strict qualified as M
import Data.Maybe (mapMaybe)
import Data.Set qualified as S
import Futhark.Analysis.Alias qualified as Alias
import Futhark.Analysis.HORep.SOAC qualified as H
import Futhark.IR.Prop.Aliases
import Futhark.IR.SOACS hiding (SOAC (..))
import Futhark.IR.SOACS qualified as Futhark
import Futhark.Util (nubOrd)
-- | Information associated with an edge in the graph.
data EdgeT
= Alias VName
| InfDep VName
| Dep VName
| Cons VName
| Fake VName
| Res VName
deriving (Eq, Ord)
-- | Information associated with a node in the graph.
data NodeT
= StmNode (Stm SOACS)
| SoacNode H.ArrayTransforms (Pat Type) (H.SOAC SOACS) (StmAux (ExpDec SOACS))
| -- | First 'VName' is result; last is input.
TransNode VName H.ArrayTransform VName
| -- | Node corresponding to a result of the entire computation
-- (i.e. the 'Result' of a body). Any node that is not
-- transitively reachable from one of these can be considered
-- dead.
ResNode VName
| -- | Node corresponding to a free variable. These are used to
-- safely handle consumption, which also means we don't have to
-- create a node for every free single variable.
FreeNode VName
| MatchNode (Stm SOACS) [(NodeT, [EdgeT])]
| DoNode (Stm SOACS) [(NodeT, [EdgeT])]
deriving (Eq)
instance Show EdgeT where
show (Dep vName) = "Dep " <> prettyString vName
show (InfDep vName) = "iDep " <> prettyString vName
show (Cons _) = "Cons"
show (Fake _) = "Fake"
show (Res _) = "Res"
show (Alias _) = "Alias"
instance Show NodeT where
show (StmNode (Let pat _ _)) = L.intercalate ", " $ map prettyString $ patNames pat
show (SoacNode _ pat _ _) = prettyString pat
show (TransNode _ tr _) = prettyString (show tr)
show (ResNode name) = prettyString $ "Res: " ++ prettyString name
show (FreeNode name) = prettyString $ "Input: " ++ prettyString name
show (MatchNode stm _) = "Match: " ++ L.intercalate ", " (map prettyString $ stmNames stm)
show (DoNode stm _) = "Do: " ++ L.intercalate ", " (map prettyString $ stmNames stm)
-- | The name that this edge depends on.
getName :: EdgeT -> VName
getName edgeT = case edgeT of
Alias vn -> vn
InfDep vn -> vn
Dep vn -> vn
Cons vn -> vn
Fake vn -> vn
Res vn -> vn
-- | Does the node acutally represent something in the program? A
-- "non-real" node represents things like fake nodes inserted to
-- express ordering due to consumption.
isRealNode :: NodeT -> Bool
isRealNode ResNode {} = False
isRealNode FreeNode {} = False
isRealNode _ = True
-- | Prettyprint dependency graph.
pprg :: DepGraph -> String
pprg = G.showDot . G.fglToDotString . G.nemap show show . dgGraph
-- | A pair of a 'G.Node' and the node label.
type DepNode = G.LNode NodeT
type DepEdge = G.LEdge EdgeT
| A tuple with four parts : inbound links to the node , the node
itself , the ' NodeT ' " label " , and outbound links from the node .
-- This type is used to modify the graph in 'mapAcross'.
type DepContext = G.Context NodeT EdgeT
-- | A dependency graph. Edges go from *consumers* to *producers*
-- (i.e. from usage to definition). That means the incoming edges of
-- a node are the dependents of that node, and the outgoing edges are
-- the dependencies of that node.
data DepGraph = DepGraph
{ dgGraph :: G.Gr NodeT EdgeT,
dgProducerMapping :: ProducerMapping,
| A table mapping VNames to VNames that are aliased to it .
dgAliasTable :: AliasTable
}
-- | A "graph augmentation" is a monadic action that modifies the graph.
type DepGraphAug m = DepGraph -> m DepGraph
-- | For each node, what producer should the node depend on and what
-- type is it.
type EdgeGenerator = NodeT -> [(VName, EdgeT)]
-- | A mapping from variable name to the graph node that produces
-- it.
type ProducerMapping = M.Map VName G.Node
makeMapping :: Monad m => DepGraphAug m
makeMapping dg@(DepGraph {dgGraph = g}) =
pure dg {dgProducerMapping = M.fromList $ concatMap gen_dep_list (G.labNodes g)}
where
gen_dep_list :: DepNode -> [(VName, G.Node)]
gen_dep_list (i, node) = [(name, i) | name <- getOutputs node]
-- | Apply several graph augmentations in sequence.
applyAugs :: Monad m => [DepGraphAug m] -> DepGraphAug m
applyAugs augs g = foldlM (flip ($)) g augs
| Creates for the given nodes on the graph using the ' EdgeGenerator ' .
genEdges :: Monad m => [DepNode] -> EdgeGenerator -> DepGraphAug m
genEdges l_stms edge_fun dg =
depGraphInsertEdges (concatMap (genEdge (dgProducerMapping dg)) l_stms) dg
where
-- statements -> mapping from declared array names to soac index
genEdge :: M.Map VName G.Node -> DepNode -> [G.LEdge EdgeT]
genEdge name_map (from, node) = do
(dep, edgeT) <- edge_fun node
Just to <- [M.lookup dep name_map]
pure $ G.toLEdge (from, to) edgeT
depGraphInsertEdges :: Monad m => [DepEdge] -> DepGraphAug m
depGraphInsertEdges edgs dg = pure $ dg {dgGraph = G.insEdges edgs $ dgGraph dg}
-- | Monadically modify every node of the graph.
mapAcross :: Monad m => (DepContext -> m DepContext) -> DepGraphAug m
mapAcross f dg = do
g' <- foldlM (flip helper) (dgGraph dg) (G.nodes (dgGraph dg))
pure $ dg {dgGraph = g'}
where
helper n g' = case G.match n g' of
(Just c, g_new) -> do
c' <- f c
pure $ c' G.& g_new
(Nothing, _) -> pure g'
stmFromNode :: NodeT -> Stms SOACS -- do not use outside of edge generation
stmFromNode (StmNode x) = oneStm x
stmFromNode _ = mempty
-- | Get the underlying @fgl@ node.
nodeFromLNode :: DepNode -> G.Node
nodeFromLNode = fst
-- | Get the variable name that this edge refers to.
depsFromEdge :: DepEdge -> VName
depsFromEdge = getName . G.edgeLabel
| Find all the edges connecting the two nodes .
edgesBetween :: DepGraph -> G.Node -> G.Node -> [DepEdge]
edgesBetween dg n1 n2 = G.labEdges $ G.subgraph [n1, n2] $ dgGraph dg
| @reachable dg from to@ is true if @to@ is reachable from @from@.
reachable :: DepGraph -> G.Node -> G.Node -> Bool
reachable dg source target = target `elem` Q.reachable source (dgGraph dg)
-- Utility func for augs
augWithFun :: Monad m => EdgeGenerator -> DepGraphAug m
augWithFun f dg = genEdges (G.labNodes (dgGraph dg)) f dg
addDeps :: Monad m => DepGraphAug m
addDeps = augWithFun toDep
where
toDep stmt =
let (fusible, infusible) =
bimap (map fst) (map fst)
. L.partition ((== SOACInput) . snd)
. S.toList
$ foldMap stmInputs (stmFromNode stmt)
mkDep vname = (vname, Dep vname)
mkInfDep vname = (vname, InfDep vname)
in map mkDep fusible <> map mkInfDep infusible
addConsAndAliases :: Monad m => DepGraphAug m
addConsAndAliases = augWithFun edges
where
edges (StmNode s) = consEdges s' <> aliasEdges s'
where
s' = Alias.analyseStm mempty s
edges _ = mempty
consEdges s = zip names (map Cons names)
where
names = namesToList $ consumedInStm s
aliasEdges =
map (\vname -> (vname, Alias vname))
. namesToList
. mconcat
. patAliases
. stmPat
-- extra dependencies mask the fact that consuming nodes "depend" on all other
-- nodes coming before it (now also adds fake edges to aliases - hope this
-- fixes asymptotic complexity guarantees)
addExtraCons :: Monad m => DepGraphAug m
addExtraCons dg =
depGraphInsertEdges (concatMap makeEdge (G.labEdges g)) dg
where
g = dgGraph dg
alias_table = dgAliasTable dg
mapping = dgProducerMapping dg
makeEdge (from, to, Cons cname) = do
let aliases = namesToList $ M.findWithDefault mempty cname alias_table
to' = mapMaybe (`M.lookup` mapping) aliases
p (tonode, toedge) =
tonode /= from && getName toedge `elem` (cname : aliases)
(to2, _) <- filter p $ concatMap (G.lpre g) to' <> G.lpre g to
pure $ G.toLEdge (from, to2) (Fake cname)
makeEdge _ = []
mapAcrossNodeTs :: Monad m => (NodeT -> m NodeT) -> DepGraphAug m
mapAcrossNodeTs f = mapAcross f'
where
f' (ins, n, nodeT, outs) = do
nodeT' <- f nodeT
pure (ins, n, nodeT', outs)
nodeToSoacNode :: (HasScope SOACS m, Monad m) => NodeT -> m NodeT
nodeToSoacNode n@(StmNode s@(Let pat aux op)) = case op of
Op {} -> do
maybeSoac <- H.fromExp op
case maybeSoac of
Right hsoac -> pure $ SoacNode mempty pat hsoac aux
Left H.NotSOAC -> pure n
DoLoop {} ->
pure $ DoNode s []
Match {} ->
pure $ MatchNode s []
e
| [output] <- patNames pat,
Just (ia, tr) <- H.transformFromExp (stmAuxCerts aux) e ->
pure $ TransNode output tr ia
_ -> pure n
nodeToSoacNode n = pure n
-- | Construct a graph with only nodes, but no edges.
emptyGraph :: Body SOACS -> DepGraph
emptyGraph body =
DepGraph
{ dgGraph = G.mkGraph (labelNodes (stmnodes <> resnodes <> inputnodes)) [],
dgProducerMapping = mempty,
dgAliasTable = aliases
}
where
labelNodes = zip [0 ..]
stmnodes = map StmNode $ stmsToList $ bodyStms body
resnodes = map ResNode $ namesToList $ freeIn $ bodyResult body
inputnodes = map FreeNode $ namesToList consumed
(_, (aliases, consumed)) = Alias.analyseStms mempty $ bodyStms body
getStmRes :: EdgeGenerator
getStmRes (ResNode name) = [(name, Res name)]
getStmRes _ = []
addResEdges :: Monad m => DepGraphAug m
addResEdges = augWithFun getStmRes
-- | Make a dependency graph corresponding to a 'Body'.
mkDepGraph :: (HasScope SOACS m, Monad m) => Body SOACS -> m DepGraph
mkDepGraph body = applyAugs augs $ emptyGraph body
where
augs =
[ makeMapping,
addDeps,
addConsAndAliases,
addExtraCons,
addResEdges,
mapAcrossNodeTs nodeToSoacNode -- Must be done after adding edges
]
-- | Make a dependency graph corresponding to a function.
mkDepGraphForFun :: FunDef SOACS -> DepGraph
mkDepGraphForFun f = runReader (mkDepGraph (funDefBody f)) scope
where
scope = scopeOfFParams (funDefParams f) <> scopeOf (bodyStms (funDefBody f))
| Merges two contexts .
mergedContext :: Ord b => a -> G.Context a b -> G.Context a b -> G.Context a b
mergedContext mergedlabel (inp1, n1, _, out1) (inp2, n2, _, out2) =
let new_inp = filter (\n -> snd n /= n1 && snd n /= n2) (nubOrd (inp1 <> inp2))
new_out = filter (\n -> snd n /= n1 && snd n /= n2) (nubOrd (out1 <> out2))
in (new_inp, n1, mergedlabel, new_out)
| Remove the given node , and insert the ' DepContext ' into the
-- graph, replacing any existing information about the node contained
in the ' DepContext ' .
contractEdge :: Monad m => G.Node -> DepContext -> DepGraphAug m
contractEdge n2 ctx dg = do
let n1 = G.node' ctx -- n1 remains
pure $ dg {dgGraph = ctx G.& G.delNodes [n1, n2] (dgGraph dg)}
-- Utils for fusibility/infusibility
-- find dependencies - either fusible or infusible. edges are generated based on these
-- | A classification of a free variable.
data Classification
= -- | Used as array input to a SOAC (meaning fusible).
SOACInput
| -- | Used in some other way.
Other
deriving (Eq, Ord, Show)
type Classifications = S.Set (VName, Classification)
freeClassifications :: FreeIn a => a -> Classifications
freeClassifications =
S.fromList . (`zip` repeat Other) . namesToList . freeIn
stmInputs :: Stm SOACS -> Classifications
stmInputs (Let pat aux e) =
freeClassifications (pat, aux) <> expInputs e
bodyInputs :: Body SOACS -> Classifications
bodyInputs (Body _ stms res) = foldMap stmInputs stms <> freeClassifications res
expInputs :: Exp SOACS -> Classifications
expInputs (Match cond cases defbody attr) =
foldMap (bodyInputs . caseBody) cases
<> bodyInputs defbody
<> freeClassifications (cond, attr)
expInputs (DoLoop params form b1) =
freeClassifications (params, form) <> bodyInputs b1
expInputs (Op soac) = case soac of
Futhark.Screma w is form -> inputs is <> freeClassifications (w, form)
Futhark.Hist w is ops lam -> inputs is <> freeClassifications (w, ops, lam)
Futhark.Scatter w is lam iws -> inputs is <> freeClassifications (w, lam, iws)
Futhark.Stream w is nes lam ->
inputs is <> freeClassifications (w, nes, lam)
Futhark.JVP {} -> freeClassifications soac
Futhark.VJP {} -> freeClassifications soac
where
inputs = S.fromList . (`zip` repeat SOACInput)
expInputs e
| Just (arr, _) <- H.transformFromExp mempty e =
S.singleton (arr, SOACInput)
<> freeClassifications (freeIn e `namesSubtract` oneName arr)
| otherwise = freeClassifications e
stmNames :: Stm SOACS -> [VName]
stmNames = patNames . stmPat
getOutputs :: NodeT -> [VName]
getOutputs node = case node of
(StmNode stm) -> stmNames stm
(TransNode v _ _) -> [v]
(ResNode _) -> []
(FreeNode name) -> [name]
(MatchNode stm _) -> stmNames stm
(DoNode stm _) -> stmNames stm
(SoacNode _ pat _ _) -> patNames pat
-- | Is there a possibility of fusion?
isDep :: EdgeT -> Bool
isDep (Dep _) = True
isDep (Res _) = True
isDep _ = False
-- | Is this an infusible edge?
isInf :: (G.Node, G.Node, EdgeT) -> Bool
isInf (_, _, e) = case e of
InfDep _ -> True
Fake _ -> True -- this is infusible to avoid simultaneous cons/dep edges
_ -> False
-- | Is this a 'Cons' edge?
isCons :: EdgeT -> Bool
isCons (Cons _) = True
isCons _ = False
| null | https://raw.githubusercontent.com/diku-dk/futhark/c0eccff27fd804390c8968954342bf9b23479bfc/src/Futhark/Optimise/Fusion/GraphRep.hs | haskell | (i.e. a 'Body'), built to handle fusion. Could perhaps be made
more general. An important property is that it does not handle
"nested bodies" (e.g. 'Match'); these are represented as single
nodes.
This is all implemented on top of the graph representation provided
by the @fgl@ package ("Data.Graph.Inductive"). The graph provided
by this package allows nodes and edges to have arbitrarily-typed
variables to the node that produces that variable. There are also
edges that do not represent normal data dependencies, but other
things. This means that a node can have multiple edges for the
same name, indicating different kinds of dependencies.
* Data structure
* Queries
* Construction
| Information associated with an edge in the graph.
| Information associated with a node in the graph.
| First 'VName' is result; last is input.
| Node corresponding to a result of the entire computation
(i.e. the 'Result' of a body). Any node that is not
transitively reachable from one of these can be considered
dead.
| Node corresponding to a free variable. These are used to
safely handle consumption, which also means we don't have to
create a node for every free single variable.
| The name that this edge depends on.
| Does the node acutally represent something in the program? A
"non-real" node represents things like fake nodes inserted to
express ordering due to consumption.
| Prettyprint dependency graph.
| A pair of a 'G.Node' and the node label.
This type is used to modify the graph in 'mapAcross'.
| A dependency graph. Edges go from *consumers* to *producers*
(i.e. from usage to definition). That means the incoming edges of
a node are the dependents of that node, and the outgoing edges are
the dependencies of that node.
| A "graph augmentation" is a monadic action that modifies the graph.
| For each node, what producer should the node depend on and what
type is it.
| A mapping from variable name to the graph node that produces
it.
| Apply several graph augmentations in sequence.
statements -> mapping from declared array names to soac index
| Monadically modify every node of the graph.
do not use outside of edge generation
| Get the underlying @fgl@ node.
| Get the variable name that this edge refers to.
Utility func for augs
extra dependencies mask the fact that consuming nodes "depend" on all other
nodes coming before it (now also adds fake edges to aliases - hope this
fixes asymptotic complexity guarantees)
| Construct a graph with only nodes, but no edges.
| Make a dependency graph corresponding to a 'Body'.
Must be done after adding edges
| Make a dependency graph corresponding to a function.
graph, replacing any existing information about the node contained
n1 remains
Utils for fusibility/infusibility
find dependencies - either fusible or infusible. edges are generated based on these
| A classification of a free variable.
| Used as array input to a SOAC (meaning fusible).
| Used in some other way.
| Is there a possibility of fusion?
| Is this an infusible edge?
this is infusible to avoid simultaneous cons/dep edges
| Is this a 'Cons' edge? | | A graph representation of a sequence of statements
" labels " . It is these labels ( ' EdgeT ' , ' NodeT ' ) that we use to
contain - specific information . An edge goes * from * uses of
module Futhark.Optimise.Fusion.GraphRep
EdgeT (..),
NodeT (..),
DepContext,
DepGraphAug,
DepGraph (..),
DepNode,
getName,
nodeFromLNode,
mergedContext,
mapAcross,
edgesBetween,
reachable,
applyAugs,
depsFromEdge,
contractEdge,
isRealNode,
isCons,
isDep,
isInf,
mkDepGraph,
mkDepGraphForFun,
pprg,
)
where
import Control.Monad.Reader
import Data.Bifunctor (bimap)
import Data.Foldable (foldlM)
import Data.Graph.Inductive.Dot qualified as G
import Data.Graph.Inductive.Graph qualified as G
import Data.Graph.Inductive.Query.DFS qualified as Q
import Data.Graph.Inductive.Tree qualified as G
import Data.List qualified as L
import Data.Map.Strict qualified as M
import Data.Maybe (mapMaybe)
import Data.Set qualified as S
import Futhark.Analysis.Alias qualified as Alias
import Futhark.Analysis.HORep.SOAC qualified as H
import Futhark.IR.Prop.Aliases
import Futhark.IR.SOACS hiding (SOAC (..))
import Futhark.IR.SOACS qualified as Futhark
import Futhark.Util (nubOrd)
data EdgeT
= Alias VName
| InfDep VName
| Dep VName
| Cons VName
| Fake VName
| Res VName
deriving (Eq, Ord)
data NodeT
= StmNode (Stm SOACS)
| SoacNode H.ArrayTransforms (Pat Type) (H.SOAC SOACS) (StmAux (ExpDec SOACS))
TransNode VName H.ArrayTransform VName
ResNode VName
FreeNode VName
| MatchNode (Stm SOACS) [(NodeT, [EdgeT])]
| DoNode (Stm SOACS) [(NodeT, [EdgeT])]
deriving (Eq)
instance Show EdgeT where
show (Dep vName) = "Dep " <> prettyString vName
show (InfDep vName) = "iDep " <> prettyString vName
show (Cons _) = "Cons"
show (Fake _) = "Fake"
show (Res _) = "Res"
show (Alias _) = "Alias"
instance Show NodeT where
show (StmNode (Let pat _ _)) = L.intercalate ", " $ map prettyString $ patNames pat
show (SoacNode _ pat _ _) = prettyString pat
show (TransNode _ tr _) = prettyString (show tr)
show (ResNode name) = prettyString $ "Res: " ++ prettyString name
show (FreeNode name) = prettyString $ "Input: " ++ prettyString name
show (MatchNode stm _) = "Match: " ++ L.intercalate ", " (map prettyString $ stmNames stm)
show (DoNode stm _) = "Do: " ++ L.intercalate ", " (map prettyString $ stmNames stm)
getName :: EdgeT -> VName
getName edgeT = case edgeT of
Alias vn -> vn
InfDep vn -> vn
Dep vn -> vn
Cons vn -> vn
Fake vn -> vn
Res vn -> vn
isRealNode :: NodeT -> Bool
isRealNode ResNode {} = False
isRealNode FreeNode {} = False
isRealNode _ = True
pprg :: DepGraph -> String
pprg = G.showDot . G.fglToDotString . G.nemap show show . dgGraph
type DepNode = G.LNode NodeT
type DepEdge = G.LEdge EdgeT
| A tuple with four parts : inbound links to the node , the node
itself , the ' NodeT ' " label " , and outbound links from the node .
type DepContext = G.Context NodeT EdgeT
data DepGraph = DepGraph
{ dgGraph :: G.Gr NodeT EdgeT,
dgProducerMapping :: ProducerMapping,
| A table mapping VNames to VNames that are aliased to it .
dgAliasTable :: AliasTable
}
type DepGraphAug m = DepGraph -> m DepGraph
type EdgeGenerator = NodeT -> [(VName, EdgeT)]
type ProducerMapping = M.Map VName G.Node
makeMapping :: Monad m => DepGraphAug m
makeMapping dg@(DepGraph {dgGraph = g}) =
pure dg {dgProducerMapping = M.fromList $ concatMap gen_dep_list (G.labNodes g)}
where
gen_dep_list :: DepNode -> [(VName, G.Node)]
gen_dep_list (i, node) = [(name, i) | name <- getOutputs node]
applyAugs :: Monad m => [DepGraphAug m] -> DepGraphAug m
applyAugs augs g = foldlM (flip ($)) g augs
| Creates for the given nodes on the graph using the ' EdgeGenerator ' .
genEdges :: Monad m => [DepNode] -> EdgeGenerator -> DepGraphAug m
genEdges l_stms edge_fun dg =
depGraphInsertEdges (concatMap (genEdge (dgProducerMapping dg)) l_stms) dg
where
genEdge :: M.Map VName G.Node -> DepNode -> [G.LEdge EdgeT]
genEdge name_map (from, node) = do
(dep, edgeT) <- edge_fun node
Just to <- [M.lookup dep name_map]
pure $ G.toLEdge (from, to) edgeT
depGraphInsertEdges :: Monad m => [DepEdge] -> DepGraphAug m
depGraphInsertEdges edgs dg = pure $ dg {dgGraph = G.insEdges edgs $ dgGraph dg}
mapAcross :: Monad m => (DepContext -> m DepContext) -> DepGraphAug m
mapAcross f dg = do
g' <- foldlM (flip helper) (dgGraph dg) (G.nodes (dgGraph dg))
pure $ dg {dgGraph = g'}
where
helper n g' = case G.match n g' of
(Just c, g_new) -> do
c' <- f c
pure $ c' G.& g_new
(Nothing, _) -> pure g'
stmFromNode (StmNode x) = oneStm x
stmFromNode _ = mempty
nodeFromLNode :: DepNode -> G.Node
nodeFromLNode = fst
depsFromEdge :: DepEdge -> VName
depsFromEdge = getName . G.edgeLabel
| Find all the edges connecting the two nodes .
edgesBetween :: DepGraph -> G.Node -> G.Node -> [DepEdge]
edgesBetween dg n1 n2 = G.labEdges $ G.subgraph [n1, n2] $ dgGraph dg
| @reachable dg from to@ is true if @to@ is reachable from @from@.
reachable :: DepGraph -> G.Node -> G.Node -> Bool
reachable dg source target = target `elem` Q.reachable source (dgGraph dg)
augWithFun :: Monad m => EdgeGenerator -> DepGraphAug m
augWithFun f dg = genEdges (G.labNodes (dgGraph dg)) f dg
addDeps :: Monad m => DepGraphAug m
addDeps = augWithFun toDep
where
toDep stmt =
let (fusible, infusible) =
bimap (map fst) (map fst)
. L.partition ((== SOACInput) . snd)
. S.toList
$ foldMap stmInputs (stmFromNode stmt)
mkDep vname = (vname, Dep vname)
mkInfDep vname = (vname, InfDep vname)
in map mkDep fusible <> map mkInfDep infusible
addConsAndAliases :: Monad m => DepGraphAug m
addConsAndAliases = augWithFun edges
where
edges (StmNode s) = consEdges s' <> aliasEdges s'
where
s' = Alias.analyseStm mempty s
edges _ = mempty
consEdges s = zip names (map Cons names)
where
names = namesToList $ consumedInStm s
aliasEdges =
map (\vname -> (vname, Alias vname))
. namesToList
. mconcat
. patAliases
. stmPat
addExtraCons :: Monad m => DepGraphAug m
addExtraCons dg =
depGraphInsertEdges (concatMap makeEdge (G.labEdges g)) dg
where
g = dgGraph dg
alias_table = dgAliasTable dg
mapping = dgProducerMapping dg
makeEdge (from, to, Cons cname) = do
let aliases = namesToList $ M.findWithDefault mempty cname alias_table
to' = mapMaybe (`M.lookup` mapping) aliases
p (tonode, toedge) =
tonode /= from && getName toedge `elem` (cname : aliases)
(to2, _) <- filter p $ concatMap (G.lpre g) to' <> G.lpre g to
pure $ G.toLEdge (from, to2) (Fake cname)
makeEdge _ = []
mapAcrossNodeTs :: Monad m => (NodeT -> m NodeT) -> DepGraphAug m
mapAcrossNodeTs f = mapAcross f'
where
f' (ins, n, nodeT, outs) = do
nodeT' <- f nodeT
pure (ins, n, nodeT', outs)
nodeToSoacNode :: (HasScope SOACS m, Monad m) => NodeT -> m NodeT
nodeToSoacNode n@(StmNode s@(Let pat aux op)) = case op of
Op {} -> do
maybeSoac <- H.fromExp op
case maybeSoac of
Right hsoac -> pure $ SoacNode mempty pat hsoac aux
Left H.NotSOAC -> pure n
DoLoop {} ->
pure $ DoNode s []
Match {} ->
pure $ MatchNode s []
e
| [output] <- patNames pat,
Just (ia, tr) <- H.transformFromExp (stmAuxCerts aux) e ->
pure $ TransNode output tr ia
_ -> pure n
nodeToSoacNode n = pure n
emptyGraph :: Body SOACS -> DepGraph
emptyGraph body =
DepGraph
{ dgGraph = G.mkGraph (labelNodes (stmnodes <> resnodes <> inputnodes)) [],
dgProducerMapping = mempty,
dgAliasTable = aliases
}
where
labelNodes = zip [0 ..]
stmnodes = map StmNode $ stmsToList $ bodyStms body
resnodes = map ResNode $ namesToList $ freeIn $ bodyResult body
inputnodes = map FreeNode $ namesToList consumed
(_, (aliases, consumed)) = Alias.analyseStms mempty $ bodyStms body
getStmRes :: EdgeGenerator
getStmRes (ResNode name) = [(name, Res name)]
getStmRes _ = []
addResEdges :: Monad m => DepGraphAug m
addResEdges = augWithFun getStmRes
mkDepGraph :: (HasScope SOACS m, Monad m) => Body SOACS -> m DepGraph
mkDepGraph body = applyAugs augs $ emptyGraph body
where
augs =
[ makeMapping,
addDeps,
addConsAndAliases,
addExtraCons,
addResEdges,
]
mkDepGraphForFun :: FunDef SOACS -> DepGraph
mkDepGraphForFun f = runReader (mkDepGraph (funDefBody f)) scope
where
scope = scopeOfFParams (funDefParams f) <> scopeOf (bodyStms (funDefBody f))
| Merges two contexts .
mergedContext :: Ord b => a -> G.Context a b -> G.Context a b -> G.Context a b
mergedContext mergedlabel (inp1, n1, _, out1) (inp2, n2, _, out2) =
let new_inp = filter (\n -> snd n /= n1 && snd n /= n2) (nubOrd (inp1 <> inp2))
new_out = filter (\n -> snd n /= n1 && snd n /= n2) (nubOrd (out1 <> out2))
in (new_inp, n1, mergedlabel, new_out)
| Remove the given node , and insert the ' DepContext ' into the
in the ' DepContext ' .
contractEdge :: Monad m => G.Node -> DepContext -> DepGraphAug m
contractEdge n2 ctx dg = do
pure $ dg {dgGraph = ctx G.& G.delNodes [n1, n2] (dgGraph dg)}
data Classification
SOACInput
Other
deriving (Eq, Ord, Show)
type Classifications = S.Set (VName, Classification)
freeClassifications :: FreeIn a => a -> Classifications
freeClassifications =
S.fromList . (`zip` repeat Other) . namesToList . freeIn
stmInputs :: Stm SOACS -> Classifications
stmInputs (Let pat aux e) =
freeClassifications (pat, aux) <> expInputs e
bodyInputs :: Body SOACS -> Classifications
bodyInputs (Body _ stms res) = foldMap stmInputs stms <> freeClassifications res
expInputs :: Exp SOACS -> Classifications
expInputs (Match cond cases defbody attr) =
foldMap (bodyInputs . caseBody) cases
<> bodyInputs defbody
<> freeClassifications (cond, attr)
expInputs (DoLoop params form b1) =
freeClassifications (params, form) <> bodyInputs b1
expInputs (Op soac) = case soac of
Futhark.Screma w is form -> inputs is <> freeClassifications (w, form)
Futhark.Hist w is ops lam -> inputs is <> freeClassifications (w, ops, lam)
Futhark.Scatter w is lam iws -> inputs is <> freeClassifications (w, lam, iws)
Futhark.Stream w is nes lam ->
inputs is <> freeClassifications (w, nes, lam)
Futhark.JVP {} -> freeClassifications soac
Futhark.VJP {} -> freeClassifications soac
where
inputs = S.fromList . (`zip` repeat SOACInput)
expInputs e
| Just (arr, _) <- H.transformFromExp mempty e =
S.singleton (arr, SOACInput)
<> freeClassifications (freeIn e `namesSubtract` oneName arr)
| otherwise = freeClassifications e
stmNames :: Stm SOACS -> [VName]
stmNames = patNames . stmPat
getOutputs :: NodeT -> [VName]
getOutputs node = case node of
(StmNode stm) -> stmNames stm
(TransNode v _ _) -> [v]
(ResNode _) -> []
(FreeNode name) -> [name]
(MatchNode stm _) -> stmNames stm
(DoNode stm _) -> stmNames stm
(SoacNode _ pat _ _) -> patNames pat
isDep :: EdgeT -> Bool
isDep (Dep _) = True
isDep (Res _) = True
isDep _ = False
isInf :: (G.Node, G.Node, EdgeT) -> Bool
isInf (_, _, e) = case e of
InfDep _ -> True
_ -> False
isCons :: EdgeT -> Bool
isCons (Cons _) = True
isCons _ = False
|
60a1bf7bd15f5d009e9c4ee348ceae521f8980180ad6b3faa6f923d1bcc17840 | mindreframer/clojure-stuff | core_test.clj | (ns yesql.core-test
(:require [clojure.java.jdbc :as jdbc]
[expectations :refer :all]
[yesql.core :refer :all]))
(def derby-db {:subprotocol "derby"
:subname (gensym "memory:")
:create true})
(defquery current-time-query "yesql/sample_files/current_time.sql")
(defquery mixed-parameters-query "yesql/sample_files/mixed_parameters.sql")
;;; Check we can start up the test DB.
(expect (more-> java.sql.Timestamp (-> first :1))
(jdbc/query derby-db ["SELECT CURRENT_TIMESTAMP FROM SYSIBM.SYSDUMMY1"]))
;;; Test querying.
(expect (more-> java.util.Date
(-> first :time))
(current-time-query derby-db))
(expect (more-> java.util.Date
(-> first :time))
(mixed-parameters-query derby-db 1 2 3 4))
(expect empty?
(mixed-parameters-query derby-db 1 2 0 0))
Test Metadata .
(expect {:doc "Just selects the current time.\nNothing fancy."
:arglists '([db])}
(in (meta (var current-time-query))))
(expect {:doc "Here's a query with some named and some anonymous parameters.\n(...and some repeats.)"
:arglists '([db value1 value2 ? ?])}
(in (meta (var mixed-parameters-query))))
;; Running a query in a transaction and using the result outside of it should work as expected.
(expect-let [[{time :time}] (jdbc/with-db-transaction [connection derby-db]
(current-time-query connection))]
java.util.Date
time)
;;; Check defqueries returns the list of defined vars.
(expect-let [return-value (defqueries "yesql/sample_files/combined_file.sql")]
[(var the-time) (var sums) (var edge)]
return-value)
SQL 's quoting rules .
(defquery quoting "yesql/sample_files/quoting.sql")
(expect "'can't'"
(:word (first (quoting derby-db))))
| null | https://raw.githubusercontent.com/mindreframer/clojure-stuff/1e761b2dacbbfbeec6f20530f136767e788e0fe3/github.com/krisajenkins/yesql/test/yesql/core_test.clj | clojure | Check we can start up the test DB.
Test querying.
Running a query in a transaction and using the result outside of it should work as expected.
Check defqueries returns the list of defined vars. | (ns yesql.core-test
(:require [clojure.java.jdbc :as jdbc]
[expectations :refer :all]
[yesql.core :refer :all]))
(def derby-db {:subprotocol "derby"
:subname (gensym "memory:")
:create true})
(defquery current-time-query "yesql/sample_files/current_time.sql")
(defquery mixed-parameters-query "yesql/sample_files/mixed_parameters.sql")
(expect (more-> java.sql.Timestamp (-> first :1))
(jdbc/query derby-db ["SELECT CURRENT_TIMESTAMP FROM SYSIBM.SYSDUMMY1"]))
(expect (more-> java.util.Date
(-> first :time))
(current-time-query derby-db))
(expect (more-> java.util.Date
(-> first :time))
(mixed-parameters-query derby-db 1 2 3 4))
(expect empty?
(mixed-parameters-query derby-db 1 2 0 0))
Test Metadata .
(expect {:doc "Just selects the current time.\nNothing fancy."
:arglists '([db])}
(in (meta (var current-time-query))))
(expect {:doc "Here's a query with some named and some anonymous parameters.\n(...and some repeats.)"
:arglists '([db value1 value2 ? ?])}
(in (meta (var mixed-parameters-query))))
(expect-let [[{time :time}] (jdbc/with-db-transaction [connection derby-db]
(current-time-query connection))]
java.util.Date
time)
(expect-let [return-value (defqueries "yesql/sample_files/combined_file.sql")]
[(var the-time) (var sums) (var edge)]
return-value)
SQL 's quoting rules .
(defquery quoting "yesql/sample_files/quoting.sql")
(expect "'can't'"
(:word (first (quoting derby-db))))
|
ae9bbb488660d9f6ea7fee5b2d9e44bd5116432ce8f6bfb9db4a0c0659a7508c | tobbebex/GPipe-Core | PrimitiveArray.hs | # LANGUAGE CPP #
# LANGUAGE TypeSynonymInstances , FlexibleInstances , ScopedTypeVariables , EmptyDataDecls , TypeFamilies , GADTs #
module Graphics.GPipe.Internal.PrimitiveArray where
import Graphics.GPipe.Internal.Buffer
import Graphics.GPipe.Internal.Shader
#if __GLASGOW_HASKELL__ < 804
import Data.Semigroup
#endif
import Data.Monoid hiding ((<>))
import Data.IORef
import Data.Word
import Graphics.GL.Core33
import Graphics.GL.Types
-- | A vertex array is the basic building block for a primitive array. It is created from the contents of a 'Buffer', but unlike a 'Buffer',
-- it may be truncated, zipped with other vertex arrays, and even morphed into arrays of a different type with the provided 'Functor' instance.
-- A @VertexArray t a@ has elements of type @a@, and @t@ indicates whether the vertex array may be used as instances or not.
data VertexArray t a = VertexArray {
| Retrieve the number of elements in a ' VertexArray ' .
vertexArrayLength :: Int,
vertexArraySkip :: Int,
bArrBFunc:: BInput -> a
}
| A phantom type to indicate that a ' VertexArray ' may only be used for instances ( in ' toPrimitiveArrayInstanced ' and ' toPrimitiveArrayIndexedInstanced ' ) .
data Instances
| Create a ' VertexArray ' from a ' Buffer ' . The vertex array will have the same number of elements as the buffer , use ' takeVertices ' and ' dropVertices ' to make it smaller .
newVertexArray :: Buffer os a -> Render os (VertexArray t a)
newVertexArray buffer = Render $ return $ VertexArray (bufferLength buffer) 0 $ bufBElement buffer
instance Functor (VertexArray t) where
fmap f (VertexArray n s g) = VertexArray n s (f . g)
| Zip two ' VertexArray 's using the function given as first argument . If either of the argument ' VertexArray 's are restriced to ' Instances ' only , then so will the resulting
-- array be, as depicted by the 'Combine' type family.
zipVertices :: (a -> b -> c) -> VertexArray t a -> VertexArray t' b -> VertexArray (Combine t t') c
zipVertices h (VertexArray n s f) (VertexArray m t g) = VertexArray (min n m) totSkip newArrFun
where totSkip = min s t
newArrFun x = let baseSkip = bInSkipElems x - totSkip in h (f x { bInSkipElems = baseSkip + s}) (g x { bInSkipElems = baseSkip + t})
type family Combine t t' where
Combine () Instances = Instances
Combine Instances () = Instances
Combine Instances Instances = Instances
Combine () () = ()
| @takeVertices n a@ creates a shorter vertex array by taking the @n@ first elements of the array
takeVertices :: Int -> VertexArray t a -> VertexArray t a
takeVertices n (VertexArray l s f) = VertexArray (min (max n 0) l) s f
| @dropVertices n a@ creates a shorter vertex array by dropping the @n@ first elements of the array The argument array @a@ must not be
-- constrained to only 'Instances'.
dropVertices :: Int -> VertexArray () a -> VertexArray t a
dropVertices n (VertexArray l s f) = VertexArray (l - n') (s+n') f
where
n' = min (max n 0) l
| @replicateEach n a@ will create a longer vertex array , only to be used for instances , by replicating each element of the array times . E.g.
@replicateEach 3 { ABCD ... }@ will yield @{AAABBBCCCDDD ... }@. This is particulary useful before zipping the array with another that has a different replication rate .
replicateEach :: Int -> VertexArray t a -> VertexArray Instances a
replicateEach n (VertexArray m s f) = VertexArray (n*m) s (\x -> f $ x {bInInstanceDiv = bInInstanceDiv x * n})
type family IndexFormat a where
IndexFormat (B Word32) = Word32
IndexFormat (BPacked Word16) = Word16
IndexFormat (BPacked Word8) = Word8
-- | An index array is like a vertex array, but contains only integer indices. These indices must come from a tightly packed 'Buffer', hence the lack of
a ' Functor ' instance and no conversion from ' VertexArray 's .
data IndexArray = IndexArray {
iArrName :: IORef GLuint,
-- | Numer of indices in an 'IndexArray'.
indexArrayLength:: Int,
offset:: Int,
restart:: Maybe Int,
indexType :: GLuint
}
-- | Create an 'IndexArray' from a 'Buffer' of unsigned integers (as constrained by the closed 'IndexFormat' type family instances). The index array will have the same number of elements as the buffer, use 'takeIndices' and 'dropIndices' to make it smaller.
-- The @Maybe a@ argument is used to optionally denote a primitive restart index.
newIndexArray :: forall os f b a. (BufferFormat b, Integral a, IndexFormat b ~ a) => Buffer os b -> Maybe a -> Render os IndexArray
newIndexArray buf r = let a = undefined :: b in Render $ return $ IndexArray (bufName buf) (bufferLength buf) 0 (fmap fromIntegral r) (getGlType a)
| @takeIndices n a@ creates a shorter index array by taking the @n@ first indices of the array
takeIndices :: Int -> IndexArray -> IndexArray
takeIndices n i = i { indexArrayLength = min (max n 0) (indexArrayLength i) }
| @dropIndices n a@ creates a shorter index array by dropping the @n@ first indices of the array
dropIndices :: Int -> IndexArray -> IndexArray
dropIndices n i = i { indexArrayLength = l - n', offset = offset i + n' }
where
l = indexArrayLength i
n' = min (max n 0) l
data Triangles
data Lines
data Points
data PrimitiveTopology p where
TriangleList :: PrimitiveTopology Triangles
TriangleStrip :: PrimitiveTopology Triangles
TriangleFan :: PrimitiveTopology Triangles
LineList :: PrimitiveTopology Lines
LineStrip :: PrimitiveTopology Lines
LineLoop :: PrimitiveTopology Lines
PointList :: PrimitiveTopology Points
toGLtopology :: PrimitiveTopology p -> GLuint
toGLtopology TriangleList = GL_TRIANGLES
toGLtopology TriangleStrip = GL_TRIANGLE_STRIP
toGLtopology TriangleFan = GL_TRIANGLE_FAN
toGLtopology LineList = GL_LINES
toGLtopology LineStrip = GL_LINE_STRIP
toGLtopology LineLoop = GL_LINE_LOOP
toGLtopology PointList = GL_POINTS
Some day :
instance PrimitiveTopology TrianglesWithAdjacency where
toGLtopology = 0
data Geometry TrianglesWithAdjacency a = TriangleWithAdjacency a a a a a a
instance PrimitiveTopology LinesWithAdjacency where
toGLtopology LinesWithAdjacencyList = 0
toGLtopology LinesWithAdjacencyStrip = 1
data Geometry LinesWithAdjacency a = LineWithAdjacency a a a a
Some day:
instance PrimitiveTopology TrianglesWithAdjacency where
toGLtopology TriangleStripWithAdjacency = 0
data Geometry TrianglesWithAdjacency a = TriangleWithAdjacency a a a a a a
instance PrimitiveTopology LinesWithAdjacency where
toGLtopology LinesWithAdjacencyList = 0
toGLtopology LinesWithAdjacencyStrip = 1
data Geometry LinesWithAdjacency a = LineWithAdjacency a a a a
-}
type InstanceCount = Int
type BaseVertex = Int
data PrimitiveArrayInt p a = PrimitiveArraySimple (PrimitiveTopology p) Int BaseVertex a
| PrimitiveArrayIndexed (PrimitiveTopology p) IndexArray BaseVertex a
| PrimitiveArrayInstanced (PrimitiveTopology p) InstanceCount Int BaseVertex a
| PrimitiveArrayIndexedInstanced (PrimitiveTopology p) IndexArray InstanceCount BaseVertex a
-- | An array of primitives
newtype PrimitiveArray p a = PrimitiveArray {getPrimitiveArray :: [PrimitiveArrayInt p a]}
instance Semigroup (PrimitiveArray p a) where
PrimitiveArray a <> PrimitiveArray b = PrimitiveArray (a ++ b)
instance Monoid (PrimitiveArray p a) where
mempty = PrimitiveArray []
#if __GLASGOW_HASKELL__ < 804
mappend = (<>)
#endif
instance Functor (PrimitiveArray p) where
fmap f (PrimitiveArray xs) = PrimitiveArray $ fmap g xs
where g (PrimitiveArraySimple p l s a) = PrimitiveArraySimple p l s (f a)
g (PrimitiveArrayIndexed p i s a) = PrimitiveArrayIndexed p i s (f a)
g (PrimitiveArrayInstanced p il l s a) = PrimitiveArrayInstanced p il l s (f a)
g (PrimitiveArrayIndexedInstanced p i il s a) = PrimitiveArrayIndexedInstanced p i il s (f a)
toPrimitiveArray :: PrimitiveTopology p -> VertexArray () a -> PrimitiveArray p a
toPrimitiveArray p va = PrimitiveArray [PrimitiveArraySimple p (vertexArrayLength va) (vertexArraySkip va) (bArrBFunc va (BInput 0 0))]
toPrimitiveArrayIndexed :: PrimitiveTopology p -> IndexArray -> VertexArray () a -> PrimitiveArray p a
toPrimitiveArrayIndexed p ia va = PrimitiveArray [PrimitiveArrayIndexed p ia (vertexArraySkip va) (bArrBFunc va (BInput 0 0))]
toPrimitiveArrayInstanced :: PrimitiveTopology p -> (a -> b -> c) -> VertexArray () a -> VertexArray t b -> PrimitiveArray p c
Base instance not supported in GL < 4 , so need to burn in
toPrimitiveArrayIndexedInstanced :: PrimitiveTopology p -> IndexArray -> (a -> b -> c) -> VertexArray () a -> VertexArray t b -> PrimitiveArray p c
Base instance not supported in GL < 4 , so need to burn in
| null | https://raw.githubusercontent.com/tobbebex/GPipe-Core/4607e2c31d5beec30f2a918ab8ad48472ca236b7/GPipe-Core/src/Graphics/GPipe/Internal/PrimitiveArray.hs | haskell | | A vertex array is the basic building block for a primitive array. It is created from the contents of a 'Buffer', but unlike a 'Buffer',
it may be truncated, zipped with other vertex arrays, and even morphed into arrays of a different type with the provided 'Functor' instance.
A @VertexArray t a@ has elements of type @a@, and @t@ indicates whether the vertex array may be used as instances or not.
array be, as depicted by the 'Combine' type family.
constrained to only 'Instances'.
| An index array is like a vertex array, but contains only integer indices. These indices must come from a tightly packed 'Buffer', hence the lack of
| Numer of indices in an 'IndexArray'.
| Create an 'IndexArray' from a 'Buffer' of unsigned integers (as constrained by the closed 'IndexFormat' type family instances). The index array will have the same number of elements as the buffer, use 'takeIndices' and 'dropIndices' to make it smaller.
The @Maybe a@ argument is used to optionally denote a primitive restart index.
| An array of primitives | # LANGUAGE CPP #
# LANGUAGE TypeSynonymInstances , FlexibleInstances , ScopedTypeVariables , EmptyDataDecls , TypeFamilies , GADTs #
module Graphics.GPipe.Internal.PrimitiveArray where
import Graphics.GPipe.Internal.Buffer
import Graphics.GPipe.Internal.Shader
#if __GLASGOW_HASKELL__ < 804
import Data.Semigroup
#endif
import Data.Monoid hiding ((<>))
import Data.IORef
import Data.Word
import Graphics.GL.Core33
import Graphics.GL.Types
data VertexArray t a = VertexArray {
| Retrieve the number of elements in a ' VertexArray ' .
vertexArrayLength :: Int,
vertexArraySkip :: Int,
bArrBFunc:: BInput -> a
}
| A phantom type to indicate that a ' VertexArray ' may only be used for instances ( in ' toPrimitiveArrayInstanced ' and ' toPrimitiveArrayIndexedInstanced ' ) .
data Instances
| Create a ' VertexArray ' from a ' Buffer ' . The vertex array will have the same number of elements as the buffer , use ' takeVertices ' and ' dropVertices ' to make it smaller .
newVertexArray :: Buffer os a -> Render os (VertexArray t a)
newVertexArray buffer = Render $ return $ VertexArray (bufferLength buffer) 0 $ bufBElement buffer
instance Functor (VertexArray t) where
fmap f (VertexArray n s g) = VertexArray n s (f . g)
| Zip two ' VertexArray 's using the function given as first argument . If either of the argument ' VertexArray 's are restriced to ' Instances ' only , then so will the resulting
zipVertices :: (a -> b -> c) -> VertexArray t a -> VertexArray t' b -> VertexArray (Combine t t') c
zipVertices h (VertexArray n s f) (VertexArray m t g) = VertexArray (min n m) totSkip newArrFun
where totSkip = min s t
newArrFun x = let baseSkip = bInSkipElems x - totSkip in h (f x { bInSkipElems = baseSkip + s}) (g x { bInSkipElems = baseSkip + t})
type family Combine t t' where
Combine () Instances = Instances
Combine Instances () = Instances
Combine Instances Instances = Instances
Combine () () = ()
| @takeVertices n a@ creates a shorter vertex array by taking the @n@ first elements of the array
takeVertices :: Int -> VertexArray t a -> VertexArray t a
takeVertices n (VertexArray l s f) = VertexArray (min (max n 0) l) s f
| @dropVertices n a@ creates a shorter vertex array by dropping the @n@ first elements of the array The argument array @a@ must not be
dropVertices :: Int -> VertexArray () a -> VertexArray t a
dropVertices n (VertexArray l s f) = VertexArray (l - n') (s+n') f
where
n' = min (max n 0) l
| @replicateEach n a@ will create a longer vertex array , only to be used for instances , by replicating each element of the array times . E.g.
@replicateEach 3 { ABCD ... }@ will yield @{AAABBBCCCDDD ... }@. This is particulary useful before zipping the array with another that has a different replication rate .
replicateEach :: Int -> VertexArray t a -> VertexArray Instances a
replicateEach n (VertexArray m s f) = VertexArray (n*m) s (\x -> f $ x {bInInstanceDiv = bInInstanceDiv x * n})
type family IndexFormat a where
IndexFormat (B Word32) = Word32
IndexFormat (BPacked Word16) = Word16
IndexFormat (BPacked Word8) = Word8
a ' Functor ' instance and no conversion from ' VertexArray 's .
data IndexArray = IndexArray {
iArrName :: IORef GLuint,
indexArrayLength:: Int,
offset:: Int,
restart:: Maybe Int,
indexType :: GLuint
}
newIndexArray :: forall os f b a. (BufferFormat b, Integral a, IndexFormat b ~ a) => Buffer os b -> Maybe a -> Render os IndexArray
newIndexArray buf r = let a = undefined :: b in Render $ return $ IndexArray (bufName buf) (bufferLength buf) 0 (fmap fromIntegral r) (getGlType a)
| @takeIndices n a@ creates a shorter index array by taking the @n@ first indices of the array
takeIndices :: Int -> IndexArray -> IndexArray
takeIndices n i = i { indexArrayLength = min (max n 0) (indexArrayLength i) }
| @dropIndices n a@ creates a shorter index array by dropping the @n@ first indices of the array
dropIndices :: Int -> IndexArray -> IndexArray
dropIndices n i = i { indexArrayLength = l - n', offset = offset i + n' }
where
l = indexArrayLength i
n' = min (max n 0) l
data Triangles
data Lines
data Points
data PrimitiveTopology p where
TriangleList :: PrimitiveTopology Triangles
TriangleStrip :: PrimitiveTopology Triangles
TriangleFan :: PrimitiveTopology Triangles
LineList :: PrimitiveTopology Lines
LineStrip :: PrimitiveTopology Lines
LineLoop :: PrimitiveTopology Lines
PointList :: PrimitiveTopology Points
toGLtopology :: PrimitiveTopology p -> GLuint
toGLtopology TriangleList = GL_TRIANGLES
toGLtopology TriangleStrip = GL_TRIANGLE_STRIP
toGLtopology TriangleFan = GL_TRIANGLE_FAN
toGLtopology LineList = GL_LINES
toGLtopology LineStrip = GL_LINE_STRIP
toGLtopology LineLoop = GL_LINE_LOOP
toGLtopology PointList = GL_POINTS
Some day :
instance PrimitiveTopology TrianglesWithAdjacency where
toGLtopology = 0
data Geometry TrianglesWithAdjacency a = TriangleWithAdjacency a a a a a a
instance PrimitiveTopology LinesWithAdjacency where
toGLtopology LinesWithAdjacencyList = 0
toGLtopology LinesWithAdjacencyStrip = 1
data Geometry LinesWithAdjacency a = LineWithAdjacency a a a a
Some day:
instance PrimitiveTopology TrianglesWithAdjacency where
toGLtopology TriangleStripWithAdjacency = 0
data Geometry TrianglesWithAdjacency a = TriangleWithAdjacency a a a a a a
instance PrimitiveTopology LinesWithAdjacency where
toGLtopology LinesWithAdjacencyList = 0
toGLtopology LinesWithAdjacencyStrip = 1
data Geometry LinesWithAdjacency a = LineWithAdjacency a a a a
-}
type InstanceCount = Int
type BaseVertex = Int
data PrimitiveArrayInt p a = PrimitiveArraySimple (PrimitiveTopology p) Int BaseVertex a
| PrimitiveArrayIndexed (PrimitiveTopology p) IndexArray BaseVertex a
| PrimitiveArrayInstanced (PrimitiveTopology p) InstanceCount Int BaseVertex a
| PrimitiveArrayIndexedInstanced (PrimitiveTopology p) IndexArray InstanceCount BaseVertex a
newtype PrimitiveArray p a = PrimitiveArray {getPrimitiveArray :: [PrimitiveArrayInt p a]}
instance Semigroup (PrimitiveArray p a) where
PrimitiveArray a <> PrimitiveArray b = PrimitiveArray (a ++ b)
instance Monoid (PrimitiveArray p a) where
mempty = PrimitiveArray []
#if __GLASGOW_HASKELL__ < 804
mappend = (<>)
#endif
instance Functor (PrimitiveArray p) where
fmap f (PrimitiveArray xs) = PrimitiveArray $ fmap g xs
where g (PrimitiveArraySimple p l s a) = PrimitiveArraySimple p l s (f a)
g (PrimitiveArrayIndexed p i s a) = PrimitiveArrayIndexed p i s (f a)
g (PrimitiveArrayInstanced p il l s a) = PrimitiveArrayInstanced p il l s (f a)
g (PrimitiveArrayIndexedInstanced p i il s a) = PrimitiveArrayIndexedInstanced p i il s (f a)
toPrimitiveArray :: PrimitiveTopology p -> VertexArray () a -> PrimitiveArray p a
toPrimitiveArray p va = PrimitiveArray [PrimitiveArraySimple p (vertexArrayLength va) (vertexArraySkip va) (bArrBFunc va (BInput 0 0))]
toPrimitiveArrayIndexed :: PrimitiveTopology p -> IndexArray -> VertexArray () a -> PrimitiveArray p a
toPrimitiveArrayIndexed p ia va = PrimitiveArray [PrimitiveArrayIndexed p ia (vertexArraySkip va) (bArrBFunc va (BInput 0 0))]
toPrimitiveArrayInstanced :: PrimitiveTopology p -> (a -> b -> c) -> VertexArray () a -> VertexArray t b -> PrimitiveArray p c
Base instance not supported in GL < 4 , so need to burn in
toPrimitiveArrayIndexedInstanced :: PrimitiveTopology p -> IndexArray -> (a -> b -> c) -> VertexArray () a -> VertexArray t b -> PrimitiveArray p c
Base instance not supported in GL < 4 , so need to burn in
|
55298cb42fe990af24151067ecee7717f109f478385eed8cd277dd08ade74c12 | Octachron/codept | bundle.mli | val versioned_stdlib: int * int -> Module.named list
val stdlib : Module.dict
val bigarray : Module.dict
val num : Module.dict
val threads : Module.dict
val graphics : Module.dict
val dynlink : Module.dict
val unix : Module.dict
| null | https://raw.githubusercontent.com/Octachron/codept/5346aee9337f4bef6a2e5bb7db91625217ca499e/bundled/bundle.mli | ocaml | val versioned_stdlib: int * int -> Module.named list
val stdlib : Module.dict
val bigarray : Module.dict
val num : Module.dict
val threads : Module.dict
val graphics : Module.dict
val dynlink : Module.dict
val unix : Module.dict
|
|
658e3fd8224c8fbe63911ad2b0d80874aafd1ddd8b7d9e6e8d92ac0c7f1214de | EveryTian/Haskell-Codewars | calculate-fibonacci-return-count-of-digit-occurrences.hs | -- -fibonacci-return-count-of-digit-occurrences
module Kata (fibDigits) where
import Data.List (sortBy)
fibDigits :: Integer -> [(Integer, Integer)]
fibDigits = sortBy (flip compare) . filter ((/= 0) . fst) . (`zip` [0..9]) . count . show . (fibs !!) . fromIntegral
where
count = count' $ replicate 10 0
where
count' result [] = result
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('0':xs) = count' [n0 + 1, n1, n2, n3, n4, n5, n6, n7, n8, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('1':xs) = count' [n0, n1 + 1, n2, n3, n4, n5, n6, n7, n8, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('2':xs) = count' [n0, n1, n2 + 1, n3, n4, n5, n6, n7, n8, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('3':xs) = count' [n0, n1, n2, n3 + 1, n4, n5, n6, n7, n8, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('4':xs) = count' [n0, n1, n2, n3, n4 + 1, n5, n6, n7, n8, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('5':xs) = count' [n0, n1, n2, n3, n4, n5 + 1, n6, n7, n8, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('6':xs) = count' [n0, n1, n2, n3, n4, n5, n6 + 1, n7, n8, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('7':xs) = count' [n0, n1, n2, n3, n4, n5, n6, n7 + 1, n8, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('8':xs) = count' [n0, n1, n2, n3, n4, n5, n6, n7, n8 + 1, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('9':xs) = count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9 + 1] xs
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
| null | https://raw.githubusercontent.com/EveryTian/Haskell-Codewars/dc48d95c676ce1a59f697d07672acb6d4722893b/5kyu/calculate-fibonacci-return-count-of-digit-occurrences.hs | haskell | -fibonacci-return-count-of-digit-occurrences |
module Kata (fibDigits) where
import Data.List (sortBy)
fibDigits :: Integer -> [(Integer, Integer)]
fibDigits = sortBy (flip compare) . filter ((/= 0) . fst) . (`zip` [0..9]) . count . show . (fibs !!) . fromIntegral
where
count = count' $ replicate 10 0
where
count' result [] = result
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('0':xs) = count' [n0 + 1, n1, n2, n3, n4, n5, n6, n7, n8, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('1':xs) = count' [n0, n1 + 1, n2, n3, n4, n5, n6, n7, n8, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('2':xs) = count' [n0, n1, n2 + 1, n3, n4, n5, n6, n7, n8, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('3':xs) = count' [n0, n1, n2, n3 + 1, n4, n5, n6, n7, n8, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('4':xs) = count' [n0, n1, n2, n3, n4 + 1, n5, n6, n7, n8, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('5':xs) = count' [n0, n1, n2, n3, n4, n5 + 1, n6, n7, n8, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('6':xs) = count' [n0, n1, n2, n3, n4, n5, n6 + 1, n7, n8, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('7':xs) = count' [n0, n1, n2, n3, n4, n5, n6, n7 + 1, n8, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('8':xs) = count' [n0, n1, n2, n3, n4, n5, n6, n7, n8 + 1, n9] xs
count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9] ('9':xs) = count' [n0, n1, n2, n3, n4, n5, n6, n7, n8, n9 + 1] xs
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
|
65fc9d95cb4e8db1f6669892db8396a51882d2d4878259494c4ff1e9717116f7 | jfischoff/tmp-postgres | Main.hs | module Main where
import Control.DeepSeq
import Control.Exception
import Control.Monad
import Criterion.Main hiding (defaultConfig)
import Data.String
import Database.Postgres.Temp.Internal
import Database.Postgres.Temp.Internal.Core
import Database.Postgres.Temp.Internal.Config
import qualified Database.PostgreSQL.Simple as PG
import System.IO.Temp (createTempDirectory, withTempDirectory)
import qualified Database.PostgreSQL.Simple.Options as Options
data Once a = Once { unOnce :: a }
instance NFData (Once a) where
rnf x = seq x ()
defaultConfigDefaultInitDb :: Config
defaultConfigDefaultInitDb = mempty
{ logger = pure mempty
, postgresConfigFile = fastPostgresConfig
, initDbConfig = pure mempty
}
createFooDb :: PG.Connection -> Int -> IO ()
createFooDb conn index = void $ PG.execute_ conn $ fromString $ unlines
[ "CREATE TABLE foo" <> show index
, "( id int"
, ");"
]
migrateDb :: DB -> IO ()
migrateDb db = do
let theConnectionString = toConnectionString db
bracket (PG.connectPostgreSQL theConnectionString) PG.close $
\conn -> mapM_ (createFooDb conn) [0 .. 100]
testQuery :: DB -> IO ()
testQuery db = do
let theConnectionString = toConnectionString db
bracket (PG.connectPostgreSQL theConnectionString) PG.close $
\conn -> void $ PG.execute_ conn "INSERT INTO foo1 (id) VALUES (1)"
setupCache :: Bool -> IO Cache
setupCache cow = do
cacheInfo <- setupInitDbCache (defaultCacheConfig { cacheUseCopyOnWrite = cow})
void (withConfig (defaultConfig <> cacheConfig cacheInfo) (const $ pure ()))
pure cacheInfo
setupWithCache :: (Config -> Benchmark) -> Benchmark
setupWithCache f = envWithCleanup (setupCache True) cleanupInitDbCache $ f . (defaultConfig <>) . cacheConfig
setupWithCacheNoCow :: (Config -> Benchmark) -> Benchmark
setupWithCacheNoCow f = envWithCleanup (setupCache False) cleanupInitDbCache $ f . (defaultConfig <>) . cacheConfig
setupCacheAndSP :: IO (Cache, Snapshot, Once Config)
setupCacheAndSP = do
cacheInfo <- setupCache True
let theCacheConfig = defaultConfig <> cacheConfig cacheInfo
sp <- either throwIO pure <=< withConfig theCacheConfig $ \db -> do
migrateDb db
either throwIO pure =<< takeSnapshot db
let theConfig = defaultConfig <> snapshotConfig sp <> theCacheConfig
pure (cacheInfo, sp, Once theConfig)
cleanupCacheAndSP :: (Cache, Snapshot, Once Config) -> IO ()
cleanupCacheAndSP (x, y, _) = cleanupSnapshot y >> cleanupInitDbCache x
setupWithCacheAndSP :: (Config -> Benchmark) -> Benchmark
setupWithCacheAndSP f = envWithCleanup setupCacheAndSP cleanupCacheAndSP $ \ ~(_, _, Once x) -> f x
setupWithCacheAndSP' :: (Snapshot -> Benchmark) -> Benchmark
setupWithCacheAndSP' f = envWithCleanup setupCacheAndSP cleanupCacheAndSP $ \ ~(_, x, _) -> f x
setupCacheAndAction :: IO (Cache, FilePath, Once Config)
setupCacheAndAction = do
cacheInfo <- setupCache True
snapshotDir <- createTempDirectory "/tmp" "tmp-postgres-bench-cache"
let theCacheConfig = defaultConfig <> cacheConfig cacheInfo
theConfig <- either throwIO pure =<< cacheAction snapshotDir migrateDb theCacheConfig
pure (cacheInfo, snapshotDir, Once theConfig)
cleanupCacheAndAction :: (Cache, FilePath, Once Config) -> IO ()
cleanupCacheAndAction (c, f, _) = rmDirIgnoreErrors f >> cleanupInitDbCache c
setupWithCacheAndAction :: (FilePath -> Config -> Benchmark) -> Benchmark
setupWithCacheAndAction f = envWithCleanup setupCacheAndAction cleanupCacheAndAction $
\ ~(_, filePath, Once x) -> f filePath x
main :: IO ()
main = defaultMain
[ bench "with" $ whnfIO $ with $ const $ pure ()
, bench "withConfig no --no-sync" $ whnfIO $
withConfig defaultConfigDefaultInitDb $ const $ pure ()
, bench "withConfig verbose" $ whnfIO $
withConfig verboseConfig $ const $ pure ()
, bench "withConfig db create" $ whnfIO $
withConfig (optionsToDefaultConfig (mempty { Options.dbname = pure "test" } )) $
const $ pure ()
, setupWithCacheNoCow $ \theConfig -> bench "withConfig silent cache no cow" $ whnfIO $
withConfig theConfig $ const $ pure ()
, setupWithCache $ \theCacheConfig -> bench "withConfig silent cache" $ whnfIO $
withConfig theCacheConfig $ const $ pure ()
, setupWithCache $ \theCacheConfig -> bench "cache action and recache and cache" $ whnfIO $ withTempDirectory "/tmp" "tmp-postgres-bench-cache" $ \snapshotDir -> do
newConfig <- either throwIO pure =<< cacheAction snapshotDir migrateDb theCacheConfig
either throwIO pure =<< flip withConfig testQuery
=<< either throwIO pure =<< cacheAction snapshotDir migrateDb newConfig
, setupWithCacheAndAction $ \snapshotDir theCacheConfig -> bench "pre-cache action and recache" $ whnfIO $ do
either throwIO pure =<< flip withConfig testQuery
=<< either throwIO pure =<< cacheAction snapshotDir migrateDb theCacheConfig
, setupWithCacheAndSP $ \theConfig -> bench "withConfig pre-setup with withSnapshot" $ whnfIO $
void $ withConfig theConfig $ const $ pure ()
, setupWithCacheAndSP' $ \sp -> bench "snapshotConfig" $ whnfIO $ void $ flip withConfig (const $ pure ())
$ snapshotConfig sp
, bench "migrateDb" $ perRunEnvWithCleanup (either throwIO (pure . Once) =<< startConfig defaultConfig) (stop . unOnce) $
\ ~(Once db) -> migrateDb db
, bench "withSnapshot" $ perRunEnvWithCleanup (either throwIO (pure . Once) =<< startConfig defaultConfig) (stop . unOnce) $
\ ~(Once db) -> void $ withSnapshot db $ const $ pure ()
, bench "stopGracefully" $ perRunEnvWithCleanup (either throwIO (pure . Once) =<< start) (stop . unOnce) $
\ ~(Once db) -> do
void $ stopPostgresGracefully db
stop db
, bench "stop" $ perRunEnvWithCleanup (either throwIO (pure . Once) =<< start) (stop . unOnce) $
\ ~(Once db) -> stop db
, bench "stop serial" $ perRunEnvWithCleanup (either throwIO (pure . Once) =<< start) (stop . unOnce) $
\ ~(Once DB {..}) ->
stopPlan dbPostgresProcess >> cleanupConfig dbResources
]
| null | https://raw.githubusercontent.com/jfischoff/tmp-postgres/593e3ebcb7643afd6095f6269de3552d01c7ff40/benchmark/Main.hs | haskell | module Main where
import Control.DeepSeq
import Control.Exception
import Control.Monad
import Criterion.Main hiding (defaultConfig)
import Data.String
import Database.Postgres.Temp.Internal
import Database.Postgres.Temp.Internal.Core
import Database.Postgres.Temp.Internal.Config
import qualified Database.PostgreSQL.Simple as PG
import System.IO.Temp (createTempDirectory, withTempDirectory)
import qualified Database.PostgreSQL.Simple.Options as Options
data Once a = Once { unOnce :: a }
instance NFData (Once a) where
rnf x = seq x ()
defaultConfigDefaultInitDb :: Config
defaultConfigDefaultInitDb = mempty
{ logger = pure mempty
, postgresConfigFile = fastPostgresConfig
, initDbConfig = pure mempty
}
createFooDb :: PG.Connection -> Int -> IO ()
createFooDb conn index = void $ PG.execute_ conn $ fromString $ unlines
[ "CREATE TABLE foo" <> show index
, "( id int"
, ");"
]
migrateDb :: DB -> IO ()
migrateDb db = do
let theConnectionString = toConnectionString db
bracket (PG.connectPostgreSQL theConnectionString) PG.close $
\conn -> mapM_ (createFooDb conn) [0 .. 100]
testQuery :: DB -> IO ()
testQuery db = do
let theConnectionString = toConnectionString db
bracket (PG.connectPostgreSQL theConnectionString) PG.close $
\conn -> void $ PG.execute_ conn "INSERT INTO foo1 (id) VALUES (1)"
setupCache :: Bool -> IO Cache
setupCache cow = do
cacheInfo <- setupInitDbCache (defaultCacheConfig { cacheUseCopyOnWrite = cow})
void (withConfig (defaultConfig <> cacheConfig cacheInfo) (const $ pure ()))
pure cacheInfo
setupWithCache :: (Config -> Benchmark) -> Benchmark
setupWithCache f = envWithCleanup (setupCache True) cleanupInitDbCache $ f . (defaultConfig <>) . cacheConfig
setupWithCacheNoCow :: (Config -> Benchmark) -> Benchmark
setupWithCacheNoCow f = envWithCleanup (setupCache False) cleanupInitDbCache $ f . (defaultConfig <>) . cacheConfig
setupCacheAndSP :: IO (Cache, Snapshot, Once Config)
setupCacheAndSP = do
cacheInfo <- setupCache True
let theCacheConfig = defaultConfig <> cacheConfig cacheInfo
sp <- either throwIO pure <=< withConfig theCacheConfig $ \db -> do
migrateDb db
either throwIO pure =<< takeSnapshot db
let theConfig = defaultConfig <> snapshotConfig sp <> theCacheConfig
pure (cacheInfo, sp, Once theConfig)
cleanupCacheAndSP :: (Cache, Snapshot, Once Config) -> IO ()
cleanupCacheAndSP (x, y, _) = cleanupSnapshot y >> cleanupInitDbCache x
setupWithCacheAndSP :: (Config -> Benchmark) -> Benchmark
setupWithCacheAndSP f = envWithCleanup setupCacheAndSP cleanupCacheAndSP $ \ ~(_, _, Once x) -> f x
setupWithCacheAndSP' :: (Snapshot -> Benchmark) -> Benchmark
setupWithCacheAndSP' f = envWithCleanup setupCacheAndSP cleanupCacheAndSP $ \ ~(_, x, _) -> f x
setupCacheAndAction :: IO (Cache, FilePath, Once Config)
setupCacheAndAction = do
cacheInfo <- setupCache True
snapshotDir <- createTempDirectory "/tmp" "tmp-postgres-bench-cache"
let theCacheConfig = defaultConfig <> cacheConfig cacheInfo
theConfig <- either throwIO pure =<< cacheAction snapshotDir migrateDb theCacheConfig
pure (cacheInfo, snapshotDir, Once theConfig)
cleanupCacheAndAction :: (Cache, FilePath, Once Config) -> IO ()
cleanupCacheAndAction (c, f, _) = rmDirIgnoreErrors f >> cleanupInitDbCache c
setupWithCacheAndAction :: (FilePath -> Config -> Benchmark) -> Benchmark
setupWithCacheAndAction f = envWithCleanup setupCacheAndAction cleanupCacheAndAction $
\ ~(_, filePath, Once x) -> f filePath x
main :: IO ()
main = defaultMain
[ bench "with" $ whnfIO $ with $ const $ pure ()
, bench "withConfig no --no-sync" $ whnfIO $
withConfig defaultConfigDefaultInitDb $ const $ pure ()
, bench "withConfig verbose" $ whnfIO $
withConfig verboseConfig $ const $ pure ()
, bench "withConfig db create" $ whnfIO $
withConfig (optionsToDefaultConfig (mempty { Options.dbname = pure "test" } )) $
const $ pure ()
, setupWithCacheNoCow $ \theConfig -> bench "withConfig silent cache no cow" $ whnfIO $
withConfig theConfig $ const $ pure ()
, setupWithCache $ \theCacheConfig -> bench "withConfig silent cache" $ whnfIO $
withConfig theCacheConfig $ const $ pure ()
, setupWithCache $ \theCacheConfig -> bench "cache action and recache and cache" $ whnfIO $ withTempDirectory "/tmp" "tmp-postgres-bench-cache" $ \snapshotDir -> do
newConfig <- either throwIO pure =<< cacheAction snapshotDir migrateDb theCacheConfig
either throwIO pure =<< flip withConfig testQuery
=<< either throwIO pure =<< cacheAction snapshotDir migrateDb newConfig
, setupWithCacheAndAction $ \snapshotDir theCacheConfig -> bench "pre-cache action and recache" $ whnfIO $ do
either throwIO pure =<< flip withConfig testQuery
=<< either throwIO pure =<< cacheAction snapshotDir migrateDb theCacheConfig
, setupWithCacheAndSP $ \theConfig -> bench "withConfig pre-setup with withSnapshot" $ whnfIO $
void $ withConfig theConfig $ const $ pure ()
, setupWithCacheAndSP' $ \sp -> bench "snapshotConfig" $ whnfIO $ void $ flip withConfig (const $ pure ())
$ snapshotConfig sp
, bench "migrateDb" $ perRunEnvWithCleanup (either throwIO (pure . Once) =<< startConfig defaultConfig) (stop . unOnce) $
\ ~(Once db) -> migrateDb db
, bench "withSnapshot" $ perRunEnvWithCleanup (either throwIO (pure . Once) =<< startConfig defaultConfig) (stop . unOnce) $
\ ~(Once db) -> void $ withSnapshot db $ const $ pure ()
, bench "stopGracefully" $ perRunEnvWithCleanup (either throwIO (pure . Once) =<< start) (stop . unOnce) $
\ ~(Once db) -> do
void $ stopPostgresGracefully db
stop db
, bench "stop" $ perRunEnvWithCleanup (either throwIO (pure . Once) =<< start) (stop . unOnce) $
\ ~(Once db) -> stop db
, bench "stop serial" $ perRunEnvWithCleanup (either throwIO (pure . Once) =<< start) (stop . unOnce) $
\ ~(Once DB {..}) ->
stopPlan dbPostgresProcess >> cleanupConfig dbResources
]
|
|
59297abcb07fd6c03fe4f3aa9853ccba4f620323431e9af41034e2efddf7f469 | emaphis/HtDP2e-solutions | 08_Designing_with_Structures.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname 08_Designing_with_Structures) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
HtDP 2e - 5 Adding Structure
5.2 Designing with Structures
Exercises : 80 - 82
;; The design recipe including structures:
;; Sample Problem:
Design a function that computes the distance of objects in a 3 - dimensional
;; space to the origin.
1 . Data design
;; pieces of data that go to gether belong in a structure
(define-struct r3 [x y z])
; A R3 is a structure:
; (make-r3 Number Number Number)
(define ex1 (make-r3 1 2 13))
(define ex2 (make-r3 -1 0 3))
; R3 -> ???
#;; template for R3
(define (fn-for-r3 r)
(... (r3-x r)
(r3-y r)
(r3-z r)))
2 . Signature , purpose statement and function header :
; R3 -> Numbers
; produces the distance from an T3 to origin
; origin: (make-r3 0 0 0)
;(define (r3-distance-to-0 r) 0)
3 . Use the examples to creat tests
(check-within (r3-distance-to-0 (make-r3 0 0 0)) 0 0.01)
(check-within (inexact->exact (r3-distance-to-0 ex1)) 13.19 0.01)
(check-within (inexact->exact (r3-distance-to-0 ex2)) 3.162 0.01)
4 . create a template
#;;
(define (r3-distance-to-0 r)
(... (... (r3-x r)) ; Number
(... (r3-y r)) ; Number
(... (r3-z r)))) ; Number
5 . Use the selector expressions from the template
(define (r3-distance-to-0 r)
(sqrt (+ (sqr (r3-x r)) ; Number
(sqr (r3-y r)) ; Number
(sqr (r3-z r)))))
6 . Test !
See exercise 80 , 81 , 82
| null | https://raw.githubusercontent.com/emaphis/HtDP2e-solutions/ecb60b9a7bbf9b8999c0122b6ea152a3301f0a68/1-Fixed-Size-Data/05-Adding-Structure/08_Designing_with_Structures.rkt | racket | about the language level of this file in a form that our tools can easily process.
The design recipe including structures:
Sample Problem:
space to the origin.
pieces of data that go to gether belong in a structure
A R3 is a structure:
(make-r3 Number Number Number)
R3 -> ???
template for R3
R3 -> Numbers
produces the distance from an T3 to origin
origin: (make-r3 0 0 0)
(define (r3-distance-to-0 r) 0)
Number
Number
Number
Number
Number | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-reader.ss" "lang")((modname 08_Designing_with_Structures) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
HtDP 2e - 5 Adding Structure
5.2 Designing with Structures
Exercises : 80 - 82
Design a function that computes the distance of objects in a 3 - dimensional
1 . Data design
(define-struct r3 [x y z])
(define ex1 (make-r3 1 2 13))
(define ex2 (make-r3 -1 0 3))
(define (fn-for-r3 r)
(... (r3-x r)
(r3-y r)
(r3-z r)))
2 . Signature , purpose statement and function header :
3 . Use the examples to creat tests
(check-within (r3-distance-to-0 (make-r3 0 0 0)) 0 0.01)
(check-within (inexact->exact (r3-distance-to-0 ex1)) 13.19 0.01)
(check-within (inexact->exact (r3-distance-to-0 ex2)) 3.162 0.01)
4 . create a template
(define (r3-distance-to-0 r)
5 . Use the selector expressions from the template
(define (r3-distance-to-0 r)
(sqr (r3-z r)))))
6 . Test !
See exercise 80 , 81 , 82
|
9d55a4e425a0b70c033e1824986da4abec61c91f57cf57893a200071fa6ed253 | ndmitchell/uniplate | Timer.hs |
module Uniplate.Timer(getTime, timer, dp2) where
import Data.Time.Clock.POSIX(getPOSIXTime)
import Numeric
getTime :: IO Double
getTime = (fromRational . toRational) `fmap` getPOSIXTime
timer :: IO a -> IO Double
timer x = do
start <- getTime
x
stop <- getTime
return $ stop - start
dp2 x = showFFloat (Just 2) x ""
| null | https://raw.githubusercontent.com/ndmitchell/uniplate/7d3039606d7a083f6d77f9f960c919668788de91/Uniplate/Timer.hs | haskell |
module Uniplate.Timer(getTime, timer, dp2) where
import Data.Time.Clock.POSIX(getPOSIXTime)
import Numeric
getTime :: IO Double
getTime = (fromRational . toRational) `fmap` getPOSIXTime
timer :: IO a -> IO Double
timer x = do
start <- getTime
x
stop <- getTime
return $ stop - start
dp2 x = showFFloat (Just 2) x ""
|
|
8e074c98e57b458c3ce4a9da6eb25f93ddc619205f620ede1b2aa5e51d583cf0 | ygrek/mldonkey | mp3tagui.mli | (**************************************************************************)
Copyright 2003 , 2002 b8_bavard , , , b52_simon INRIA
(* *)
(* This file is part of mldonkey. *)
(* *)
is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation ; either version 2 of the License ,
(* or (at your option) any later version. *)
(* *)
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 mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston ,
MA 02111 - 1307 USA
(* *)
(**************************************************************************)
(** Graphical user interface functions. *)
(** A type to indicate which tag we want to read and write.*)
type id3 =
* Id3 version 1
* Id3 version 2
* Both id3 versions 1 and 2
(** Make the user edit the tag of the given file. *)
val edit_file : id3 -> string -> unit
(** Make the user edit the given v1 tag in a window with the given title. *)
val edit_tag_v1 : string -> Mp3tag.Id3v1.tag -> unit
(** Make the user edit the given v2 tag in a window with the given title. *)
val edit_tag_v2 : string -> Mp3tag.Id3v2.tag -> Mp3tag.Id3v2.tag
| null | https://raw.githubusercontent.com/ygrek/mldonkey/333868a12bb6cd25fed49391dd2c3a767741cb51/src/utils/mp3tagui/mp3tagui.mli | ocaml | ************************************************************************
This file is part of mldonkey.
or (at your option) any later version.
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.
************************************************************************
* Graphical user interface functions.
* A type to indicate which tag we want to read and write.
* Make the user edit the tag of the given file.
* Make the user edit the given v1 tag in a window with the given title.
* Make the user edit the given v2 tag in a window with the given title. | Copyright 2003 , 2002 b8_bavard , , , b52_simon INRIA
is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation ; either version 2 of the License ,
is distributed in the hope that it will be useful ,
You should have received a copy of the GNU General Public License
along with mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston ,
MA 02111 - 1307 USA
type id3 =
* Id3 version 1
* Id3 version 2
* Both id3 versions 1 and 2
val edit_file : id3 -> string -> unit
val edit_tag_v1 : string -> Mp3tag.Id3v1.tag -> unit
val edit_tag_v2 : string -> Mp3tag.Id3v2.tag -> Mp3tag.Id3v2.tag
|
78a891792ceb90509c86f0829253a7248512ddaeb2a43b5ff31661956dfebae2 | serokell/qtah | QGraphicsView.hs | This file is part of Qtah .
--
Copyright 2015 - 2018 The Qtah Authors .
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation , either version 3 of the License , or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details .
--
You should have received a copy of the GNU Lesser General Public License
-- along with this program. If not, see </>.
module Graphics.UI.Qtah.Generator.Interface.Widgets.QGraphicsView (
aModule,
c_QGraphicsView,
e_DragMode,
e_ViewportAnchor,
e_ViewportUpdateMode,
e_OptimizationFlag,
e_CacheModeFlag,
bs_CacheMode,
bs_OptimizationFlags
) where
import Foreign.Hoppy.Generator.Spec (
Export (ExportClass, ExportEnum, ExportBitspace),
addReqIncludes,
classSetEntityPrefix,
ident,
ident1,
includeStd,
makeClass,
mkMethod,
mkMethod',
mkConstMethod,
mkConstMethod',
mkCtor
)
import Foreign.Hoppy.Generator.Types (
objT,
constT,
ptrT,
intT,
voidT,
enumT,
boolT,
bitspaceT,
)
import Graphics.UI.Qtah.Generator.Interface.Core.Types hiding (aModule)
import Graphics.UI.Qtah.Generator.Interface.Core.QPoint (c_QPoint)
import Graphics.UI.Qtah.Generator.Interface.Core.QPointF (c_QPointF)
import Graphics.UI.Qtah.Generator.Interface.Core.QRect (c_QRect)
import Graphics.UI.Qtah.Generator.Interface.Core.QRectF (c_QRectF)
import Graphics.UI.Qtah.Generator.Interface.Gui.QBrush (c_QBrush)
import Graphics.UI.Qtah.Generator.Interface.Gui.QPainter (c_QPainter, e_RenderHint, bs_RenderHints)
import Graphics.UI.Qtah.Generator.Interface.Gui.QPolygon (c_QPolygon)
import Graphics.UI.Qtah.Generator.Interface.Gui.QPolygonF (c_QPolygonF)
import Graphics.UI.Qtah.Generator.Interface.Gui.QTransform (c_QTransform)
import Graphics . UI.Qtah . Generator . Interface . . QPainter
import Graphics.UI.Qtah.Generator.Interface.Gui.QPainterPath (c_QPainterPath)
import Graphics.UI.Qtah.Generator.Interface.Widgets.QAbstractScrollArea (c_QAbstractScrollArea)
import Graphics.UI.Qtah.Generator.Interface.Widgets.QGraphicsItem (c_QGraphicsItem)
import Graphics.UI.Qtah.Generator.Interface.Widgets.QGraphicsScene (c_QGraphicsScene)
import Graphics.UI.Qtah.Generator.Interface.Widgets.QWidget (c_QWidget)
import Graphics.UI.Qtah.Generator.Module (AModule (AQtModule), makeQtModule)
import Graphics.UI.Qtah.Generator.Types
{-# ANN module "HLint: ignore Use camelCase" #-}
aModule =
AQtModule $
makeQtModule ["Widgets", "QGraphicsView"] $
(QtExport $ ExportClass c_QGraphicsView) :
map (QtExport . ExportEnum)
[ e_CacheModeFlag
, e_DragMode
, e_OptimizationFlag
, e_ViewportAnchor
, e_ViewportUpdateMode
] ++
map (QtExport . ExportBitspace)
[ bs_CacheMode
, bs_OptimizationFlags
]
c_QGraphicsView =
addReqIncludes [includeStd "QGraphicsView"] $
classSetEntityPrefix "" $
makeClass (ident "QGraphicsView") Nothing [c_QAbstractScrollArea]
[ mkCtor "new" []
, mkCtor "newWithScene" [ptrT $ objT c_QGraphicsScene]
, mkCtor "newWithParent" [ptrT $ objT c_QWidget]
, mkCtor "newWithSceneAndParent" [ptrT $ objT c_QGraphicsScene, ptrT $ objT c_QWidget]
, mkConstMethod "alignment" [] $ bitspaceT bs_Alignment
, mkConstMethod "backgroundBrush" [] $ objT c_QBrush
, mkConstMethod "cacheMode" [] $ bitspaceT bs_CacheMode
, mkMethod' "centerOn" "centerOnPointF" [objT c_QPointF] voidT
, mkMethod' "centerOn" "centerOnRaw" [qreal, qreal] voidT
, mkMethod' "centerOn" "centerOnItem" [ptrT $ constT $ objT c_QGraphicsItem] voidT
, mkConstMethod "dragMode" [] $ enumT e_DragMode
, mkMethod' "ensureVisible" "ensureVisibleRectF" [objT c_QRectF] voidT
, mkMethod' "ensureVisible" "ensureVisibleRaw"
[qreal, qreal, qreal, qreal] voidT
, mkMethod' "ensureVisible" "ensureVisibleItem"
[ptrT $ constT $ objT c_QGraphicsItem] voidT
, mkMethod' "ensureVisible" "ensureVisibleRectFAll"
[objT c_QRectF, intT, intT] voidT
, mkMethod' "ensureVisible" "ensureVisibleRawAll"
[qreal, qreal, qreal, qreal, intT, intT] voidT
, mkMethod' "ensureVisible" "ensureVisibleItemAll"
[ptrT $ constT $ objT c_QGraphicsItem, intT, intT] voidT
, mkMethod' "fitInView" "fitInViewRectF" [objT c_QRectF] voidT
, mkMethod' "fitInView" "fitInViewRect" [qreal, qreal, qreal, qreal] voidT
, mkMethod' "fitInView" "fitInViewItem" [ptrT $ constT $ objT c_QGraphicsItem] voidT
, mkMethod' "fitInView" "fitInViewRectFAll" [objT c_QRectF, enumT e_AspectRatioMode] voidT
, mkMethod' "fitInView" "fitInViewRectAll"
[qreal, qreal, qreal, qreal, enumT e_AspectRatioMode] voidT
, mkMethod' "fitInView" "fitInViewItemAll"
[ptrT $ constT $ objT c_QGraphicsItem, enumT e_AspectRatioMode] voidT
, mkConstMethod "foregroundBrush" [] $ objT c_QBrush
, mkConstMethod "isInteractive" [] boolT
, mkConstMethod "isTransformed" [] boolT
, mkConstMethod' "itemAt" "itemAtPoint" [objT c_QPoint] $ ptrT $ objT c_QGraphicsItem
, mkConstMethod' "itemAt" "itemAtRaw" [intT, intT] $ ptrT $ objT c_QGraphicsItem
TODO mkConstMethod " items " [ ] $ objT c_QList < QGraphicsItem $ objT c _ * >
TODO mkConstMethod " items " [ objT ] $ objT c_QList < QGraphicsItem $ objT c _ * >
TODO mkConstMethod " items " [ intT , intT ] $ objT c_QList < QGraphicsItem $ objT c _ * >
TODO mkConstMethod " items " [ intT , intT , intT , , objT c_Qt::ItemSelectionMode ] $
-- objT c_QList<QGraphicsItem $ objT c_*>
TODO mkConstMethod " items " [ objT , objT c_Qt::ItemSelectionMode ] $
-- objT c_QList<QGraphicsItem $ objT c_*>
TODO mkConstMethod " items " [ objT , objT c_Qt::ItemSelectionMode ] $
-- objT c_QList<QGraphicsItem $ objT c_*>
TODO mkConstMethod " items " [ objT c_QPainterPath , objT c_Qt::ItemSelectionMode ] $
-- objT c_QList<QGraphicsItem $ objT c_*>
, mkConstMethod' "mapFromScene" "mapFromScenePointF"
[objT c_QPointF] $ objT c_QPoint
, mkConstMethod' "mapFromScene" "mapFromSceneRectF"
[objT c_QRectF] $ objT c_QPolygon
, mkConstMethod' "mapFromScene" "mapFromScenePolygonF"
[objT c_QPolygonF] $ objT c_QPolygon
, mkConstMethod' "mapFromScene" "mapFromScenePainterPath"
[objT c_QPainterPath] $ objT c_QPainterPath
, mkConstMethod' "mapFromScene" "mapFromScenePointFRaw"
[qreal, qreal] $ objT c_QPoint
, mkConstMethod' "mapFromScene" "mapFromSceneRectFRaw"
[qreal, qreal, qreal, qreal] $ objT c_QPolygon
, mkConstMethod' "mapToScene" "mapToScenePoint"
[objT c_QPoint] $ objT c_QPointF
, mkConstMethod' "mapToScene" "mapToSceneRect"
[objT c_QRect] $ objT c_QPolygonF
, mkConstMethod' "mapToScene" "mapToScenePolygon"
[objT c_QPolygon] $ objT c_QPolygonF
, mkConstMethod' "mapToScene" "mapToScenePainterPath"
[objT c_QPainterPath] $ objT c_QPainterPath
, mkConstMethod' "mapToScene" "mapToScenePointRaw"
[intT, intT] $ objT c_QPointF
, mkConstMethod' "mapToScene" "mapToSceneRectRaw"
[intT, intT, intT, intT] $ objT c_QPolygonF
TODO mkConstMethod " matrix " [ ] $ objT c_QMatrix
, mkConstMethod "optimizationFlags" [] $ bitspaceT bs_OptimizationFlags
, mkMethod "render" [ptrT $ objT c_QPainter] voidT
, mkMethod' "render" "renderAll"
[ptrT $ objT c_QPainter, objT c_QRectF, objT c_QRect, enumT e_AspectRatioMode] voidT
, mkConstMethod "renderHints" [] $ bitspaceT bs_RenderHints
, mkMethod "resetCachedContent" [] voidT
, mkMethod "resetMatrix" [] voidT
, mkMethod "resetTransform" [] voidT
, mkConstMethod "resizeAnchor" [] $ enumT e_ViewportAnchor
, mkMethod "rotate" [qreal] voidT
TODO mkConstMethod " rubberBandSelectionMode " [ ] $ objT c_Qt::ItemSelectionMode
, mkMethod "scale" [qreal, qreal] voidT
, mkConstMethod "scene" [] $ ptrT $ objT c_QGraphicsScene
, mkConstMethod "sceneRect" [] $ objT c_QRectF
, mkMethod "setAlignment" [bitspaceT bs_Alignment] voidT
, mkMethod "setBackgroundBrush" [objT c_QBrush] voidT
, mkMethod "setCacheMode" [bitspaceT bs_CacheMode] voidT
, mkMethod "setDragMode" [enumT e_DragMode] voidT
, mkMethod "setForegroundBrush" [objT c_QBrush] voidT
, mkMethod "setInteractive" [boolT] voidT
TODO mkMethod " setMatrix " [ objT c_QMatrix ] voidT
TODO mkMethod ' " setMatrix " " setMatrixAll " [ objT c_QMatrix , boolT ] voidT
, mkMethod "setOptimizationFlag" [enumT e_OptimizationFlag] voidT
, mkMethod' "setOptimizationFlag" "setOptimizationFlagAll" [enumT e_OptimizationFlag, boolT] voidT
, mkMethod "setOptimizationFlags" [bitspaceT bs_OptimizationFlags] voidT
, mkMethod "setRenderHint" [enumT e_RenderHint] voidT
, mkMethod' "setRenderHint" "setRenderHintAll" [enumT e_RenderHint, boolT] voidT
, mkMethod "setRenderHints" [bitspaceT bs_RenderHints] voidT
, mkMethod "setResizeAnchor" [enumT e_ViewportAnchor] voidT
TODO mkMethod " setRubberBandSelectionMode " [ objT c_Qt::ItemSelectionMode ] voidT
, mkMethod "setScene" [ptrT $ objT c_QGraphicsScene] voidT
, mkMethod' "setSceneRect" "setSceneRectF" [objT c_QRectF] voidT
, mkMethod' "setSceneRect" "setSceneRectRaw" [qreal, qreal, qreal, qreal] voidT
, mkMethod "setTransform" [objT c_QTransform] voidT
, mkMethod' "setTransform" "setTransformAll" [objT c_QTransform, boolT] voidT
, mkMethod "setTransformationAnchor" [enumT e_ViewportAnchor] voidT
, mkMethod "setViewportUpdateMode" [enumT e_ViewportUpdateMode] voidT
, mkMethod "shear" [qreal, qreal] voidT
, mkConstMethod "transform" [] $ objT c_QTransform
, mkConstMethod "transformationAnchor" [] $ enumT e_ViewportAnchor
, mkMethod "translate" [qreal, qreal] voidT
, mkConstMethod "viewportTransform" [] $ objT c_QTransform
]
(e_CacheModeFlag, bs_CacheMode) =
makeQtEnumBitspace (ident1 "QGraphicsView" "CacheModeFlag") "CacheMode"
[includeStd "QGraphicsView"]
[ (0x0, ["cache","none"])
, (0x1, ["cache","background"])
]
e_DragMode =
makeQtEnum (ident1 "QGraphicsView" "DragMode") [includeStd "QGraphicsView"]
[ (0, ["no", "drag"])
, (1, ["scroll", "hand", "drag"])
, (2, ["rubber", "band", "drag"])
]
(e_OptimizationFlag, bs_OptimizationFlags) =
makeQtEnumBitspace (ident1 "QGraphicsView" "OptimizationFlag") "OptimizationFlags"
[includeStd "QGraphicsView"]
[ (0x1, ["dont","clip","painter"])
, (0x2, ["dont","save","painter","state"])
, (0x4, ["dont","adjust","for","antialiasing"])
, (0x8, ["indirect","painting"])
]
e_ViewportAnchor =
makeQtEnum (ident1 "QGraphicsView" "ViewportAnchor")
[includeStd "QGraphicsView"]
[ (0, ["no", "anchor"])
, (1, ["anchor", "view", "center"])
, (2, ["anchor", "under", "mouse"])
]
e_ViewportUpdateMode =
makeQtEnum (ident1 "QGraphicsView" "ViewportUpdateMode")
[includeStd "QGraphicsView"]
[ (0, ["full","viewport","update"])
, (1, ["minimal","viewport","update"])
, (2, ["smart","viewport","update"])
, (4, ["bounding","rect","viewport","update"])
, (3, ["no","viewport","update"])
]
-- Methods with optional arguments that weren't handled properly in the bindings above
-- (i.e. `foo` + `fooAll`).
QList < QGraphicsItem * > items
( int x , int y , int w , int h , Qt::ItemSelectionMode mode = Qt::IntersectsItemShape ) const
QList < QGraphicsItem * > items
( const QRect & rect , Qt::ItemSelectionMode mode = Qt::IntersectsItemShape ) const
QList < QGraphicsItem * > items
( const QPolygon & polygon , Qt::ItemSelectionMode mode = Qt::IntersectsItemShape ) const
QList < QGraphicsItem * > items
( const QPainterPath & path , Qt::ItemSelectionMode mode = Qt::IntersectsItemShape ) const
QList<QGraphicsItem *> items
(int x, int y, int w, int h, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const
QList<QGraphicsItem *> items
(const QRect & rect, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const
QList<QGraphicsItem *> items
(const QPolygon & polygon, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const
QList<QGraphicsItem *> items
(const QPainterPath & path, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const
-}
| null | https://raw.githubusercontent.com/serokell/qtah/abb4932248c82dc5c662a20d8f177acbc7cfa722/qtah-generator/src/Graphics/UI/Qtah/Generator/Interface/Widgets/QGraphicsView.hs | haskell |
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see </>.
# ANN module "HLint: ignore Use camelCase" #
objT c_QList<QGraphicsItem $ objT c_*>
objT c_QList<QGraphicsItem $ objT c_*>
objT c_QList<QGraphicsItem $ objT c_*>
objT c_QList<QGraphicsItem $ objT c_*>
Methods with optional arguments that weren't handled properly in the bindings above
(i.e. `foo` + `fooAll`). | This file is part of Qtah .
Copyright 2015 - 2018 The Qtah Authors .
the Free Software Foundation , either version 3 of the License , or
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public License
module Graphics.UI.Qtah.Generator.Interface.Widgets.QGraphicsView (
aModule,
c_QGraphicsView,
e_DragMode,
e_ViewportAnchor,
e_ViewportUpdateMode,
e_OptimizationFlag,
e_CacheModeFlag,
bs_CacheMode,
bs_OptimizationFlags
) where
import Foreign.Hoppy.Generator.Spec (
Export (ExportClass, ExportEnum, ExportBitspace),
addReqIncludes,
classSetEntityPrefix,
ident,
ident1,
includeStd,
makeClass,
mkMethod,
mkMethod',
mkConstMethod,
mkConstMethod',
mkCtor
)
import Foreign.Hoppy.Generator.Types (
objT,
constT,
ptrT,
intT,
voidT,
enumT,
boolT,
bitspaceT,
)
import Graphics.UI.Qtah.Generator.Interface.Core.Types hiding (aModule)
import Graphics.UI.Qtah.Generator.Interface.Core.QPoint (c_QPoint)
import Graphics.UI.Qtah.Generator.Interface.Core.QPointF (c_QPointF)
import Graphics.UI.Qtah.Generator.Interface.Core.QRect (c_QRect)
import Graphics.UI.Qtah.Generator.Interface.Core.QRectF (c_QRectF)
import Graphics.UI.Qtah.Generator.Interface.Gui.QBrush (c_QBrush)
import Graphics.UI.Qtah.Generator.Interface.Gui.QPainter (c_QPainter, e_RenderHint, bs_RenderHints)
import Graphics.UI.Qtah.Generator.Interface.Gui.QPolygon (c_QPolygon)
import Graphics.UI.Qtah.Generator.Interface.Gui.QPolygonF (c_QPolygonF)
import Graphics.UI.Qtah.Generator.Interface.Gui.QTransform (c_QTransform)
import Graphics . UI.Qtah . Generator . Interface . . QPainter
import Graphics.UI.Qtah.Generator.Interface.Gui.QPainterPath (c_QPainterPath)
import Graphics.UI.Qtah.Generator.Interface.Widgets.QAbstractScrollArea (c_QAbstractScrollArea)
import Graphics.UI.Qtah.Generator.Interface.Widgets.QGraphicsItem (c_QGraphicsItem)
import Graphics.UI.Qtah.Generator.Interface.Widgets.QGraphicsScene (c_QGraphicsScene)
import Graphics.UI.Qtah.Generator.Interface.Widgets.QWidget (c_QWidget)
import Graphics.UI.Qtah.Generator.Module (AModule (AQtModule), makeQtModule)
import Graphics.UI.Qtah.Generator.Types
aModule =
AQtModule $
makeQtModule ["Widgets", "QGraphicsView"] $
(QtExport $ ExportClass c_QGraphicsView) :
map (QtExport . ExportEnum)
[ e_CacheModeFlag
, e_DragMode
, e_OptimizationFlag
, e_ViewportAnchor
, e_ViewportUpdateMode
] ++
map (QtExport . ExportBitspace)
[ bs_CacheMode
, bs_OptimizationFlags
]
c_QGraphicsView =
addReqIncludes [includeStd "QGraphicsView"] $
classSetEntityPrefix "" $
makeClass (ident "QGraphicsView") Nothing [c_QAbstractScrollArea]
[ mkCtor "new" []
, mkCtor "newWithScene" [ptrT $ objT c_QGraphicsScene]
, mkCtor "newWithParent" [ptrT $ objT c_QWidget]
, mkCtor "newWithSceneAndParent" [ptrT $ objT c_QGraphicsScene, ptrT $ objT c_QWidget]
, mkConstMethod "alignment" [] $ bitspaceT bs_Alignment
, mkConstMethod "backgroundBrush" [] $ objT c_QBrush
, mkConstMethod "cacheMode" [] $ bitspaceT bs_CacheMode
, mkMethod' "centerOn" "centerOnPointF" [objT c_QPointF] voidT
, mkMethod' "centerOn" "centerOnRaw" [qreal, qreal] voidT
, mkMethod' "centerOn" "centerOnItem" [ptrT $ constT $ objT c_QGraphicsItem] voidT
, mkConstMethod "dragMode" [] $ enumT e_DragMode
, mkMethod' "ensureVisible" "ensureVisibleRectF" [objT c_QRectF] voidT
, mkMethod' "ensureVisible" "ensureVisibleRaw"
[qreal, qreal, qreal, qreal] voidT
, mkMethod' "ensureVisible" "ensureVisibleItem"
[ptrT $ constT $ objT c_QGraphicsItem] voidT
, mkMethod' "ensureVisible" "ensureVisibleRectFAll"
[objT c_QRectF, intT, intT] voidT
, mkMethod' "ensureVisible" "ensureVisibleRawAll"
[qreal, qreal, qreal, qreal, intT, intT] voidT
, mkMethod' "ensureVisible" "ensureVisibleItemAll"
[ptrT $ constT $ objT c_QGraphicsItem, intT, intT] voidT
, mkMethod' "fitInView" "fitInViewRectF" [objT c_QRectF] voidT
, mkMethod' "fitInView" "fitInViewRect" [qreal, qreal, qreal, qreal] voidT
, mkMethod' "fitInView" "fitInViewItem" [ptrT $ constT $ objT c_QGraphicsItem] voidT
, mkMethod' "fitInView" "fitInViewRectFAll" [objT c_QRectF, enumT e_AspectRatioMode] voidT
, mkMethod' "fitInView" "fitInViewRectAll"
[qreal, qreal, qreal, qreal, enumT e_AspectRatioMode] voidT
, mkMethod' "fitInView" "fitInViewItemAll"
[ptrT $ constT $ objT c_QGraphicsItem, enumT e_AspectRatioMode] voidT
, mkConstMethod "foregroundBrush" [] $ objT c_QBrush
, mkConstMethod "isInteractive" [] boolT
, mkConstMethod "isTransformed" [] boolT
, mkConstMethod' "itemAt" "itemAtPoint" [objT c_QPoint] $ ptrT $ objT c_QGraphicsItem
, mkConstMethod' "itemAt" "itemAtRaw" [intT, intT] $ ptrT $ objT c_QGraphicsItem
TODO mkConstMethod " items " [ ] $ objT c_QList < QGraphicsItem $ objT c _ * >
TODO mkConstMethod " items " [ objT ] $ objT c_QList < QGraphicsItem $ objT c _ * >
TODO mkConstMethod " items " [ intT , intT ] $ objT c_QList < QGraphicsItem $ objT c _ * >
TODO mkConstMethod " items " [ intT , intT , intT , , objT c_Qt::ItemSelectionMode ] $
TODO mkConstMethod " items " [ objT , objT c_Qt::ItemSelectionMode ] $
TODO mkConstMethod " items " [ objT , objT c_Qt::ItemSelectionMode ] $
TODO mkConstMethod " items " [ objT c_QPainterPath , objT c_Qt::ItemSelectionMode ] $
, mkConstMethod' "mapFromScene" "mapFromScenePointF"
[objT c_QPointF] $ objT c_QPoint
, mkConstMethod' "mapFromScene" "mapFromSceneRectF"
[objT c_QRectF] $ objT c_QPolygon
, mkConstMethod' "mapFromScene" "mapFromScenePolygonF"
[objT c_QPolygonF] $ objT c_QPolygon
, mkConstMethod' "mapFromScene" "mapFromScenePainterPath"
[objT c_QPainterPath] $ objT c_QPainterPath
, mkConstMethod' "mapFromScene" "mapFromScenePointFRaw"
[qreal, qreal] $ objT c_QPoint
, mkConstMethod' "mapFromScene" "mapFromSceneRectFRaw"
[qreal, qreal, qreal, qreal] $ objT c_QPolygon
, mkConstMethod' "mapToScene" "mapToScenePoint"
[objT c_QPoint] $ objT c_QPointF
, mkConstMethod' "mapToScene" "mapToSceneRect"
[objT c_QRect] $ objT c_QPolygonF
, mkConstMethod' "mapToScene" "mapToScenePolygon"
[objT c_QPolygon] $ objT c_QPolygonF
, mkConstMethod' "mapToScene" "mapToScenePainterPath"
[objT c_QPainterPath] $ objT c_QPainterPath
, mkConstMethod' "mapToScene" "mapToScenePointRaw"
[intT, intT] $ objT c_QPointF
, mkConstMethod' "mapToScene" "mapToSceneRectRaw"
[intT, intT, intT, intT] $ objT c_QPolygonF
TODO mkConstMethod " matrix " [ ] $ objT c_QMatrix
, mkConstMethod "optimizationFlags" [] $ bitspaceT bs_OptimizationFlags
, mkMethod "render" [ptrT $ objT c_QPainter] voidT
, mkMethod' "render" "renderAll"
[ptrT $ objT c_QPainter, objT c_QRectF, objT c_QRect, enumT e_AspectRatioMode] voidT
, mkConstMethod "renderHints" [] $ bitspaceT bs_RenderHints
, mkMethod "resetCachedContent" [] voidT
, mkMethod "resetMatrix" [] voidT
, mkMethod "resetTransform" [] voidT
, mkConstMethod "resizeAnchor" [] $ enumT e_ViewportAnchor
, mkMethod "rotate" [qreal] voidT
TODO mkConstMethod " rubberBandSelectionMode " [ ] $ objT c_Qt::ItemSelectionMode
, mkMethod "scale" [qreal, qreal] voidT
, mkConstMethod "scene" [] $ ptrT $ objT c_QGraphicsScene
, mkConstMethod "sceneRect" [] $ objT c_QRectF
, mkMethod "setAlignment" [bitspaceT bs_Alignment] voidT
, mkMethod "setBackgroundBrush" [objT c_QBrush] voidT
, mkMethod "setCacheMode" [bitspaceT bs_CacheMode] voidT
, mkMethod "setDragMode" [enumT e_DragMode] voidT
, mkMethod "setForegroundBrush" [objT c_QBrush] voidT
, mkMethod "setInteractive" [boolT] voidT
TODO mkMethod " setMatrix " [ objT c_QMatrix ] voidT
TODO mkMethod ' " setMatrix " " setMatrixAll " [ objT c_QMatrix , boolT ] voidT
, mkMethod "setOptimizationFlag" [enumT e_OptimizationFlag] voidT
, mkMethod' "setOptimizationFlag" "setOptimizationFlagAll" [enumT e_OptimizationFlag, boolT] voidT
, mkMethod "setOptimizationFlags" [bitspaceT bs_OptimizationFlags] voidT
, mkMethod "setRenderHint" [enumT e_RenderHint] voidT
, mkMethod' "setRenderHint" "setRenderHintAll" [enumT e_RenderHint, boolT] voidT
, mkMethod "setRenderHints" [bitspaceT bs_RenderHints] voidT
, mkMethod "setResizeAnchor" [enumT e_ViewportAnchor] voidT
TODO mkMethod " setRubberBandSelectionMode " [ objT c_Qt::ItemSelectionMode ] voidT
, mkMethod "setScene" [ptrT $ objT c_QGraphicsScene] voidT
, mkMethod' "setSceneRect" "setSceneRectF" [objT c_QRectF] voidT
, mkMethod' "setSceneRect" "setSceneRectRaw" [qreal, qreal, qreal, qreal] voidT
, mkMethod "setTransform" [objT c_QTransform] voidT
, mkMethod' "setTransform" "setTransformAll" [objT c_QTransform, boolT] voidT
, mkMethod "setTransformationAnchor" [enumT e_ViewportAnchor] voidT
, mkMethod "setViewportUpdateMode" [enumT e_ViewportUpdateMode] voidT
, mkMethod "shear" [qreal, qreal] voidT
, mkConstMethod "transform" [] $ objT c_QTransform
, mkConstMethod "transformationAnchor" [] $ enumT e_ViewportAnchor
, mkMethod "translate" [qreal, qreal] voidT
, mkConstMethod "viewportTransform" [] $ objT c_QTransform
]
(e_CacheModeFlag, bs_CacheMode) =
makeQtEnumBitspace (ident1 "QGraphicsView" "CacheModeFlag") "CacheMode"
[includeStd "QGraphicsView"]
[ (0x0, ["cache","none"])
, (0x1, ["cache","background"])
]
e_DragMode =
makeQtEnum (ident1 "QGraphicsView" "DragMode") [includeStd "QGraphicsView"]
[ (0, ["no", "drag"])
, (1, ["scroll", "hand", "drag"])
, (2, ["rubber", "band", "drag"])
]
(e_OptimizationFlag, bs_OptimizationFlags) =
makeQtEnumBitspace (ident1 "QGraphicsView" "OptimizationFlag") "OptimizationFlags"
[includeStd "QGraphicsView"]
[ (0x1, ["dont","clip","painter"])
, (0x2, ["dont","save","painter","state"])
, (0x4, ["dont","adjust","for","antialiasing"])
, (0x8, ["indirect","painting"])
]
e_ViewportAnchor =
makeQtEnum (ident1 "QGraphicsView" "ViewportAnchor")
[includeStd "QGraphicsView"]
[ (0, ["no", "anchor"])
, (1, ["anchor", "view", "center"])
, (2, ["anchor", "under", "mouse"])
]
e_ViewportUpdateMode =
makeQtEnum (ident1 "QGraphicsView" "ViewportUpdateMode")
[includeStd "QGraphicsView"]
[ (0, ["full","viewport","update"])
, (1, ["minimal","viewport","update"])
, (2, ["smart","viewport","update"])
, (4, ["bounding","rect","viewport","update"])
, (3, ["no","viewport","update"])
]
QList < QGraphicsItem * > items
( int x , int y , int w , int h , Qt::ItemSelectionMode mode = Qt::IntersectsItemShape ) const
QList < QGraphicsItem * > items
( const QRect & rect , Qt::ItemSelectionMode mode = Qt::IntersectsItemShape ) const
QList < QGraphicsItem * > items
( const QPolygon & polygon , Qt::ItemSelectionMode mode = Qt::IntersectsItemShape ) const
QList < QGraphicsItem * > items
( const QPainterPath & path , Qt::ItemSelectionMode mode = Qt::IntersectsItemShape ) const
QList<QGraphicsItem *> items
(int x, int y, int w, int h, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const
QList<QGraphicsItem *> items
(const QRect & rect, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const
QList<QGraphicsItem *> items
(const QPolygon & polygon, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const
QList<QGraphicsItem *> items
(const QPainterPath & path, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const
-}
|
408ef76b25111e974a03bc408a5a2c1cbb89932f7a2073b52adad83b2ea98adb | imdea-software/leap | Core.ml |
(***********************************************************************)
(* *)
LEAP
(* *)
, IMDEA Software Institute
(* *)
(* *)
Copyright 2011 IMDEA Software Institute
(* *)
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 *)
(* *)
(* -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. *)
(* *)
(***********************************************************************)
open LeapLib
open Printf
module E = Expression
module PE = PosExpression
module SolOpt = SolverOptions
type file_kind_t = Inv | Axiom
type proof_info_t =
{
cutoff : Smp.cutoff_strategy_t;
}
type proof_obligation_t =
{
vc : Tactics.vc_info; (* Maybe it could contain less information in the future *)
obligations : E.formula list;
proof_info : proof_info_t;
}
type solved_proof_obligation_t =
{
vc_info : Tactics.vc_info;
solved_obligations : (E.formula * Result.info_t) list;
result : Result.info_t;
}
module GenOptions :
sig
val sys : System.t
val focus : Expression.pc_t list
val ignore : Expression.pc_t list
val abs : System.abstraction
val hide_pres : bool
val output_file : string
val inv_folder : string
val axiom_file : string
val axiom_folder : string
val dp : DP.t
val pSolver : string
val tSolver : string
val compute_model : bool
val group_vars : bool
val forget_primed_mem : bool
val default_cutoff : Smp.cutoff_strategy_t
val use_quantifiers : bool
val output_vcs : bool
val stop_on_invalid : bool
val arrangement_gen : bool
end
=
struct
let sys = System.empty_system ()
let focus = []
let ignore = []
let abs = System.NoAbstraction
let hide_pres = true
let output_file = ""
let inv_folder = ""
let axiom_file = ""
let axiom_folder = ""
let dp = DP.NoDP
let pSolver = BackendSolvers.Yices.identifier
let tSolver = BackendSolvers.Z3.identifier
let compute_model = false
let group_vars = false
let forget_primed_mem = true
let default_cutoff = Tactics.default_cutoff_algorithm
let use_quantifiers = false
let output_vcs = false
let stop_on_invalid = false
let arrangement_gen = false
end
module type S =
sig
exception No_invariant_folder
exception No_axiom_folder
val new_proof_info : Smp.cutoff_strategy_t option -> proof_info_t
val new_proof_obligation : Tactics.vc_info ->
Expression.formula list ->
proof_info_t ->
proof_obligation_t
val obligations : proof_obligation_t -> Expression.formula list
val lines_to_consider : int list
val requires_theta : bool
val report_vcs : Tactics.vc_info list -> unit
val decl_tag : file_kind_t -> Tag.f_tag option -> Expression.formula ->
System.var_table_t -> unit
val is_def_tag : Tag.f_tag -> bool
val read_tag : file_kind_t -> Tag.f_tag -> Expression.formula
val read_tags_and_group_by_file : file_kind_t -> Tag.f_tag list -> Expression.formula list
val read_tag_info : file_kind_t -> Tag.f_tag -> Tag.f_info
val system : System.t
val theta : Expression.ThreadSet.t -> (Expression.formula * Expression.ThreadSet.t)
val rho : System.seq_or_conc_t ->
Expression.ThreadSet.t ->
int ->
Expression.ThreadSet.elt ->
Expression.formula list
val solve_proof_obligations : proof_obligation_t list ->
solved_proof_obligation_t list
end
module Make (Opt:module type of GenOptions) : S =
struct
module Eparser = ExprParser
module Elexer = ExprLexer
exception No_invariant_folder
exception No_axiom_folder
(************************************************)
(* TAGGING INFORMATION *)
(************************************************)
let tags : Tag.tag_table = Tag.tag_table_new ()
let axiom_tags : Tag.tag_table = Tag.tag_table_new ()
let axioms : Axioms.t ref = ref (Axioms.empty_axioms ())
let choose_table (k:file_kind_t) : Tag.tag_table =
match k with
| Inv -> tags
| Axiom -> axiom_tags
let tags_num () : int = Tag.tag_table_size tags
let axiom_num () : int = Tag.tag_table_size axiom_tags
let decl_tag (k : file_kind_t)
(t : Tag.f_tag option)
(phi : E.formula)
(vTbl:System.var_table_t) : unit =
let tbl = choose_table k in
match t with
| None -> ()
| Some tag -> if Tag.tag_table_mem tbl tag
then
raise(Tag.Duplicated_tag(Tag.tag_id tag))
else Tag.tag_table_add tbl tag phi (Tag.new_info vTbl)
let read_tag (k : file_kind_t) (t : Tag.f_tag) : E.formula =
let tbl = choose_table k in
if Tag.tag_table_mem tbl t then
Tag.tag_table_get_formula tbl t
else
raise(Tag.Undefined_tag(Tag.tag_id t))
let read_tags_and_group_by_file (k : file_kind_t)
(ts : Tag.f_tag list) : E.formula list =
let supp_tbl : (string, E.formula list) Hashtbl.t = Hashtbl.create 5 in
List.iter (fun tag ->
let master_id = Tag.master_id tag in
try
Hashtbl.replace supp_tbl master_id ((read_tag k tag)::(Hashtbl.find supp_tbl master_id))
with Not_found -> Hashtbl.add supp_tbl master_id [read_tag k tag]
) ts;
Hashtbl.fold (fun _ phi_list xs ->
(Formula.conj_list phi_list) :: xs
) supp_tbl []
let read_tag_info (k : file_kind_t) (t : Tag.f_tag) : Tag.f_info =
let tbl = choose_table k in
if Tag.tag_table_mem tbl t then
Tag.tag_table_get_info tbl t
else
raise(Tag.Undefined_tag(Tag.tag_id t))
let rad_supp_tags ( ts : Tag.f_tag list ) : E.formula list =
let is_def_tag (t:Tag.f_tag) : bool =
Tag.tag_table_mem tags t
let clear_tags () : unit =
Tag.tag_table_clear tags
let load_tags_from_folder (k:file_kind_t) (folder:string) : unit =
let all_files = Array.fold_left (fun xs f ->
(folder ^ "/" ^ f)::xs
) [] (Sys.readdir folder) in
let suffix = match k with
| Inv -> "inv"
| Axiom -> "axm" in
let files = List.filter (fun s -> Filename.check_suffix s suffix) all_files in
let rule = match k with
| Inv -> Eparser.invariant
| Axiom -> Eparser.axiom in
List.iter (fun i ->
let (phiVars, tag, phi_decls) = Parser.open_and_parse i
(rule Elexer.norm) in
let phi = Formula.conj_list (List.map snd phi_decls) in
List.iter (fun (subtag,subphi) -> decl_tag k subtag subphi phiVars) phi_decls;
decl_tag k tag phi phiVars
) files
(********************)
CONFIGURATION
(********************)
let (requires_theta, lines_to_consider) =
E.gen_focus_list (System.get_trans_num Opt.sys)
Opt.focus Opt.ignore
let posSolver : (module PosSolver.S) = PosSolver.choose Opt.pSolver
let numSolver : (module NumSolver.S) = NumSolver.choose Opt.pSolver
let pairsSolver: (module PairsSolver.S) = PairsSolver.choose Opt.pSolver
let tllSolver : (module TllSolver.S) = TllSolver.choose Opt.tSolver
let tslkSolver : (module TslkSolver.S) = TslkSolver.choose Opt.tSolver
(DP.get_tslk_param Opt.dp)
let calls_counter : DP.call_tbl_t = DP.new_call_tbl()
let prog_type : Bridge.prog_type = match Opt.dp with
| DP.Num -> Bridge.Num
| DP.Pairs -> Bridge.Num
| _ -> Bridge.Heap
let _ = Tactics.set_fixed_voc
(List.fold_left (fun set v ->
E.ThreadSet.add (E.VarTh v) set
) E.ThreadSet.empty (System.get_vars_of_sort Opt.sys E.Tid))
( List.map ( fun v - > E.VarTh v )
( System.get_vars_of_sort Opt.sys E.Tid ) )
(List.map (fun v -> E.VarTh v)
(System.get_vars_of_sort Opt.sys E.Tid))
*)
let _ = Tactics.set_fixed_voc ( List.map ( fun v - > E.VarTh v )
( System.get_vars_of_sort Opt.sys E.Tid ) )
let _ = Tactics.set_fixed_voc (List.map (fun v -> E.VarTh v)
(System.get_vars_of_sort Opt.sys E.Tid))
*)
(*****************************)
INITIALIZATION CODE
(*****************************)
let _ =
if Opt.inv_folder <> "" then begin
if Sys.is_directory Opt.inv_folder then begin
load_tags_from_folder Inv Opt.inv_folder
end else begin
Interface.Err.msg "Not a valid invariant folder" $
sprintf "%s is not a valid folder." Opt.inv_folder;
raise(No_invariant_folder)
end
end;
if Opt.axiom_folder <> "" then begin
if Sys.is_directory Opt.axiom_folder then begin
load_tags_from_folder Axiom Opt.axiom_folder
end else begin
Interface.Err.msg "Not a valid axiom folder" $
sprintf "%s is not a valid folder." Opt.axiom_folder;
raise(No_axiom_folder)
end
end;
if Opt.axiom_file <> "" then begin
try
axioms := Parser.open_and_parse Opt.axiom_file
(IGraphParser.axioms IGraphLexer.norm)
with _ -> begin
Interface.Err.msg "Not a valid axiom file" $
sprintf "%s is not a valid file with axioms." Opt.axiom_file;
raise(No_axiom_folder)
end
end
(******************)
(******************)
let new_proof_obligation (vc:Tactics.vc_info)
(obligations:E.formula list)
(proof_info:proof_info_t) : proof_obligation_t =
{
vc = vc;
obligations = obligations;
proof_info = proof_info;
}
let obligations (po:proof_obligation_t) : E.formula list =
po.obligations
let new_solved_proof_obligation (vc_info:Tactics.vc_info)
(solved_oblig:(E.formula * Result.info_t) list)
(result:Result.info_t) : solved_proof_obligation_t =
{
vc_info = vc_info;
solved_obligations = solved_oblig;
result = result;
}
(*********************)
PRETTY
(*********************)
let proof_obligation_to_str (po:proof_obligation_t) : string =
Printf.sprintf
("== Proof obligation ===================================================\n\
%s\n\
-- Obligations --------------------------------------------------------\n\
%s\n\
=========================================================================\n")
(Tactics.vc_info_to_str po.vc)
(String.concat "\n" (List.map E.formula_to_str po.obligations))
(*************)
(* REPORTS *)
(*************)
let report_vcs (vcs:Tactics.vc_info list) : unit =
if Opt.output_vcs then
Tactics.vc_info_list_to_folder Opt.output_file vcs
(*************************)
(* AUXILIARY FUNCTIONS *)
(*************************)
let set_status (res:Valid.t) : Result.status_t =
if Valid.is_valid res then Result.Valid Opt.dp else Result.Invalid
let add_calls (n:int) : unit =
DP.add_dp_calls calls_counter Opt.dp n
let system : System.t =
Opt.sys
let theta (voc:E.ThreadSet.t) : (E.formula * E.ThreadSet.t) =
let theta = System.gen_theta (System.SOpenArray (E.ThreadSet.elements voc)) Opt.sys Opt.abs in
let voc = E.ThreadSet.union voc (E.voc theta) in
let init_pos = if E.ThreadSet.is_empty voc then
[E.pc_form 1 E.V.Shared false]
else
E.V.VarSet.fold (fun v xs ->
E.pc_form 1 (E.V.Local v) false :: xs
) (E.voc_to_vars voc) [] in
(Formula.conj_list (theta::init_pos), voc)
let rho (seq_or_conc:System.seq_or_conc_t)
(voc:E.ThreadSet.t)
(line:int)
(th:E.ThreadSet.elt) : E.formula list =
System.gen_rho Opt.sys (System.SOpenArray (E.ThreadSet.elements voc))
seq_or_conc prog_type line Opt.abs Opt.hide_pres th
(**********************)
(* SOLVER REASONING *)
(**********************)
let decide_cutoff (cutoff:Smp.cutoff_strategy_t option) : Smp.cutoff_strategy_t =
match cutoff with
| None -> Opt.default_cutoff
| Some cut -> cut
let new_proof_info (cutoff:Smp.cutoff_strategy_t option) : proof_info_t =
{
cutoff = decide_cutoff cutoff;
}
let solve_proof_obligations (to_analyze:proof_obligation_t list)
: solved_proof_obligation_t list =
let module Pos = (val posSolver) in
let module Num = (val numSolver) in
let module Pairs = (val pairsSolver) in
let module Tll = (val tllSolver) in
let module Tslk = (val tslkSolver) in
Num.compute_model(Opt.compute_model);
Pairs.compute_model(Opt.compute_model);
Tll.compute_model(Opt.compute_model);
Tslk.compute_model(Opt.compute_model);
TslSolver.compute_model(Opt.compute_model);
ThmSolver.compute_model(Opt.compute_model);
(*
print_endline ("FORMULA TAGS: " ^ (string_of_int (Tag.tag_table_size tags)));
print_endline ("AXIOM TAGS: " ^ (string_of_int (Tag.tag_table_size axiom_tags)));
*)
let axiom_table = Axioms.new_axiom_table axiom_tags in
print_endline "Analyzing VCs...";
let case_timer = new LeapLib.timer in
let phi_timer = new LeapLib.timer in
(* Clear the internal data *)
DP.clear_call_tbl calls_counter;
(* Clear the internal data *)
let prog_lines = (System.get_trans_num Opt.sys) in
let vc_counter = ref 0 in
let oblig_counter = ref 0 in
let show_progress = not (LeapVerbose.is_verbose_enabled()) in
Progress.init (List.length to_analyze);
let result =
List.map (fun case ->
let orig_id = Tactics.get_original_vc_id case.vc in
let cutoff = case.proof_info.cutoff in
let this_calls_counter = DP.new_call_tbl() in
if LeapVerbose.is_verbose_level_enabled(LeapVerbose._SHORT_INFO) then
Report.report_vc_header !vc_counter case.vc (List.length case.obligations);
case_timer#start;
let obligation_counter = ref 1 in
let res_list =
List.map (fun phi_obligation ->
(* TODO: Choose the right to_plain function *)
if LeapVerbose.is_verbose_level_enabled(LeapVerbose._SHORT_INFO) then
Report.report_obligation_header !obligation_counter phi_obligation;
let fol_phi = phi_obligation in
(* We apply axioms if possible *)
let phi_tag = Tactics.get_vc_tag case.vc in
let vc_line = Tactics.get_line_from_info case.vc in
let ax_tags = Axioms.lookup !axioms phi_tag vc_line in
(*let _ = print_endline (Axioms.axiom_table_to_str axiom_table) in*)
print_endline ( " FOL_PHI:\n " ^ ( E.formula_to_str fol_phi ) ) ;
let (axiom_list,res_phi) =
List.fold_left (fun (axs, psi) (ax_tag,ax_kind) ->
let (ax_psi, psi') = Axioms.apply axiom_table psi ax_tag ax_kind in
(ax_psi::axs, psi')
) ([], fol_phi) ax_tags in
let axiom_phi = Formula.conj_list axiom_list in
let fol_phi = match axiom_phi with
| Formula.True -> res_phi
| _ -> Formula.Implies (axiom_phi, res_phi) in
(*print_endline ("FOL_PHI_WITH_AXIOMS:\n" ^ (E.formula_to_str fol_phi));*)
(* Solver options *)
let opt = SolOpt.new_opt () in
SolOpt.set_lines opt prog_lines;
SolOpt.set_cutoff_strategy opt cutoff;
SolOpt.set_use_quantifiers opt Opt.use_quantifiers;
SolOpt.set_use_arrangement_generator opt Opt.arrangement_gen;
Axiom application finishes
phi_timer#start;
let status =
if Valid.is_valid (Pos.check_valid prog_lines
(fst (PE.keep_locations fol_phi))) then begin
DP.add_dp_calls this_calls_counter DP.Loc 1 ~vc_id:orig_id;
Result.Valid DP.Loc
end else begin
let (validity, calls) =
match Opt.dp with
| DP.NoDP ->
(Valid.Invalid, 0)
| DP.Loc ->
(Valid.Invalid, 0)
| DP.Num ->
let num_phi = NumInterface.formula_to_int_formula fol_phi in
let (res, calls) = Num.check_valid_with_lines_plus_info
prog_lines num_phi in
if Valid.is_unknown res then begin
let z3NumSolver : (module NumSolver.S) =
NumSolver.choose BackendSolvers.Z3.identifier in
let module Z3Num = (val z3NumSolver) in
Z3Num.compute_model(Opt.compute_model);
Z3Num.check_valid_with_lines_plus_info prog_lines num_phi
end else
(res, calls)
| DP.Pairs ->
let pairs_phi = PairsInterface.formula_to_pairs_formula fol_phi in
let (res, calls) = Pairs.check_valid_with_lines_plus_info
prog_lines pairs_phi in
if Valid.is_unknown res then begin
let z3PairsSolver : (module PairsSolver.S) =
PairsSolver.choose BackendSolvers.Z3.identifier in
let module Z3Pairs = (val z3PairsSolver) in
Z3Pairs.compute_model(Opt.compute_model);
Z3Pairs.check_valid_with_lines_plus_info prog_lines pairs_phi
end else
(res, calls)
| DP.Tll ->
let tll_phi = TLLInterface.formula_to_tll_formula fol_phi in
Tll.check_valid_plus_info opt tll_phi
| DP.Tsl ->
let tsl_phi = TSLInterface.formula_to_tsl_formula fol_phi in
let (res,tsl_calls,tslk_calls) =
TslSolver.check_valid_plus_info opt tsl_phi in
DP.combine_call_table tslk_calls this_calls_counter;
(res, tsl_calls)
| DP.Tslk k ->
(* Check that the "k" DP parameter is enough for all
* levels in the formula *)
if k < Tslk.TslkExp.k then
Interface.Err.msg "Decision procedure not powerful enough" $
sprintf "A formula in TSLK[%i] cannot be analyzed with a \
TSLK[%i] decision procedure. Will proceed with \
TSLK[%i]." Tslk.TslkExp.k k Tslk.TslkExp.k;
let module TSLKIntf = TSLKInterface.Make(Tslk.TslkExp) in
let tslk_phi = TSLKIntf.formula_to_tslk_formula fol_phi in
Tslk.check_valid_plus_info opt tslk_phi
| DP.Thm ->
let thm_phi = THMInterface.formula_to_thm_formula fol_phi in
let (res,thm_calls,tll_calls) =
ThmSolver.check_valid_plus_info opt thm_phi in
DP.combine_call_table tll_calls this_calls_counter;
(res, thm_calls)
in
let _ = match Opt.dp with
| DP.NoDP -> ()
| DP.Loc -> ()
| DP.Num -> Num.print_model()
| DP.Pairs -> Pairs.print_model()
| DP.Tll -> Tll.print_model()
| DP.Tsl -> TslSolver.print_model()
| DP.Tslk _ -> Tslk.print_model()
| DP.Thm -> ThmSolver.print_model() in
DP.add_dp_calls this_calls_counter Opt.dp calls ~vc_id:orig_id;
if Opt.stop_on_invalid && (not (Valid.is_valid validity)) then begin
print_endline "!!! Process stopped because an invalid VC was found !!!";
exit (-1)
end;
set_status validity
end in
(* Analyze the formula *)
phi_timer#stop;
let time = phi_timer#elapsed_time in
if LeapVerbose.is_verbose_level_enabled(LeapVerbose._SHORT_INFO) then
Report.report_obligation_tail status time;
incr obligation_counter;
let phi_result = Result.new_info status time in
(phi_obligation, phi_result)
) case.obligations in
case_timer#stop;
oblig_counter := !oblig_counter + (List.length case.obligations);
let forall_res f = List.for_all (fun (_,info) -> f info) res_list in
let exist_res f = List.exists (fun (_,info) -> f info) res_list in
let vc_validity = if forall_res Result.is_valid then
Result.Valid Opt.dp
else if exist_res Result.is_invalid then
Result.Invalid
else
Result.Unverified in
let case_result = Result.new_info vc_validity (case_timer#elapsed_time) in
let res = new_solved_proof_obligation case.vc res_list case_result in
DP.combine_call_table this_calls_counter calls_counter;
if show_progress then
Progress.current (!vc_counter);
if LeapVerbose.is_verbose_level_enabled(LeapVerbose._SHORT_INFO) then
Report.report_vc_tail !vc_counter (List.map snd res_list) this_calls_counter;
incr vc_counter;
res
) to_analyze in
Report.report_summary (!oblig_counter)
(List.map (fun r -> r.result) result) calls_counter;
result
end
| null | https://raw.githubusercontent.com/imdea-software/leap/5f946163c0f80ff9162db605a75b7ce2e27926ef/src/Core.ml | ocaml | *********************************************************************
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
either express or implied.
See the License for the specific language governing permissions
and limitations under the License.
*********************************************************************
Maybe it could contain less information in the future
**********************************************
TAGGING INFORMATION
**********************************************
******************
******************
***************************
***************************
****************
****************
*******************
*******************
***********
REPORTS
***********
***********************
AUXILIARY FUNCTIONS
***********************
********************
SOLVER REASONING
********************
print_endline ("FORMULA TAGS: " ^ (string_of_int (Tag.tag_table_size tags)));
print_endline ("AXIOM TAGS: " ^ (string_of_int (Tag.tag_table_size axiom_tags)));
Clear the internal data
Clear the internal data
TODO: Choose the right to_plain function
We apply axioms if possible
let _ = print_endline (Axioms.axiom_table_to_str axiom_table) in
print_endline ("FOL_PHI_WITH_AXIOMS:\n" ^ (E.formula_to_str fol_phi));
Solver options
Check that the "k" DP parameter is enough for all
* levels in the formula
Analyze the formula |
LEAP
, IMDEA Software Institute
Copyright 2011 IMDEA Software Institute
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND ,
open LeapLib
open Printf
module E = Expression
module PE = PosExpression
module SolOpt = SolverOptions
type file_kind_t = Inv | Axiom
type proof_info_t =
{
cutoff : Smp.cutoff_strategy_t;
}
type proof_obligation_t =
{
obligations : E.formula list;
proof_info : proof_info_t;
}
type solved_proof_obligation_t =
{
vc_info : Tactics.vc_info;
solved_obligations : (E.formula * Result.info_t) list;
result : Result.info_t;
}
module GenOptions :
sig
val sys : System.t
val focus : Expression.pc_t list
val ignore : Expression.pc_t list
val abs : System.abstraction
val hide_pres : bool
val output_file : string
val inv_folder : string
val axiom_file : string
val axiom_folder : string
val dp : DP.t
val pSolver : string
val tSolver : string
val compute_model : bool
val group_vars : bool
val forget_primed_mem : bool
val default_cutoff : Smp.cutoff_strategy_t
val use_quantifiers : bool
val output_vcs : bool
val stop_on_invalid : bool
val arrangement_gen : bool
end
=
struct
let sys = System.empty_system ()
let focus = []
let ignore = []
let abs = System.NoAbstraction
let hide_pres = true
let output_file = ""
let inv_folder = ""
let axiom_file = ""
let axiom_folder = ""
let dp = DP.NoDP
let pSolver = BackendSolvers.Yices.identifier
let tSolver = BackendSolvers.Z3.identifier
let compute_model = false
let group_vars = false
let forget_primed_mem = true
let default_cutoff = Tactics.default_cutoff_algorithm
let use_quantifiers = false
let output_vcs = false
let stop_on_invalid = false
let arrangement_gen = false
end
module type S =
sig
exception No_invariant_folder
exception No_axiom_folder
val new_proof_info : Smp.cutoff_strategy_t option -> proof_info_t
val new_proof_obligation : Tactics.vc_info ->
Expression.formula list ->
proof_info_t ->
proof_obligation_t
val obligations : proof_obligation_t -> Expression.formula list
val lines_to_consider : int list
val requires_theta : bool
val report_vcs : Tactics.vc_info list -> unit
val decl_tag : file_kind_t -> Tag.f_tag option -> Expression.formula ->
System.var_table_t -> unit
val is_def_tag : Tag.f_tag -> bool
val read_tag : file_kind_t -> Tag.f_tag -> Expression.formula
val read_tags_and_group_by_file : file_kind_t -> Tag.f_tag list -> Expression.formula list
val read_tag_info : file_kind_t -> Tag.f_tag -> Tag.f_info
val system : System.t
val theta : Expression.ThreadSet.t -> (Expression.formula * Expression.ThreadSet.t)
val rho : System.seq_or_conc_t ->
Expression.ThreadSet.t ->
int ->
Expression.ThreadSet.elt ->
Expression.formula list
val solve_proof_obligations : proof_obligation_t list ->
solved_proof_obligation_t list
end
module Make (Opt:module type of GenOptions) : S =
struct
module Eparser = ExprParser
module Elexer = ExprLexer
exception No_invariant_folder
exception No_axiom_folder
let tags : Tag.tag_table = Tag.tag_table_new ()
let axiom_tags : Tag.tag_table = Tag.tag_table_new ()
let axioms : Axioms.t ref = ref (Axioms.empty_axioms ())
let choose_table (k:file_kind_t) : Tag.tag_table =
match k with
| Inv -> tags
| Axiom -> axiom_tags
let tags_num () : int = Tag.tag_table_size tags
let axiom_num () : int = Tag.tag_table_size axiom_tags
let decl_tag (k : file_kind_t)
(t : Tag.f_tag option)
(phi : E.formula)
(vTbl:System.var_table_t) : unit =
let tbl = choose_table k in
match t with
| None -> ()
| Some tag -> if Tag.tag_table_mem tbl tag
then
raise(Tag.Duplicated_tag(Tag.tag_id tag))
else Tag.tag_table_add tbl tag phi (Tag.new_info vTbl)
let read_tag (k : file_kind_t) (t : Tag.f_tag) : E.formula =
let tbl = choose_table k in
if Tag.tag_table_mem tbl t then
Tag.tag_table_get_formula tbl t
else
raise(Tag.Undefined_tag(Tag.tag_id t))
let read_tags_and_group_by_file (k : file_kind_t)
(ts : Tag.f_tag list) : E.formula list =
let supp_tbl : (string, E.formula list) Hashtbl.t = Hashtbl.create 5 in
List.iter (fun tag ->
let master_id = Tag.master_id tag in
try
Hashtbl.replace supp_tbl master_id ((read_tag k tag)::(Hashtbl.find supp_tbl master_id))
with Not_found -> Hashtbl.add supp_tbl master_id [read_tag k tag]
) ts;
Hashtbl.fold (fun _ phi_list xs ->
(Formula.conj_list phi_list) :: xs
) supp_tbl []
let read_tag_info (k : file_kind_t) (t : Tag.f_tag) : Tag.f_info =
let tbl = choose_table k in
if Tag.tag_table_mem tbl t then
Tag.tag_table_get_info tbl t
else
raise(Tag.Undefined_tag(Tag.tag_id t))
let rad_supp_tags ( ts : Tag.f_tag list ) : E.formula list =
let is_def_tag (t:Tag.f_tag) : bool =
Tag.tag_table_mem tags t
let clear_tags () : unit =
Tag.tag_table_clear tags
let load_tags_from_folder (k:file_kind_t) (folder:string) : unit =
let all_files = Array.fold_left (fun xs f ->
(folder ^ "/" ^ f)::xs
) [] (Sys.readdir folder) in
let suffix = match k with
| Inv -> "inv"
| Axiom -> "axm" in
let files = List.filter (fun s -> Filename.check_suffix s suffix) all_files in
let rule = match k with
| Inv -> Eparser.invariant
| Axiom -> Eparser.axiom in
List.iter (fun i ->
let (phiVars, tag, phi_decls) = Parser.open_and_parse i
(rule Elexer.norm) in
let phi = Formula.conj_list (List.map snd phi_decls) in
List.iter (fun (subtag,subphi) -> decl_tag k subtag subphi phiVars) phi_decls;
decl_tag k tag phi phiVars
) files
CONFIGURATION
let (requires_theta, lines_to_consider) =
E.gen_focus_list (System.get_trans_num Opt.sys)
Opt.focus Opt.ignore
let posSolver : (module PosSolver.S) = PosSolver.choose Opt.pSolver
let numSolver : (module NumSolver.S) = NumSolver.choose Opt.pSolver
let pairsSolver: (module PairsSolver.S) = PairsSolver.choose Opt.pSolver
let tllSolver : (module TllSolver.S) = TllSolver.choose Opt.tSolver
let tslkSolver : (module TslkSolver.S) = TslkSolver.choose Opt.tSolver
(DP.get_tslk_param Opt.dp)
let calls_counter : DP.call_tbl_t = DP.new_call_tbl()
let prog_type : Bridge.prog_type = match Opt.dp with
| DP.Num -> Bridge.Num
| DP.Pairs -> Bridge.Num
| _ -> Bridge.Heap
let _ = Tactics.set_fixed_voc
(List.fold_left (fun set v ->
E.ThreadSet.add (E.VarTh v) set
) E.ThreadSet.empty (System.get_vars_of_sort Opt.sys E.Tid))
( List.map ( fun v - > E.VarTh v )
( System.get_vars_of_sort Opt.sys E.Tid ) )
(List.map (fun v -> E.VarTh v)
(System.get_vars_of_sort Opt.sys E.Tid))
*)
let _ = Tactics.set_fixed_voc ( List.map ( fun v - > E.VarTh v )
( System.get_vars_of_sort Opt.sys E.Tid ) )
let _ = Tactics.set_fixed_voc (List.map (fun v -> E.VarTh v)
(System.get_vars_of_sort Opt.sys E.Tid))
*)
INITIALIZATION CODE
let _ =
if Opt.inv_folder <> "" then begin
if Sys.is_directory Opt.inv_folder then begin
load_tags_from_folder Inv Opt.inv_folder
end else begin
Interface.Err.msg "Not a valid invariant folder" $
sprintf "%s is not a valid folder." Opt.inv_folder;
raise(No_invariant_folder)
end
end;
if Opt.axiom_folder <> "" then begin
if Sys.is_directory Opt.axiom_folder then begin
load_tags_from_folder Axiom Opt.axiom_folder
end else begin
Interface.Err.msg "Not a valid axiom folder" $
sprintf "%s is not a valid folder." Opt.axiom_folder;
raise(No_axiom_folder)
end
end;
if Opt.axiom_file <> "" then begin
try
axioms := Parser.open_and_parse Opt.axiom_file
(IGraphParser.axioms IGraphLexer.norm)
with _ -> begin
Interface.Err.msg "Not a valid axiom file" $
sprintf "%s is not a valid file with axioms." Opt.axiom_file;
raise(No_axiom_folder)
end
end
let new_proof_obligation (vc:Tactics.vc_info)
(obligations:E.formula list)
(proof_info:proof_info_t) : proof_obligation_t =
{
vc = vc;
obligations = obligations;
proof_info = proof_info;
}
let obligations (po:proof_obligation_t) : E.formula list =
po.obligations
let new_solved_proof_obligation (vc_info:Tactics.vc_info)
(solved_oblig:(E.formula * Result.info_t) list)
(result:Result.info_t) : solved_proof_obligation_t =
{
vc_info = vc_info;
solved_obligations = solved_oblig;
result = result;
}
PRETTY
let proof_obligation_to_str (po:proof_obligation_t) : string =
Printf.sprintf
("== Proof obligation ===================================================\n\
%s\n\
-- Obligations --------------------------------------------------------\n\
%s\n\
=========================================================================\n")
(Tactics.vc_info_to_str po.vc)
(String.concat "\n" (List.map E.formula_to_str po.obligations))
let report_vcs (vcs:Tactics.vc_info list) : unit =
if Opt.output_vcs then
Tactics.vc_info_list_to_folder Opt.output_file vcs
let set_status (res:Valid.t) : Result.status_t =
if Valid.is_valid res then Result.Valid Opt.dp else Result.Invalid
let add_calls (n:int) : unit =
DP.add_dp_calls calls_counter Opt.dp n
let system : System.t =
Opt.sys
let theta (voc:E.ThreadSet.t) : (E.formula * E.ThreadSet.t) =
let theta = System.gen_theta (System.SOpenArray (E.ThreadSet.elements voc)) Opt.sys Opt.abs in
let voc = E.ThreadSet.union voc (E.voc theta) in
let init_pos = if E.ThreadSet.is_empty voc then
[E.pc_form 1 E.V.Shared false]
else
E.V.VarSet.fold (fun v xs ->
E.pc_form 1 (E.V.Local v) false :: xs
) (E.voc_to_vars voc) [] in
(Formula.conj_list (theta::init_pos), voc)
let rho (seq_or_conc:System.seq_or_conc_t)
(voc:E.ThreadSet.t)
(line:int)
(th:E.ThreadSet.elt) : E.formula list =
System.gen_rho Opt.sys (System.SOpenArray (E.ThreadSet.elements voc))
seq_or_conc prog_type line Opt.abs Opt.hide_pres th
let decide_cutoff (cutoff:Smp.cutoff_strategy_t option) : Smp.cutoff_strategy_t =
match cutoff with
| None -> Opt.default_cutoff
| Some cut -> cut
let new_proof_info (cutoff:Smp.cutoff_strategy_t option) : proof_info_t =
{
cutoff = decide_cutoff cutoff;
}
let solve_proof_obligations (to_analyze:proof_obligation_t list)
: solved_proof_obligation_t list =
let module Pos = (val posSolver) in
let module Num = (val numSolver) in
let module Pairs = (val pairsSolver) in
let module Tll = (val tllSolver) in
let module Tslk = (val tslkSolver) in
Num.compute_model(Opt.compute_model);
Pairs.compute_model(Opt.compute_model);
Tll.compute_model(Opt.compute_model);
Tslk.compute_model(Opt.compute_model);
TslSolver.compute_model(Opt.compute_model);
ThmSolver.compute_model(Opt.compute_model);
let axiom_table = Axioms.new_axiom_table axiom_tags in
print_endline "Analyzing VCs...";
let case_timer = new LeapLib.timer in
let phi_timer = new LeapLib.timer in
DP.clear_call_tbl calls_counter;
let prog_lines = (System.get_trans_num Opt.sys) in
let vc_counter = ref 0 in
let oblig_counter = ref 0 in
let show_progress = not (LeapVerbose.is_verbose_enabled()) in
Progress.init (List.length to_analyze);
let result =
List.map (fun case ->
let orig_id = Tactics.get_original_vc_id case.vc in
let cutoff = case.proof_info.cutoff in
let this_calls_counter = DP.new_call_tbl() in
if LeapVerbose.is_verbose_level_enabled(LeapVerbose._SHORT_INFO) then
Report.report_vc_header !vc_counter case.vc (List.length case.obligations);
case_timer#start;
let obligation_counter = ref 1 in
let res_list =
List.map (fun phi_obligation ->
if LeapVerbose.is_verbose_level_enabled(LeapVerbose._SHORT_INFO) then
Report.report_obligation_header !obligation_counter phi_obligation;
let fol_phi = phi_obligation in
let phi_tag = Tactics.get_vc_tag case.vc in
let vc_line = Tactics.get_line_from_info case.vc in
let ax_tags = Axioms.lookup !axioms phi_tag vc_line in
print_endline ( " FOL_PHI:\n " ^ ( E.formula_to_str fol_phi ) ) ;
let (axiom_list,res_phi) =
List.fold_left (fun (axs, psi) (ax_tag,ax_kind) ->
let (ax_psi, psi') = Axioms.apply axiom_table psi ax_tag ax_kind in
(ax_psi::axs, psi')
) ([], fol_phi) ax_tags in
let axiom_phi = Formula.conj_list axiom_list in
let fol_phi = match axiom_phi with
| Formula.True -> res_phi
| _ -> Formula.Implies (axiom_phi, res_phi) in
let opt = SolOpt.new_opt () in
SolOpt.set_lines opt prog_lines;
SolOpt.set_cutoff_strategy opt cutoff;
SolOpt.set_use_quantifiers opt Opt.use_quantifiers;
SolOpt.set_use_arrangement_generator opt Opt.arrangement_gen;
Axiom application finishes
phi_timer#start;
let status =
if Valid.is_valid (Pos.check_valid prog_lines
(fst (PE.keep_locations fol_phi))) then begin
DP.add_dp_calls this_calls_counter DP.Loc 1 ~vc_id:orig_id;
Result.Valid DP.Loc
end else begin
let (validity, calls) =
match Opt.dp with
| DP.NoDP ->
(Valid.Invalid, 0)
| DP.Loc ->
(Valid.Invalid, 0)
| DP.Num ->
let num_phi = NumInterface.formula_to_int_formula fol_phi in
let (res, calls) = Num.check_valid_with_lines_plus_info
prog_lines num_phi in
if Valid.is_unknown res then begin
let z3NumSolver : (module NumSolver.S) =
NumSolver.choose BackendSolvers.Z3.identifier in
let module Z3Num = (val z3NumSolver) in
Z3Num.compute_model(Opt.compute_model);
Z3Num.check_valid_with_lines_plus_info prog_lines num_phi
end else
(res, calls)
| DP.Pairs ->
let pairs_phi = PairsInterface.formula_to_pairs_formula fol_phi in
let (res, calls) = Pairs.check_valid_with_lines_plus_info
prog_lines pairs_phi in
if Valid.is_unknown res then begin
let z3PairsSolver : (module PairsSolver.S) =
PairsSolver.choose BackendSolvers.Z3.identifier in
let module Z3Pairs = (val z3PairsSolver) in
Z3Pairs.compute_model(Opt.compute_model);
Z3Pairs.check_valid_with_lines_plus_info prog_lines pairs_phi
end else
(res, calls)
| DP.Tll ->
let tll_phi = TLLInterface.formula_to_tll_formula fol_phi in
Tll.check_valid_plus_info opt tll_phi
| DP.Tsl ->
let tsl_phi = TSLInterface.formula_to_tsl_formula fol_phi in
let (res,tsl_calls,tslk_calls) =
TslSolver.check_valid_plus_info opt tsl_phi in
DP.combine_call_table tslk_calls this_calls_counter;
(res, tsl_calls)
| DP.Tslk k ->
if k < Tslk.TslkExp.k then
Interface.Err.msg "Decision procedure not powerful enough" $
sprintf "A formula in TSLK[%i] cannot be analyzed with a \
TSLK[%i] decision procedure. Will proceed with \
TSLK[%i]." Tslk.TslkExp.k k Tslk.TslkExp.k;
let module TSLKIntf = TSLKInterface.Make(Tslk.TslkExp) in
let tslk_phi = TSLKIntf.formula_to_tslk_formula fol_phi in
Tslk.check_valid_plus_info opt tslk_phi
| DP.Thm ->
let thm_phi = THMInterface.formula_to_thm_formula fol_phi in
let (res,thm_calls,tll_calls) =
ThmSolver.check_valid_plus_info opt thm_phi in
DP.combine_call_table tll_calls this_calls_counter;
(res, thm_calls)
in
let _ = match Opt.dp with
| DP.NoDP -> ()
| DP.Loc -> ()
| DP.Num -> Num.print_model()
| DP.Pairs -> Pairs.print_model()
| DP.Tll -> Tll.print_model()
| DP.Tsl -> TslSolver.print_model()
| DP.Tslk _ -> Tslk.print_model()
| DP.Thm -> ThmSolver.print_model() in
DP.add_dp_calls this_calls_counter Opt.dp calls ~vc_id:orig_id;
if Opt.stop_on_invalid && (not (Valid.is_valid validity)) then begin
print_endline "!!! Process stopped because an invalid VC was found !!!";
exit (-1)
end;
set_status validity
end in
phi_timer#stop;
let time = phi_timer#elapsed_time in
if LeapVerbose.is_verbose_level_enabled(LeapVerbose._SHORT_INFO) then
Report.report_obligation_tail status time;
incr obligation_counter;
let phi_result = Result.new_info status time in
(phi_obligation, phi_result)
) case.obligations in
case_timer#stop;
oblig_counter := !oblig_counter + (List.length case.obligations);
let forall_res f = List.for_all (fun (_,info) -> f info) res_list in
let exist_res f = List.exists (fun (_,info) -> f info) res_list in
let vc_validity = if forall_res Result.is_valid then
Result.Valid Opt.dp
else if exist_res Result.is_invalid then
Result.Invalid
else
Result.Unverified in
let case_result = Result.new_info vc_validity (case_timer#elapsed_time) in
let res = new_solved_proof_obligation case.vc res_list case_result in
DP.combine_call_table this_calls_counter calls_counter;
if show_progress then
Progress.current (!vc_counter);
if LeapVerbose.is_verbose_level_enabled(LeapVerbose._SHORT_INFO) then
Report.report_vc_tail !vc_counter (List.map snd res_list) this_calls_counter;
incr vc_counter;
res
) to_analyze in
Report.report_summary (!oblig_counter)
(List.map (fun r -> r.result) result) calls_counter;
result
end
|
49b9d20260e41bbe3a4c4a984f9490070e4ea5c324cb429d1f4b13fed50d4312 | avsm/mirage-duniverse | test_deadlock.ml | open Lwt.Infix
let mtu = 4000
let server_log = Logs.Src.create "test_deadlock_server" ~doc:"tcp deadlock tests: server"
module Server_log = (val Logs.src_log server_log : Logs.LOG)
let client_log = Logs.Src.create "test_deadlock_client" ~doc:"tcp deadlock tests: client"
module Client_log = (val Logs.src_log client_log : Logs.LOG)
module TCPIP =
struct
module RANDOM = Mirage_random_test
module TIME =
struct
type 'a io = 'a Lwt.t
let sleep_ns nanos = Lwt_unix.sleep (Int64.to_float nanos /. 1e9)
end
module MCLOCK = Mclock
module M =
struct
module B = Basic_backend.Make
module NETIF = Vnetif.Make(B)
module ETHIF = Ethernet.Make(NETIF)
module ARPV4 = Arp.Make(ETHIF)(TIME)
module IPV4 = Static_ipv4.Make(RANDOM)(MCLOCK)(ETHIF)(ARPV4)
module ICMPV4 = Icmpv4.Make(IPV4)
module UDPV4 = Udp.Make(IPV4)(RANDOM)
module TCPV4 = Tcp.Flow.Make(IPV4)(TIME)(MCLOCK)(RANDOM)
module TCPIP = Tcpip_stack_direct.Make(TIME)(RANDOM)(NETIF)(ETHIF)(ARPV4)(IPV4)(ICMPV4)(UDPV4)(TCPV4)
end
open M
type stack = TCPIP.t
let server_ip = Ipaddr.V4.of_string_exn "192.168.10.10"
let client_ip = Ipaddr.V4.of_string_exn "192.168.10.20"
let network = Ipaddr.V4.Prefix.of_string_exn "192.168.10.255/24"
let make ~ip ~network ?gateway netif =
MCLOCK.connect () >>= fun clock ->
ETHIF.connect ~mtu netif >>= fun ethif ->
ARPV4.connect ethif >>= fun arpv4 ->
IPV4.connect ~ip ~network ?gateway clock ethif arpv4 >>= fun ipv4 ->
ICMPV4.connect ipv4 >>= fun icmpv4 ->
UDPV4.connect ipv4 >>= fun udpv4 ->
TCPV4.connect ipv4 clock >>= fun tcpv4 ->
TCPIP.connect netif ethif arpv4 ipv4 icmpv4 udpv4 tcpv4 >>= fun tcpip ->
Lwt.return tcpip
include TCPIP
let tcpip t = t
let make role netif = match role with
| `Server -> make ~ip:server_ip ~network netif
| `Client -> make ~ip:client_ip ~network netif
type conn = M.NETIF.t
let get_stats _t =
{ Mirage_net.rx_pkts = 0l; rx_bytes = 0L;
tx_pkts = 0l; tx_bytes = 0L;
}
let reset_stats _t = ()
end
let port = 10000
let test_digest netif1 netif2 =
TCPIP.make `Client netif1 >>= fun client_stack ->
TCPIP.make `Server netif2 >>= fun server_stack ->
let send_data () =
let data = Mirage_random_test.generate 100_000_000 |> Cstruct.to_string in
let t0 = Unix.gettimeofday () in
TCPIP.TCPV4.create_connection
TCPIP.(tcpv4 @@ tcpip server_stack) (TCPIP.client_ip, port) >>= function
| Error _ -> failwith "could not establish tunneled connection"
| Ok flow ->
Server_log.debug (fun f -> f "established conn");
let rec read_digest chunks =
TCPIP.TCPV4.read flow >>= function
| Error _ -> failwith "read error"
| Ok (`Data data) -> read_digest (data :: chunks)
| Ok `Eof ->
Server_log.debug (fun f -> f "EOF");
let dt = Unix.gettimeofday () -. t0 in
Server_log.warn (fun f -> f "!!!!!!!!!! XXXX needed %.2fs (%.1f MB/s)"
dt (float (String.length data) /. dt /. 1024. ** 2.));
Lwt.return_unit
in
Lwt.pick
[ read_digest [];
begin
let rec send_data data =
if Cstruct.len data < mtu then
(TCPIP.TCPV4.write flow data >>= fun _ -> Lwt.return_unit)
else
let sub, data = Cstruct.split data mtu in
Lwt.pick
[
(TCPIP.TCPV4.write flow sub >>= fun _ -> Lwt.return_unit);
(Lwt_unix.sleep 5. >>= fun () ->
Common.failf "=========== DEADLOCK!!! =============");
]
>>= fun () ->
send_data data in
send_data @@ Cstruct.of_string data >>= fun () ->
Server_log.debug (fun f -> f "wrote data");
TCPIP.TCPV4.close flow
end
]
in
TCPIP.listen_tcpv4 (TCPIP.tcpip client_stack) ~port
(fun flow ->
Client_log.debug (fun f -> f "client got conn");
let rec consume () =
TCPIP.TCPV4.read flow >>= function
| Error _ ->
Client_log.debug (fun f -> f "XXXX client read error");
TCPIP.TCPV4.close flow
| Ok `Eof ->
TCPIP.TCPV4.write flow @@ Cstruct.of_string "thanks for all the fish"
>>= fun _ ->
TCPIP.TCPV4.close flow
| Ok (`Data _data) ->
(if Random.float 1.0 < 0.01 then Lwt_unix.sleep 0.01
else Lwt.return_unit) >>= fun () ->
consume ()
in
consume ());
Lwt.pick
[
send_data ();
TCPIP.listen @@ TCPIP.tcpip server_stack;
TCPIP.listen @@ TCPIP.tcpip client_stack;
]
let run_vnetif () =
let backend = Basic_backend.Make.create
~use_async_readers:true ~yield:Lwt_unix.yield () in
TCPIP.M.NETIF.connect backend >>= fun c1 ->
TCPIP.M.NETIF.connect backend >>= fun c2 ->
test_digest c1 c2
let suite = [
"test tcp deadlock with slow receiver", `Quick, run_vnetif
]
| null | https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/tcpip/test/test_deadlock.ml | ocaml | open Lwt.Infix
let mtu = 4000
let server_log = Logs.Src.create "test_deadlock_server" ~doc:"tcp deadlock tests: server"
module Server_log = (val Logs.src_log server_log : Logs.LOG)
let client_log = Logs.Src.create "test_deadlock_client" ~doc:"tcp deadlock tests: client"
module Client_log = (val Logs.src_log client_log : Logs.LOG)
module TCPIP =
struct
module RANDOM = Mirage_random_test
module TIME =
struct
type 'a io = 'a Lwt.t
let sleep_ns nanos = Lwt_unix.sleep (Int64.to_float nanos /. 1e9)
end
module MCLOCK = Mclock
module M =
struct
module B = Basic_backend.Make
module NETIF = Vnetif.Make(B)
module ETHIF = Ethernet.Make(NETIF)
module ARPV4 = Arp.Make(ETHIF)(TIME)
module IPV4 = Static_ipv4.Make(RANDOM)(MCLOCK)(ETHIF)(ARPV4)
module ICMPV4 = Icmpv4.Make(IPV4)
module UDPV4 = Udp.Make(IPV4)(RANDOM)
module TCPV4 = Tcp.Flow.Make(IPV4)(TIME)(MCLOCK)(RANDOM)
module TCPIP = Tcpip_stack_direct.Make(TIME)(RANDOM)(NETIF)(ETHIF)(ARPV4)(IPV4)(ICMPV4)(UDPV4)(TCPV4)
end
open M
type stack = TCPIP.t
let server_ip = Ipaddr.V4.of_string_exn "192.168.10.10"
let client_ip = Ipaddr.V4.of_string_exn "192.168.10.20"
let network = Ipaddr.V4.Prefix.of_string_exn "192.168.10.255/24"
let make ~ip ~network ?gateway netif =
MCLOCK.connect () >>= fun clock ->
ETHIF.connect ~mtu netif >>= fun ethif ->
ARPV4.connect ethif >>= fun arpv4 ->
IPV4.connect ~ip ~network ?gateway clock ethif arpv4 >>= fun ipv4 ->
ICMPV4.connect ipv4 >>= fun icmpv4 ->
UDPV4.connect ipv4 >>= fun udpv4 ->
TCPV4.connect ipv4 clock >>= fun tcpv4 ->
TCPIP.connect netif ethif arpv4 ipv4 icmpv4 udpv4 tcpv4 >>= fun tcpip ->
Lwt.return tcpip
include TCPIP
let tcpip t = t
let make role netif = match role with
| `Server -> make ~ip:server_ip ~network netif
| `Client -> make ~ip:client_ip ~network netif
type conn = M.NETIF.t
let get_stats _t =
{ Mirage_net.rx_pkts = 0l; rx_bytes = 0L;
tx_pkts = 0l; tx_bytes = 0L;
}
let reset_stats _t = ()
end
let port = 10000
let test_digest netif1 netif2 =
TCPIP.make `Client netif1 >>= fun client_stack ->
TCPIP.make `Server netif2 >>= fun server_stack ->
let send_data () =
let data = Mirage_random_test.generate 100_000_000 |> Cstruct.to_string in
let t0 = Unix.gettimeofday () in
TCPIP.TCPV4.create_connection
TCPIP.(tcpv4 @@ tcpip server_stack) (TCPIP.client_ip, port) >>= function
| Error _ -> failwith "could not establish tunneled connection"
| Ok flow ->
Server_log.debug (fun f -> f "established conn");
let rec read_digest chunks =
TCPIP.TCPV4.read flow >>= function
| Error _ -> failwith "read error"
| Ok (`Data data) -> read_digest (data :: chunks)
| Ok `Eof ->
Server_log.debug (fun f -> f "EOF");
let dt = Unix.gettimeofday () -. t0 in
Server_log.warn (fun f -> f "!!!!!!!!!! XXXX needed %.2fs (%.1f MB/s)"
dt (float (String.length data) /. dt /. 1024. ** 2.));
Lwt.return_unit
in
Lwt.pick
[ read_digest [];
begin
let rec send_data data =
if Cstruct.len data < mtu then
(TCPIP.TCPV4.write flow data >>= fun _ -> Lwt.return_unit)
else
let sub, data = Cstruct.split data mtu in
Lwt.pick
[
(TCPIP.TCPV4.write flow sub >>= fun _ -> Lwt.return_unit);
(Lwt_unix.sleep 5. >>= fun () ->
Common.failf "=========== DEADLOCK!!! =============");
]
>>= fun () ->
send_data data in
send_data @@ Cstruct.of_string data >>= fun () ->
Server_log.debug (fun f -> f "wrote data");
TCPIP.TCPV4.close flow
end
]
in
TCPIP.listen_tcpv4 (TCPIP.tcpip client_stack) ~port
(fun flow ->
Client_log.debug (fun f -> f "client got conn");
let rec consume () =
TCPIP.TCPV4.read flow >>= function
| Error _ ->
Client_log.debug (fun f -> f "XXXX client read error");
TCPIP.TCPV4.close flow
| Ok `Eof ->
TCPIP.TCPV4.write flow @@ Cstruct.of_string "thanks for all the fish"
>>= fun _ ->
TCPIP.TCPV4.close flow
| Ok (`Data _data) ->
(if Random.float 1.0 < 0.01 then Lwt_unix.sleep 0.01
else Lwt.return_unit) >>= fun () ->
consume ()
in
consume ());
Lwt.pick
[
send_data ();
TCPIP.listen @@ TCPIP.tcpip server_stack;
TCPIP.listen @@ TCPIP.tcpip client_stack;
]
let run_vnetif () =
let backend = Basic_backend.Make.create
~use_async_readers:true ~yield:Lwt_unix.yield () in
TCPIP.M.NETIF.connect backend >>= fun c1 ->
TCPIP.M.NETIF.connect backend >>= fun c2 ->
test_digest c1 c2
let suite = [
"test tcp deadlock with slow receiver", `Quick, run_vnetif
]
|
|
e2cdc98c01d25d2749dcddd8585927984d87dfd32af569c76722d27299b69b6d | rm-hull/jasentaa | combinators_test.cljc | (ns jasentaa.parser.combinators-test
(:require
#?(:clj [clojure.test :refer :all]
:cljs [cljs.test :refer-macros [deftest is testing]])
[jasentaa.monad :as m]
[jasentaa.test-helpers :as th]
[jasentaa.parser.basic :as pb]
[jasentaa.parser.combinators :as pc]))
(deftest check-and-then
(let [parser (pc/and-then (pb/match "a") (pb/match "b"))]
(is (= [[[\a \b] "el"]] (th/test-harness parser "abel")))
(is (= (m/failure) (th/test-harness parser "apple")))
(is (= (m/failure) (th/test-harness parser "")))))
(deftest check-or-else
(let [parser (pc/or-else (pb/match "a") (pb/match "b"))]
(is (= [[\a "pple"]] (th/test-harness parser "apple")))
(is (= [[\b "anana"]] (th/test-harness parser "banana")))
(is (= (m/failure) (th/test-harness parser "orange")))))
(deftest check-many
(let [parser (pc/many (pb/match "a"))]
(is (= [[\a] ""] (first (th/test-harness parser "a"))))
(is (= [[\a \a \a] "bbb"] (first (th/test-harness parser "aaabbb"))))
(is (= [[] nil] (first (th/test-harness parser ""))))
(is (= [[\a] "pple"] (first (th/test-harness parser "apple"))))
(is (= [[] "orange"] (first (th/test-harness parser "orange"))))))
| null | https://raw.githubusercontent.com/rm-hull/jasentaa/aeb0738d05db6ad536ee67253c6716c7a0b1c586/test/jasentaa/parser/combinators_test.cljc | clojure | (ns jasentaa.parser.combinators-test
(:require
#?(:clj [clojure.test :refer :all]
:cljs [cljs.test :refer-macros [deftest is testing]])
[jasentaa.monad :as m]
[jasentaa.test-helpers :as th]
[jasentaa.parser.basic :as pb]
[jasentaa.parser.combinators :as pc]))
(deftest check-and-then
(let [parser (pc/and-then (pb/match "a") (pb/match "b"))]
(is (= [[[\a \b] "el"]] (th/test-harness parser "abel")))
(is (= (m/failure) (th/test-harness parser "apple")))
(is (= (m/failure) (th/test-harness parser "")))))
(deftest check-or-else
(let [parser (pc/or-else (pb/match "a") (pb/match "b"))]
(is (= [[\a "pple"]] (th/test-harness parser "apple")))
(is (= [[\b "anana"]] (th/test-harness parser "banana")))
(is (= (m/failure) (th/test-harness parser "orange")))))
(deftest check-many
(let [parser (pc/many (pb/match "a"))]
(is (= [[\a] ""] (first (th/test-harness parser "a"))))
(is (= [[\a \a \a] "bbb"] (first (th/test-harness parser "aaabbb"))))
(is (= [[] nil] (first (th/test-harness parser ""))))
(is (= [[\a] "pple"] (first (th/test-harness parser "apple"))))
(is (= [[] "orange"] (first (th/test-harness parser "orange"))))))
|
|
f1b8b0bb8288f7f718a0f293a047346355b6edca930cae2295ad2188fad7a623 | robrix/starlight | Length.hs | {-# LANGUAGE DeriveTraversable #-}
# LANGUAGE DerivingVia #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module Unit.Length
( Length
, Metres(..)
, fromAUs
, module Unit
, module Unit.Algebra
, module Unit.Multiple
) where
import Data.Functor.I
import Data.Functor.K
import Foreign.Storable
import GHC.TypeLits
import GL.Type as GL
import GL.Uniform
import Linear.Conjugate
import Linear.Epsilon
import Linear.Metric
import Linear.Vector
import System.Random (Random)
import Unit
import Unit.Algebra
import Unit.Multiple
data Length a
instance Dimension Length
instance (Unit Length u, KnownNat n) => Pow Length (Length :^: n) u n (u :^: n)
newtype Metres a = Metres { getMetres :: a }
deriving (Column, Conjugate, Epsilon, Enum, Eq, Foldable, Floating, Fractional, Functor, Integral, Num, Ord, Random, Real, RealFloat, RealFrac, Row, Show, Storable, Traversable, GL.Type, Uniform)
deriving (Additive, Applicative, Metric, Monad) via I
instance Unit Length Metres where
suffix = K ('m':)
fromAUs :: Num a => a -> Metres a
fromAUs a = Metres (149597870700 * a)
| null | https://raw.githubusercontent.com/robrix/starlight/ad80ab74dc2eedbb52a75ac8ce507661d32f488e/src/Unit/Length.hs | haskell | # LANGUAGE DeriveTraversable # | # LANGUAGE DerivingVia #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module Unit.Length
( Length
, Metres(..)
, fromAUs
, module Unit
, module Unit.Algebra
, module Unit.Multiple
) where
import Data.Functor.I
import Data.Functor.K
import Foreign.Storable
import GHC.TypeLits
import GL.Type as GL
import GL.Uniform
import Linear.Conjugate
import Linear.Epsilon
import Linear.Metric
import Linear.Vector
import System.Random (Random)
import Unit
import Unit.Algebra
import Unit.Multiple
data Length a
instance Dimension Length
instance (Unit Length u, KnownNat n) => Pow Length (Length :^: n) u n (u :^: n)
newtype Metres a = Metres { getMetres :: a }
deriving (Column, Conjugate, Epsilon, Enum, Eq, Foldable, Floating, Fractional, Functor, Integral, Num, Ord, Random, Real, RealFloat, RealFrac, Row, Show, Storable, Traversable, GL.Type, Uniform)
deriving (Additive, Applicative, Metric, Monad) via I
instance Unit Length Metres where
suffix = K ('m':)
fromAUs :: Num a => a -> Metres a
fromAUs a = Metres (149597870700 * a)
|
7dea0d4c35788c7be2eef21f7392fb9a0787fb3f30eabf9b7740a4f693079de9 | aeternity/aeternity | aemon_sup.erl | -module(aemon_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% supervisor callbacks
-export([init/1]).
-define(SERVER, ?MODULE).
-define(CHILD(Mod,N,Type), {Mod,{Mod,start_link,[]},permanent,N,Type,[Mod]}).
%% ==================================================================
%% API
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
%% ==================================================================
%% supervisor callbacks
init(_) ->
ChildSpecs = child_specs(aemon_config:is_active()),
{ok, {{one_for_one, 5, 10}, ChildSpecs}}.
%% ==================================================================
%% internal functions
child_specs(false) ->
[];
child_specs(true) ->
[ ?CHILD(aemon_mon_ttl, 5000, worker)
, ?CHILD(aemon_mon_on_chain, 5000, worker)
, ?CHILD(aemon_mon_gen_stats, 5000, worker)
, ?CHILD(aemon_mon, 5000, worker)
, ?CHILD(aemon_publisher, 5000, worker)
].
| null | https://raw.githubusercontent.com/aeternity/aeternity/b7ce6ae15dab7fa22287c2da3d4405c29bb4edd7/apps/aemon/src/aemon_sup.erl | erlang | API
supervisor callbacks
==================================================================
API
==================================================================
supervisor callbacks
==================================================================
internal functions | -module(aemon_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-define(SERVER, ?MODULE).
-define(CHILD(Mod,N,Type), {Mod,{Mod,start_link,[]},permanent,N,Type,[Mod]}).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init(_) ->
ChildSpecs = child_specs(aemon_config:is_active()),
{ok, {{one_for_one, 5, 10}, ChildSpecs}}.
child_specs(false) ->
[];
child_specs(true) ->
[ ?CHILD(aemon_mon_ttl, 5000, worker)
, ?CHILD(aemon_mon_on_chain, 5000, worker)
, ?CHILD(aemon_mon_gen_stats, 5000, worker)
, ?CHILD(aemon_mon, 5000, worker)
, ?CHILD(aemon_publisher, 5000, worker)
].
|
6d751cc9555d35a850f9e7b55eec9ac3d69f3e49b2a12128e0cf0bb36a8e0d91 | haskell-suite/haskell-tc | Naming5.hs | module Naming5 where
outer b = b
where
inner :: a -> a
inner a = const b a
const _ b = b
| null | https://raw.githubusercontent.com/haskell-suite/haskell-tc/abf5e3cc624e0095cae14c3c1c695b76ea8ffcb9/tests/Naming5.hs | haskell | module Naming5 where
outer b = b
where
inner :: a -> a
inner a = const b a
const _ b = b
|
|
a7ca6306b3b236ae9f0a4a3a2e112ef9c69af63d8190b7cbc61bcbca09dc4bab | Frozenlock/bacure | remote_device.clj | (ns bacure.test.remote-device
(:use clojure.test)
(:require [bacure.local-device :as ld]
[bacure.read-properties :as rp]
[bacure.remote-device :as rd]
[bacure.test.foreign-device :as fd]
[bacure.services :as services]
[bacure.network :as net]))
(defn init-local-test-devices!
"Boot up local devices and return their IDs.
The devices are registered as foreign devices to each other."
[qty]
(let [id->ip (into {} (map (juxt :id :ip-address) (fd/generate-local-devices! qty)))]
;; Make devices aware of each other
(doseq [[ld-id _] id->ip] ; current local device
(doseq [[_ rd-ip] (dissoc id->ip ld-id)] ; all the other devices
(ld/register-as-foreign-device ld-id rd-ip 47808 60)))
(doseq [id (keys id->ip)]
(ld/i-am-broadcast! id))
(Thread/sleep 50)
(keys id->ip)))
(deftest basic-read-properties
(ld/with-temp-devices
(let [[ld-id rd-id] (init-local-test-devices! 2)]
(testing "Partition array"
(with-redefs [services/send-request-promise (constantly {:success 10})]
(let [expected-result (into [] (for [i (range 1 11)]
[[:device rd-id] [:object-list i]]))]
(is (= expected-result
(rp/expand-array ld-id rd-id [:device rd-id] :object-list)))))))))
(deftest extended-information
(ld/with-temp-devices
(let [[ld-id rd-id] (init-local-test-devices! 2)]
;; initially we shouldn't have this data
(is (= nil (rd/cached-extended-information ld-id rd-id)))
;; now try to retrieve it
(let [data (rd/extended-information ld-id rd-id)]
(is (:protocol-services-supported data))
(is (:object-name data))))))
(deftest read-properties
(ld/with-temp-devices
;; first we create the local devices
(let [[ld-id rd-id] (init-local-test-devices! 2)]
(is (some #{rd-id} (rd/remote-devices ld-id))
(str "This test requires a device with ID "rd-id " on the network."))
(testing "Read properties"
;; Get the extended information (mostly to know if we can use
;; readPropertyMultiple)."
(is (= (get-in (rd/extended-information ld-id rd-id)
[:protocol-services-supported :read-property])
true))
;; we try a few reads
(let [obj-prop-references [[[:device rd-id] :object-name]
[[:device rd-id] :protocol-version]
[[:device rd-id] :protocol-revision]
[[:device rd-id] [:object-list 1]]]] ; <--- with array index
(testing "Read individually"
;; Reading individually means that each
;; object-property-reference is requested separately, then
;; merged into objects maps.
(let [indiv-read (rp/read-individually ld-id rd-id obj-prop-references)
{:keys [object-name protocol-version protocol-revision] :as result} (first indiv-read)]
(is (and object-name protocol-version protocol-revision))
(is (= [:device rd-id] (some-> result (get :object-list))))
(testing "Read Property Multiple"
(let [multi-read (rp/read-property-multiple ld-id rd-id obj-prop-references)
{:keys [object-name protocol-version protocol-revision object-list] :as results}
(first multi-read)]
;; result of reading individually or in bulk should be the same
(is (= indiv-read multi-read))))))))
(testing "Set property"
;; set a remote property
(let [test-string "This is a test"]
(rd/set-remote-property! ld-id rd-id [:device rd-id] :description test-string)
(is (= (:description (first (rp/read-properties ld-id rd-id [[[:device rd-id] :description]])))
test-string))))
(testing "Create/delete object"
;; first we delete an objects that doesn't exist. We should get an error
;; ;; then we delete once again: we should get an error.
(is (= (rd/delete-remote-object! ld-id rd-id [:analog-input 1])
{:error {:error-class :object :error-code :unknown-object}}))
;; ;; create the new object
( is (: success ( rd / create - remote - object ! ld - id rd - id { : object - identifier [: analog - input 1 ]
;; :object-name "Test analog"
;; :description "This is a test"})))
;; ;; set the remote property
( rd / set - remote - property ! ld - id rd - id [: analog - input 1 ] : present - value 10 )
;; ;; read the remote property; should have the value we just set.
( is (= ( - > ( rp / read - properties ld - id rd - id [ [ [: analog - input 1 ] : present - value ] ] )
first
;; (get :present-value))
;; 10.0))
( rd / delete - remote - object ! ld - id rd - id [: analog - input 1 ] )
( is (= ( - > ( rp / read - properties ld - id rd - id [ [ [: analog - input 1 ] : present - value ] ] )
( first )
;; :present-value)
;; {:error {:error-class :object :error-code :unknown-object}}))
)
(testing "Splitting max read multiple references"
;; create a bunch of objects
(doseq [i (range 10)]
(ld/add-object! rd-id {:object-identifier [:analog-input i]
:object-name (str "Analog "i)
:description "This is a test"}))
(let [mrmr (.getMaxReadMultipleReferences (rd/rd ld-id rd-id))]
(.setMaxReadMultipleReferences (rd/rd ld-id rd-id) 2) ;; <--
maximum 2 references this will force us to read the
;; properties by sending multiple requests. They should all
;; be merged once they come back.
(let [results (rp/read-properties ld-id rd-id [[[:analog-input 0] :object-name]
[[:analog-input 1] :object-name]
[[:analog-input 3] :object-name]
[[:analog-input 4] :object-name]
[[:analog-input 15] :object-name]] ;; <-- will return an error
)]
(is (= 5 (count results)))
(is (:error-code (:object-name (last results)))))
(.setMaxReadMultipleReferences (rd/rd ld-id rd-id) mrmr))
;; ;; delete all objects
( doseq [ i ( range 10 ) ]
;; (rd/delete-remote-object! ld-id rd-id [:analog-input i])))
))))
| null | https://raw.githubusercontent.com/Frozenlock/bacure/2d743492f7865d8c61313f4d73818c3d1ee462de/test/bacure/test/remote_device.clj | clojure | Make devices aware of each other
current local device
all the other devices
initially we shouldn't have this data
now try to retrieve it
first we create the local devices
Get the extended information (mostly to know if we can use
readPropertyMultiple)."
we try a few reads
<--- with array index
Reading individually means that each
object-property-reference is requested separately, then
merged into objects maps.
result of reading individually or in bulk should be the same
set a remote property
first we delete an objects that doesn't exist. We should get an error
;; then we delete once again: we should get an error.
;; create the new object
:object-name "Test analog"
:description "This is a test"})))
;; set the remote property
;; read the remote property; should have the value we just set.
(get :present-value))
10.0))
:present-value)
{:error {:error-class :object :error-code :unknown-object}}))
create a bunch of objects
<--
properties by sending multiple requests. They should all
be merged once they come back.
<-- will return an error
;; delete all objects
(rd/delete-remote-object! ld-id rd-id [:analog-input i]))) | (ns bacure.test.remote-device
(:use clojure.test)
(:require [bacure.local-device :as ld]
[bacure.read-properties :as rp]
[bacure.remote-device :as rd]
[bacure.test.foreign-device :as fd]
[bacure.services :as services]
[bacure.network :as net]))
(defn init-local-test-devices!
"Boot up local devices and return their IDs.
The devices are registered as foreign devices to each other."
[qty]
(let [id->ip (into {} (map (juxt :id :ip-address) (fd/generate-local-devices! qty)))]
(ld/register-as-foreign-device ld-id rd-ip 47808 60)))
(doseq [id (keys id->ip)]
(ld/i-am-broadcast! id))
(Thread/sleep 50)
(keys id->ip)))
(deftest basic-read-properties
(ld/with-temp-devices
(let [[ld-id rd-id] (init-local-test-devices! 2)]
(testing "Partition array"
(with-redefs [services/send-request-promise (constantly {:success 10})]
(let [expected-result (into [] (for [i (range 1 11)]
[[:device rd-id] [:object-list i]]))]
(is (= expected-result
(rp/expand-array ld-id rd-id [:device rd-id] :object-list)))))))))
(deftest extended-information
(ld/with-temp-devices
(let [[ld-id rd-id] (init-local-test-devices! 2)]
(is (= nil (rd/cached-extended-information ld-id rd-id)))
(let [data (rd/extended-information ld-id rd-id)]
(is (:protocol-services-supported data))
(is (:object-name data))))))
(deftest read-properties
(ld/with-temp-devices
(let [[ld-id rd-id] (init-local-test-devices! 2)]
(is (some #{rd-id} (rd/remote-devices ld-id))
(str "This test requires a device with ID "rd-id " on the network."))
(testing "Read properties"
(is (= (get-in (rd/extended-information ld-id rd-id)
[:protocol-services-supported :read-property])
true))
(let [obj-prop-references [[[:device rd-id] :object-name]
[[:device rd-id] :protocol-version]
[[:device rd-id] :protocol-revision]
(testing "Read individually"
(let [indiv-read (rp/read-individually ld-id rd-id obj-prop-references)
{:keys [object-name protocol-version protocol-revision] :as result} (first indiv-read)]
(is (and object-name protocol-version protocol-revision))
(is (= [:device rd-id] (some-> result (get :object-list))))
(testing "Read Property Multiple"
(let [multi-read (rp/read-property-multiple ld-id rd-id obj-prop-references)
{:keys [object-name protocol-version protocol-revision object-list] :as results}
(first multi-read)]
(is (= indiv-read multi-read))))))))
(testing "Set property"
(let [test-string "This is a test"]
(rd/set-remote-property! ld-id rd-id [:device rd-id] :description test-string)
(is (= (:description (first (rp/read-properties ld-id rd-id [[[:device rd-id] :description]])))
test-string))))
(testing "Create/delete object"
(is (= (rd/delete-remote-object! ld-id rd-id [:analog-input 1])
{:error {:error-class :object :error-code :unknown-object}}))
( is (: success ( rd / create - remote - object ! ld - id rd - id { : object - identifier [: analog - input 1 ]
( rd / set - remote - property ! ld - id rd - id [: analog - input 1 ] : present - value 10 )
( is (= ( - > ( rp / read - properties ld - id rd - id [ [ [: analog - input 1 ] : present - value ] ] )
first
( rd / delete - remote - object ! ld - id rd - id [: analog - input 1 ] )
( is (= ( - > ( rp / read - properties ld - id rd - id [ [ [: analog - input 1 ] : present - value ] ] )
( first )
)
(testing "Splitting max read multiple references"
(doseq [i (range 10)]
(ld/add-object! rd-id {:object-identifier [:analog-input i]
:object-name (str "Analog "i)
:description "This is a test"}))
(let [mrmr (.getMaxReadMultipleReferences (rd/rd ld-id rd-id))]
maximum 2 references this will force us to read the
(let [results (rp/read-properties ld-id rd-id [[[:analog-input 0] :object-name]
[[:analog-input 1] :object-name]
[[:analog-input 3] :object-name]
[[:analog-input 4] :object-name]
)]
(is (= 5 (count results)))
(is (:error-code (:object-name (last results)))))
(.setMaxReadMultipleReferences (rd/rd ld-id rd-id) mrmr))
( doseq [ i ( range 10 ) ]
))))
|
907f949b74f4c705f3690ab3d69e762c9f3b150a450d47fcbd9d980bd276f1ee | caiorss/Functional-Programming | toupper-imp.hs |
-- file: ch07/toupper-imp.hs
import System.IO
import Data.Char(toUpper)
main :: IO ()
main = do
inh <- openFile "/etc/issue" ReadMode
outh <- openFile "/tmp/issue.out" WriteMode
mainloop inh outh
hClose inh
hClose outh
mainloop :: Handle -> Handle -> IO ()
mainloop inh outh =
do ineof <- hIsEOF inh
if ineof
then return ()
else do inpStr <- hGetLine inh
hPutStrLn outh (map toUpper inpStr)
mainloop inh outh
| null | https://raw.githubusercontent.com/caiorss/Functional-Programming/ef3526898e3014e9c99bf495033ff36a4530503d/haskell/rwh/ch07/toupper-imp.hs | haskell | file: ch07/toupper-imp.hs |
import System.IO
import Data.Char(toUpper)
main :: IO ()
main = do
inh <- openFile "/etc/issue" ReadMode
outh <- openFile "/tmp/issue.out" WriteMode
mainloop inh outh
hClose inh
hClose outh
mainloop :: Handle -> Handle -> IO ()
mainloop inh outh =
do ineof <- hIsEOF inh
if ineof
then return ()
else do inpStr <- hGetLine inh
hPutStrLn outh (map toUpper inpStr)
mainloop inh outh
|
59ce52c45d65a87b256786610dfcd6788332ed6913d8f9297fb8fb9c89e446b0 | zenspider/schemers | exercise.4.41.scm | #!/usr/bin/env csi -s
(require rackunit)
Exercise 4.41
;; Write an ordinary Scheme program to solve the multiple dwelling
;; puzzle.
;; no | null | https://raw.githubusercontent.com/zenspider/schemers/2939ca553ac79013a4c3aaaec812c1bad3933b16/sicp/ch_4/exercise.4.41.scm | scheme | Write an ordinary Scheme program to solve the multiple dwelling
puzzle.
no | #!/usr/bin/env csi -s
(require rackunit)
Exercise 4.41
|
0b20c376f219b3929b643a5d295fe6026fbd883ed19af9d5e828b40f4d49229d | goblint/analyzer | violation.ml | module type ViolationArg =
sig
include MyARG.S with module Edge = MyARG.InlineEdge
val prev: Node.t -> (Edge.t * Node.t) list
val violations: Node.t list
end
let find_sinks (type node) (module Arg:ViolationArg with type Node.t = node) =
let module NHT = BatHashtbl.Make (Arg.Node) in
let non_sinks = NHT.create 100 in
(* DFS *)
let rec iter_node node =
if not (NHT.mem non_sinks node) then begin
NHT.replace non_sinks node ();
List.iter (fun (_, prev_node) ->
iter_node prev_node
) (Arg.prev node)
end
in
List.iter iter_node Arg.violations;
fun n ->
not (NHT.mem non_sinks n)
module type Feasibility =
sig
module Node: MyARG.Node
(* TODO: avoid copying this to every Feasibility? *)
type result =
| Feasible
| Infeasible of (Node.t * MyARG.inline_edge * Node.t) list
| Unknown
val check_path: (Node.t * MyARG.inline_edge * Node.t) list -> result
end
module UnknownFeasibility (Node: MyARG.Node): Feasibility with module Node = Node =
struct
module Node = Node
type result =
| Feasible
| Infeasible of (Node.t * MyARG.inline_edge * Node.t) list
| Unknown
let check_path _ = Unknown
end
exception Found
module type PathArg = MyARG.S with module Edge = MyARG.InlineEdge
type 'node result =
| Feasible of (module PathArg with type Node.t = 'node)
| Infeasible of ('node * MyARG.inline_edge * 'node) list
| Unknown
let find_path (type node) (module Arg:ViolationArg with type Node.t = node) (module Feasibility:Feasibility with type Node.t = node): node result =
let module NHT = BatHashtbl.Make (Arg.Node) in
let rec trace_path next_nodes node2 =
if NHT.mem next_nodes node2 then begin
(* ignore (Pretty.printf "PATH: %s\n" (Arg.Node.to_string node2)); *)
let (edge, next_node) = NHT.find next_nodes node2 in
ignore ( Pretty.printf " % a\n " MyCFG.pretty_edge edge ) ;
(node2, edge, next_node) :: trace_path next_nodes next_node
end
else
[]
in
let print_path path =
List.iter (fun (n1, e, n2) ->
ignore (GoblintCil.Pretty.printf " %s =[%s]=> %s\n" (Arg.Node.to_string n1) (Arg.Edge.to_string e) (Arg.Node.to_string n2))
) path
in
let find_path nodes =
let next_nodes = NHT.create 100 in
let itered_nodes = NHT.create 100 in
let rec bfs curs nexts = match curs with
| node :: curs' ->
if Arg.Node.equal node Arg.main_entry then
raise Found
else if not (NHT.mem itered_nodes node) then begin
NHT.replace itered_nodes node ();
List.iter (fun (edge, prev_node) ->
match edge with
| MyARG.CFGEdge _
| InlineEntry _
| InlineReturn _ ->
if not (NHT.mem itered_nodes prev_node) then
NHT.replace next_nodes prev_node (edge, node)
| InlinedEdge _
| ThreadEntry _ -> ()
) (Arg.prev node);
bfs curs' (List.map snd (Arg.prev node) @ nexts)
end
else
bfs curs' nexts
| [] ->
match nexts with
| [] -> ()
| _ -> bfs nexts []
in
try bfs nodes []; None with
| Found ->
Some (trace_path next_nodes Arg.main_entry)
in
begin match find_path Arg.violations with
| Some path ->
print_path path;
begin match Feasibility.check_path path with
| Feasibility.Feasible ->
print_endline "feasible";
let module PathArg =
struct
module Node = Arg.Node
module Edge = Arg.Edge
let main_entry = BatTuple.Tuple3.first (List.hd path)
let next =
let module NHT = BatHashtbl.Make (Node) in
let next = NHT.create (List.length path) in
List.iter (fun (n1, e, n2) ->
NHT.modify_def [] n1 (fun nexts -> (e, n2) :: nexts) next
) path;
(fun n -> NHT.find_default next n [])
end
in
Feasible (module PathArg)
| Feasibility.Infeasible subpath ->
print_endline "infeasible";
print_path subpath;
Infeasible subpath
| Feasibility.Unknown ->
print_endline "unknown";
Unknown
end
| None ->
Unknown
end
| null | https://raw.githubusercontent.com/goblint/analyzer/35d5ac7c41f178776424330ddba5472976754239/src/witness/violation.ml | ocaml | DFS
TODO: avoid copying this to every Feasibility?
ignore (Pretty.printf "PATH: %s\n" (Arg.Node.to_string node2)); | module type ViolationArg =
sig
include MyARG.S with module Edge = MyARG.InlineEdge
val prev: Node.t -> (Edge.t * Node.t) list
val violations: Node.t list
end
let find_sinks (type node) (module Arg:ViolationArg with type Node.t = node) =
let module NHT = BatHashtbl.Make (Arg.Node) in
let non_sinks = NHT.create 100 in
let rec iter_node node =
if not (NHT.mem non_sinks node) then begin
NHT.replace non_sinks node ();
List.iter (fun (_, prev_node) ->
iter_node prev_node
) (Arg.prev node)
end
in
List.iter iter_node Arg.violations;
fun n ->
not (NHT.mem non_sinks n)
module type Feasibility =
sig
module Node: MyARG.Node
type result =
| Feasible
| Infeasible of (Node.t * MyARG.inline_edge * Node.t) list
| Unknown
val check_path: (Node.t * MyARG.inline_edge * Node.t) list -> result
end
module UnknownFeasibility (Node: MyARG.Node): Feasibility with module Node = Node =
struct
module Node = Node
type result =
| Feasible
| Infeasible of (Node.t * MyARG.inline_edge * Node.t) list
| Unknown
let check_path _ = Unknown
end
exception Found
module type PathArg = MyARG.S with module Edge = MyARG.InlineEdge
type 'node result =
| Feasible of (module PathArg with type Node.t = 'node)
| Infeasible of ('node * MyARG.inline_edge * 'node) list
| Unknown
let find_path (type node) (module Arg:ViolationArg with type Node.t = node) (module Feasibility:Feasibility with type Node.t = node): node result =
let module NHT = BatHashtbl.Make (Arg.Node) in
let rec trace_path next_nodes node2 =
if NHT.mem next_nodes node2 then begin
let (edge, next_node) = NHT.find next_nodes node2 in
ignore ( Pretty.printf " % a\n " MyCFG.pretty_edge edge ) ;
(node2, edge, next_node) :: trace_path next_nodes next_node
end
else
[]
in
let print_path path =
List.iter (fun (n1, e, n2) ->
ignore (GoblintCil.Pretty.printf " %s =[%s]=> %s\n" (Arg.Node.to_string n1) (Arg.Edge.to_string e) (Arg.Node.to_string n2))
) path
in
let find_path nodes =
let next_nodes = NHT.create 100 in
let itered_nodes = NHT.create 100 in
let rec bfs curs nexts = match curs with
| node :: curs' ->
if Arg.Node.equal node Arg.main_entry then
raise Found
else if not (NHT.mem itered_nodes node) then begin
NHT.replace itered_nodes node ();
List.iter (fun (edge, prev_node) ->
match edge with
| MyARG.CFGEdge _
| InlineEntry _
| InlineReturn _ ->
if not (NHT.mem itered_nodes prev_node) then
NHT.replace next_nodes prev_node (edge, node)
| InlinedEdge _
| ThreadEntry _ -> ()
) (Arg.prev node);
bfs curs' (List.map snd (Arg.prev node) @ nexts)
end
else
bfs curs' nexts
| [] ->
match nexts with
| [] -> ()
| _ -> bfs nexts []
in
try bfs nodes []; None with
| Found ->
Some (trace_path next_nodes Arg.main_entry)
in
begin match find_path Arg.violations with
| Some path ->
print_path path;
begin match Feasibility.check_path path with
| Feasibility.Feasible ->
print_endline "feasible";
let module PathArg =
struct
module Node = Arg.Node
module Edge = Arg.Edge
let main_entry = BatTuple.Tuple3.first (List.hd path)
let next =
let module NHT = BatHashtbl.Make (Node) in
let next = NHT.create (List.length path) in
List.iter (fun (n1, e, n2) ->
NHT.modify_def [] n1 (fun nexts -> (e, n2) :: nexts) next
) path;
(fun n -> NHT.find_default next n [])
end
in
Feasible (module PathArg)
| Feasibility.Infeasible subpath ->
print_endline "infeasible";
print_path subpath;
Infeasible subpath
| Feasibility.Unknown ->
print_endline "unknown";
Unknown
end
| None ->
Unknown
end
|
61178a8038fd5503d3eb759c30b9f2c5cc013adb02c17e951f39dc252ed55060 | evrim/core-server | tab.lisp | (in-package :core-server)
;; -------------------------------------------------------------------------
;; Tab Widget
;; -------------------------------------------------------------------------
(defcomponent <widget:tab (<core:tab <widget:simple)
())
| null | https://raw.githubusercontent.com/evrim/core-server/200ea8151d2f8d81b593d605b183a9cddae1e82d/src/web/widgets/tab.lisp | lisp | -------------------------------------------------------------------------
Tab Widget
------------------------------------------------------------------------- | (in-package :core-server)
(defcomponent <widget:tab (<core:tab <widget:simple)
())
|
e02c45fb847a3cce6c2883ccfbcc751e5a614aa81b3f879ac7fd18c82382138a | DanielG/ghc-mod | DynFlags.hs | # LANGUAGE TemplateHaskell #
# LANGUAGE StandaloneDeriving #
# LANGUAGE CPP #
module GhcMod.DynFlags where
import Control.Applicative
import Control.Monad
import GHC
import qualified GHC as G
import GHC.Paths (libdir)
import qualified GhcMod.Gap as Gap
import GhcMod.Types
import GhcMod.DebugLogger
import GhcMod.DynFlagsTH
import System.IO.Unsafe (unsafePerformIO)
import Prelude
-- For orphans
#if __GLASGOW_HASKELL__ == 802
import Util (OverridingBool(..))
import PprColour
#endif
setEmptyLogger :: DynFlags -> DynFlags
setEmptyLogger df =
Gap.setLogAction df $ \_ _ _ _ _ _ -> return ()
setDebugLogger :: (String -> IO ()) -> DynFlags -> DynFlags
setDebugLogger put df = do
Gap.setLogAction df (debugLogAction put)
-- * Fast
-- * Friendly to foreign export
-- * Not friendly to -XTemplateHaskell and -XPatternSynonyms
-- * Uses little memory
setHscNothing :: DynFlags -> DynFlags
setHscNothing df = df {
ghcMode = CompManager
, ghcLink = NoLink
, hscTarget = HscNothing
, optLevel = 0
}
-- * Slow
-- * Not friendly to foreign export
-- * Friendly to -XTemplateHaskell and -XPatternSynonyms
-- * Uses lots of memory
setHscInterpreted :: DynFlags -> DynFlags
setHscInterpreted df = df {
ghcMode = CompManager
, ghcLink = LinkInMemory
, hscTarget = HscInterpreted
, optLevel = 0
}
| Parse command line ghc options and add them to the ' DynFlags ' passed
addCmdOpts :: GhcMonad m => [GHCOption] -> DynFlags -> m DynFlags
addCmdOpts cmdOpts df =
fst3 <$> G.parseDynamicFlags df (map G.noLoc cmdOpts)
where
fst3 (a,_,_) = a
----------------------------------------------------------------
withDynFlags :: GhcMonad m
=> (DynFlags -> DynFlags)
-> m a
-> m a
withDynFlags setFlags body = G.gbracket setup teardown (\_ -> body)
where
setup = do
dflags <- G.getSessionDynFlags
void $ G.setSessionDynFlags (setFlags dflags)
return dflags
teardown = void . G.setSessionDynFlags
withCmdFlags :: GhcMonad m => [GHCOption] -> m a -> m a
withCmdFlags flags body = G.gbracket setup teardown (\_ -> body)
where
setup = do
dflags <- G.getSessionDynFlags
void $ G.setSessionDynFlags =<< addCmdOpts flags dflags
return dflags
teardown = void . G.setSessionDynFlags
----------------------------------------------------------------
| Set ' DynFlags ' equivalent to " -w : " .
setNoWarningFlags :: DynFlags -> DynFlags
setNoWarningFlags df = df { warningFlags = Gap.emptyWarnFlags}
| Set ' DynFlags ' equivalent to " -Wall " .
setAllWarningFlags :: DynFlags -> DynFlags
setAllWarningFlags df = df { warningFlags = allWarningFlags }
allWarningFlags :: Gap.WarnFlags
allWarningFlags = unsafePerformIO $
G.runGhc (Just libdir) $ do
df <- G.getSessionDynFlags
df' <- addCmdOpts ["-Wall"] df
return $ G.warningFlags df'
----------------------------------------------------------------
deferErrors :: Monad m => DynFlags -> m DynFlags
deferErrors df = return $
Gap.setWarnTypedHoles $ Gap.setDeferTypedHoles $
Gap.setDeferTypeErrors $ setNoWarningFlags df
----------------------------------------------------------------
#if __GLASGOW_HASKELL__ == 802
deriving instance Eq OverridingBool
deriving instance Eq PprColour.Scheme
deriving instance Eq PprColour.PprColour
#endif
deriveEqDynFlags [d|
eqDynFlags :: DynFlags -> DynFlags -> [[(Bool, String)]]
eqDynFlags = undefined
|]
| null | https://raw.githubusercontent.com/DanielG/ghc-mod/391e187a5dfef4421aab2508fa6ff7875cc8259d/core/GhcMod/DynFlags.hs | haskell | For orphans
* Fast
* Friendly to foreign export
* Not friendly to -XTemplateHaskell and -XPatternSynonyms
* Uses little memory
* Slow
* Not friendly to foreign export
* Friendly to -XTemplateHaskell and -XPatternSynonyms
* Uses lots of memory
--------------------------------------------------------------
--------------------------------------------------------------
--------------------------------------------------------------
-------------------------------------------------------------- | # LANGUAGE TemplateHaskell #
# LANGUAGE StandaloneDeriving #
# LANGUAGE CPP #
module GhcMod.DynFlags where
import Control.Applicative
import Control.Monad
import GHC
import qualified GHC as G
import GHC.Paths (libdir)
import qualified GhcMod.Gap as Gap
import GhcMod.Types
import GhcMod.DebugLogger
import GhcMod.DynFlagsTH
import System.IO.Unsafe (unsafePerformIO)
import Prelude
#if __GLASGOW_HASKELL__ == 802
import Util (OverridingBool(..))
import PprColour
#endif
setEmptyLogger :: DynFlags -> DynFlags
setEmptyLogger df =
Gap.setLogAction df $ \_ _ _ _ _ _ -> return ()
setDebugLogger :: (String -> IO ()) -> DynFlags -> DynFlags
setDebugLogger put df = do
Gap.setLogAction df (debugLogAction put)
setHscNothing :: DynFlags -> DynFlags
setHscNothing df = df {
ghcMode = CompManager
, ghcLink = NoLink
, hscTarget = HscNothing
, optLevel = 0
}
setHscInterpreted :: DynFlags -> DynFlags
setHscInterpreted df = df {
ghcMode = CompManager
, ghcLink = LinkInMemory
, hscTarget = HscInterpreted
, optLevel = 0
}
| Parse command line ghc options and add them to the ' DynFlags ' passed
addCmdOpts :: GhcMonad m => [GHCOption] -> DynFlags -> m DynFlags
addCmdOpts cmdOpts df =
fst3 <$> G.parseDynamicFlags df (map G.noLoc cmdOpts)
where
fst3 (a,_,_) = a
withDynFlags :: GhcMonad m
=> (DynFlags -> DynFlags)
-> m a
-> m a
withDynFlags setFlags body = G.gbracket setup teardown (\_ -> body)
where
setup = do
dflags <- G.getSessionDynFlags
void $ G.setSessionDynFlags (setFlags dflags)
return dflags
teardown = void . G.setSessionDynFlags
withCmdFlags :: GhcMonad m => [GHCOption] -> m a -> m a
withCmdFlags flags body = G.gbracket setup teardown (\_ -> body)
where
setup = do
dflags <- G.getSessionDynFlags
void $ G.setSessionDynFlags =<< addCmdOpts flags dflags
return dflags
teardown = void . G.setSessionDynFlags
| Set ' DynFlags ' equivalent to " -w : " .
setNoWarningFlags :: DynFlags -> DynFlags
setNoWarningFlags df = df { warningFlags = Gap.emptyWarnFlags}
| Set ' DynFlags ' equivalent to " -Wall " .
setAllWarningFlags :: DynFlags -> DynFlags
setAllWarningFlags df = df { warningFlags = allWarningFlags }
allWarningFlags :: Gap.WarnFlags
allWarningFlags = unsafePerformIO $
G.runGhc (Just libdir) $ do
df <- G.getSessionDynFlags
df' <- addCmdOpts ["-Wall"] df
return $ G.warningFlags df'
deferErrors :: Monad m => DynFlags -> m DynFlags
deferErrors df = return $
Gap.setWarnTypedHoles $ Gap.setDeferTypedHoles $
Gap.setDeferTypeErrors $ setNoWarningFlags df
#if __GLASGOW_HASKELL__ == 802
deriving instance Eq OverridingBool
deriving instance Eq PprColour.Scheme
deriving instance Eq PprColour.PprColour
#endif
deriveEqDynFlags [d|
eqDynFlags :: DynFlags -> DynFlags -> [[(Bool, String)]]
eqDynFlags = undefined
|]
|
bde39d81d7bc7ede8652b2e8a88e39998ffe138a3812ad9eb8be7f2d74ddc38f | tek/ribosome | RegisterType.hs | |Codec data type for Neovim register types .
module Ribosome.Data.RegisterType where
import Prettyprinter (Pretty (pretty))
import Ribosome.Host.Class.Msgpack.Decode (MsgpackDecode (..))
import Ribosome.Host.Class.Msgpack.Encode (MsgpackEncode (..))
import Ribosome.Host.Class.Msgpack.Util (decodeString)
|The type of a Neovim register , corresponding to concepts like line- or character - wise visual mode .
data RegisterType =
Character
|
Line
|
Block
|
BlockWidth Int
|
Unknown Text
deriving stock (Eq, Show, Ord)
instance IsString RegisterType where
fromString "v" =
Character
fromString "V" =
Line
fromString a@('c' : 'v' : _) =
Unknown (toText a)
fromString a =
Unknown (toText a)
instance MsgpackDecode RegisterType where
fromMsgpack =
decodeString
instance MsgpackEncode RegisterType where
toMsgpack Character =
toMsgpack ("v" :: Text)
toMsgpack Line =
toMsgpack ("V" :: Text)
toMsgpack Block =
toMsgpack ("b" :: Text)
toMsgpack (BlockWidth width) =
toMsgpack ("b" <> show width :: Text)
toMsgpack (Unknown _) =
toMsgpack ("" :: Text)
instance Pretty RegisterType where
pretty = \case
Character ->
"c"
Line ->
"v"
Block ->
"<c-v>"
BlockWidth width ->
"<c-v>" <> pretty width
Unknown a ->
pretty a
| null | https://raw.githubusercontent.com/tek/ribosome/4eb38f599b72450c93cac4a7b474247e478be1a8/packages/ribosome/lib/Ribosome/Data/RegisterType.hs | haskell | |Codec data type for Neovim register types .
module Ribosome.Data.RegisterType where
import Prettyprinter (Pretty (pretty))
import Ribosome.Host.Class.Msgpack.Decode (MsgpackDecode (..))
import Ribosome.Host.Class.Msgpack.Encode (MsgpackEncode (..))
import Ribosome.Host.Class.Msgpack.Util (decodeString)
|The type of a Neovim register , corresponding to concepts like line- or character - wise visual mode .
data RegisterType =
Character
|
Line
|
Block
|
BlockWidth Int
|
Unknown Text
deriving stock (Eq, Show, Ord)
instance IsString RegisterType where
fromString "v" =
Character
fromString "V" =
Line
fromString a@('c' : 'v' : _) =
Unknown (toText a)
fromString a =
Unknown (toText a)
instance MsgpackDecode RegisterType where
fromMsgpack =
decodeString
instance MsgpackEncode RegisterType where
toMsgpack Character =
toMsgpack ("v" :: Text)
toMsgpack Line =
toMsgpack ("V" :: Text)
toMsgpack Block =
toMsgpack ("b" :: Text)
toMsgpack (BlockWidth width) =
toMsgpack ("b" <> show width :: Text)
toMsgpack (Unknown _) =
toMsgpack ("" :: Text)
instance Pretty RegisterType where
pretty = \case
Character ->
"c"
Line ->
"v"
Block ->
"<c-v>"
BlockWidth width ->
"<c-v>" <> pretty width
Unknown a ->
pretty a
|
|
e410c9c7a939078c6722ce9e34dbefac346572394763a0ee0f4dcaef7f4bd026 | timbertson/opam2nix | test_vars.ml | open OUnit2
open Opam2nix
module Name = OpamPackage.Name
let print_var = function
| Some v -> OpamVariable.string_of_variable_contents v
| None -> "None"
let test_path ocaml_version prefix name ?scope expected =
name >:: (fun _ ->
let scope = scope |> Option.map Name.of_string in
assert_equal ~printer:print_var (Some (S expected)) (Vars.path_var ~ocaml_version:(Some ocaml_version) ~prefix ~scope name)
)
let suite = "Util" >:::
[
("path vars" >:::
let ocaml_version = OpamPackage.Version.of_string "1.2.3" in
let scope = "pkg" in
let prefix = "/prefix" in
let test = test_path ocaml_version (OpamFilename.Dir.of_string prefix) in
let base = "/prefix/lib/ocaml/1.2.3" in
let sitelib = base ^ "/site-lib" in
[
test "lib" sitelib;
test "lib" ~scope (sitelib ^ "/pkg");
test "stublibs" (sitelib ^ "/stublibs");
test "stublibs" ~scope (sitelib ^ "/stublibs/pkg");
test "toplevel" (sitelib ^ "/toplevel");
test "toplevel" ~scope (sitelib ^ "/toplevel/pkg");
] @ (
toplevel dirs
["bin"; "sbin"; "man"; "libexec"; "etc"; "doc"; "share"]
|> List.map (fun name -> [
test name (prefix ^ "/" ^ name);
test name ~scope (prefix ^ "/" ^ name ^ "/" ^ scope);
])
|> List.concat
) @ [
test "lib_root" sitelib;
test "lib_root" ~scope sitelib;
test "share_root" (prefix ^ "/share");
test "share_root" ~scope (prefix ^ "/share");
]
);
]
| null | https://raw.githubusercontent.com/timbertson/opam2nix/dee96eb1c706edc61e38df35240e0f707cfb800e/test_src/test_vars.ml | ocaml | open OUnit2
open Opam2nix
module Name = OpamPackage.Name
let print_var = function
| Some v -> OpamVariable.string_of_variable_contents v
| None -> "None"
let test_path ocaml_version prefix name ?scope expected =
name >:: (fun _ ->
let scope = scope |> Option.map Name.of_string in
assert_equal ~printer:print_var (Some (S expected)) (Vars.path_var ~ocaml_version:(Some ocaml_version) ~prefix ~scope name)
)
let suite = "Util" >:::
[
("path vars" >:::
let ocaml_version = OpamPackage.Version.of_string "1.2.3" in
let scope = "pkg" in
let prefix = "/prefix" in
let test = test_path ocaml_version (OpamFilename.Dir.of_string prefix) in
let base = "/prefix/lib/ocaml/1.2.3" in
let sitelib = base ^ "/site-lib" in
[
test "lib" sitelib;
test "lib" ~scope (sitelib ^ "/pkg");
test "stublibs" (sitelib ^ "/stublibs");
test "stublibs" ~scope (sitelib ^ "/stublibs/pkg");
test "toplevel" (sitelib ^ "/toplevel");
test "toplevel" ~scope (sitelib ^ "/toplevel/pkg");
] @ (
toplevel dirs
["bin"; "sbin"; "man"; "libexec"; "etc"; "doc"; "share"]
|> List.map (fun name -> [
test name (prefix ^ "/" ^ name);
test name ~scope (prefix ^ "/" ^ name ^ "/" ^ scope);
])
|> List.concat
) @ [
test "lib_root" sitelib;
test "lib_root" ~scope sitelib;
test "share_root" (prefix ^ "/share");
test "share_root" ~scope (prefix ^ "/share");
]
);
]
|
|
e177d6428316f4d047d6f0a260bec66ed206ba820307382ca5a9d131530ba2c8 | leopiney/tensor-safe | LSTM.hs | # LANGUAGE DataKinds #
{-# LANGUAGE GADTs #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
| This module declares the classing LSTM layer data type .
module TensorSafe.Layers.LSTM where
import Data.Kind (Type)
import Data.Map (fromList)
import Data.Proxy (Proxy (..))
import GHC.TypeLits (KnownNat, Nat, natVal)
import TensorSafe.Compile.Expr (CNetwork (CNLayer), DLayer (DLSTM))
import TensorSafe.Layer (Layer (..))
-- | A LSTM layer with a number of units and a option to return the original sequences.
data LSTM :: Nat -> Bool -> Type where
LSTM :: LSTM units returnSequences
deriving (Show)
instance (KnownNat units) => Layer (LSTM units b) where
layer = LSTM
compile _ _ =
let units = show $ natVal (Proxy :: Proxy units)
returnSequences = show $ (Proxy :: Proxy returnSequences)
in CNLayer
DLSTM
( fromList
[ ("units", units),
("returnSequences", returnSequences)
]
)
| null | https://raw.githubusercontent.com/leopiney/tensor-safe/cdf611dbbe68f6f6cb0b44fe31d86b28a547a3f2/src/TensorSafe/Layers/LSTM.hs | haskell | # LANGUAGE GADTs #
| A LSTM layer with a number of units and a option to return the original sequences. | # LANGUAGE DataKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
| This module declares the classing LSTM layer data type .
module TensorSafe.Layers.LSTM where
import Data.Kind (Type)
import Data.Map (fromList)
import Data.Proxy (Proxy (..))
import GHC.TypeLits (KnownNat, Nat, natVal)
import TensorSafe.Compile.Expr (CNetwork (CNLayer), DLayer (DLSTM))
import TensorSafe.Layer (Layer (..))
data LSTM :: Nat -> Bool -> Type where
LSTM :: LSTM units returnSequences
deriving (Show)
instance (KnownNat units) => Layer (LSTM units b) where
layer = LSTM
compile _ _ =
let units = show $ natVal (Proxy :: Proxy units)
returnSequences = show $ (Proxy :: Proxy returnSequences)
in CNLayer
DLSTM
( fromList
[ ("units", units),
("returnSequences", returnSequences)
]
)
|
6c1d5e89f6f2593cac9bfbbbe48635dde503cfc816843eb14bb2302176a6ff30 | ocaml-ppx/ppx_tools_versioned | standalone.ml | open Migrate_parsetree
(* To run as a standalone binary, run the registered drivers *)
let () = Driver.run_main ()
| null | https://raw.githubusercontent.com/ocaml-ppx/ppx_tools_versioned/00a0150cdabfa7f0dad2c5e0e6b32230d22295ca/example/ppx_once/standalone.ml | ocaml | To run as a standalone binary, run the registered drivers | open Migrate_parsetree
let () = Driver.run_main ()
|
28f316b9fa1596fed43071c3ce649d4e3d24e0d00545c3c59ebc26ebed64609d | erlydtl/erlydtl | erlydtl_contrib_humanize.erl | -module(erlydtl_contrib_humanize).
-export([intcomma/1]).
intcomma(Value) when is_integer(Value) ->
intcomma(integer_to_list(Value));
intcomma(Value) ->
ValueBin = iolist_to_binary(Value),
intcomma(ValueBin, size(ValueBin) rem 3, <<>>).
intcomma(<<>>, _, Acc) ->
Acc;
intcomma(<< C, Rest/bits >>, 0, <<>>) ->
intcomma(Rest, 2, << C >>);
intcomma(<< C, Rest/bits >>, 0, Acc) ->
intcomma(Rest, 2, << Acc/binary, $,, C >>);
intcomma(<< C, Rest/bits >>, N, Acc) ->
intcomma(Rest, N - 1, << Acc/binary, C >>).
| null | https://raw.githubusercontent.com/erlydtl/erlydtl/c1f3df8379b09894d333de4e9a3ca2f3e260cba3/src/erlydtl_contrib_humanize.erl | erlang | -module(erlydtl_contrib_humanize).
-export([intcomma/1]).
intcomma(Value) when is_integer(Value) ->
intcomma(integer_to_list(Value));
intcomma(Value) ->
ValueBin = iolist_to_binary(Value),
intcomma(ValueBin, size(ValueBin) rem 3, <<>>).
intcomma(<<>>, _, Acc) ->
Acc;
intcomma(<< C, Rest/bits >>, 0, <<>>) ->
intcomma(Rest, 2, << C >>);
intcomma(<< C, Rest/bits >>, 0, Acc) ->
intcomma(Rest, 2, << Acc/binary, $,, C >>);
intcomma(<< C, Rest/bits >>, N, Acc) ->
intcomma(Rest, N - 1, << Acc/binary, C >>).
|
|
795b114c59fddf40b0bdb596524949125b8cd741f8d9761d9084acb6fc1bf71d | plumatic/grab-bag | hash.clj | (ns plumbing.hash
(:import
[plumbing MurmurHash]))
This is OK for hash functions but bad for collisions -- 31 is too small .
IE 2 char strings on average collide with 8 others .
(defn hash64 ^long [s]
(loop [h 1125899906842597
s (seq (name s))]
(if s
(recur (unchecked-add (unchecked-multiply 31 h) (long (int (first s)))) (next s))
h)))
;; About the same speed, it seems, and many fewer collisions.
(defn murmur64 ^long [^String s]
(MurmurHash/hash64 s))
| null | https://raw.githubusercontent.com/plumatic/grab-bag/a15e943322fbbf6f00790ce5614ba6f90de1a9b5/lib/plumbing/src/plumbing/hash.clj | clojure | About the same speed, it seems, and many fewer collisions. | (ns plumbing.hash
(:import
[plumbing MurmurHash]))
This is OK for hash functions but bad for collisions -- 31 is too small .
IE 2 char strings on average collide with 8 others .
(defn hash64 ^long [s]
(loop [h 1125899906842597
s (seq (name s))]
(if s
(recur (unchecked-add (unchecked-multiply 31 h) (long (int (first s)))) (next s))
h)))
(defn murmur64 ^long [^String s]
(MurmurHash/hash64 s))
|
18f74c55cac64125b10de327675f0f09ebb28b532ba34f57251d11624a5a4eec | instedd/planwise | dashboard.cljs | (ns planwise.client.projects2.components.dashboard
(:require [reagent.core :as r]
[re-frame.core :refer [subscribe dispatch] :as rf]
[re-com.core :as rc]
[clojure.string :refer [blank? capitalize]]
[planwise.client.asdf :as asdf]
[planwise.client.components.common2 :as common2]
[planwise.client.routes :as routes]
[planwise.client.ui.common :as ui]
[planwise.client.ui.rmwc :as m]
[planwise.client.utils :as utils]
[planwise.client.projects2.components.settings :as settings]
[planwise.common :refer [get-consumer-unit get-demand-unit get-provider-unit get-capacity-unit] :as common]))
(defn- project-tabs
[{:keys [active] :or {active :scenarios}}]
[m/TabBar {:activeTabIndex ({:scenarios 0 :settings 1} active)
:on-change (fn [evt]
(let [tab-index (.-value (.-target evt))]
(case tab-index
0 (dispatch [:projects2/project-scenarios])
1 (dispatch [:projects2/project-settings]))))}
[m/Tab "Scenarios"]
[m/Tab "Settings"]])
(defn- project-secondary-actions
[]
[[ui/menu-item {:on-click #(dispatch [:projects2/open-reset-dialog])
:icon "undo"}
"Back to draft"]
[ui/menu-item {:on-click #(dispatch [:projects2/open-delete-dialog])
:icon "delete"}
"Delete project"]])
(defn- create-chip
[input]
(when (not (blank? input)) [m/ChipSet [m/Chip [m/ChipText input]]]))
(defn- scenarios-list-item
[{:keys [project-id id name label state demand-coverage effort changeset-summary geo-coverage population-under-coverage index source-demand analysis-type]}]
(if id
[:tr {:key id :on-click (fn [evt]
(if (or (.-shiftKey evt) (.-metaKey evt))
(.open js/window (routes/scenarios {:project-id project-id :id id}))
(dispatch [:scenarios/load-scenario {:id id}])))}
[:td.col-state (cond (= state "pending") [create-chip state]
(not= label "initial") [create-chip label])]
[:td.col-name name]
[:td.col-demand-coverage
(some-> demand-coverage utils/format-number)]
[:td.col-pop-without-service
(when (and (some? demand-coverage) (some? population-under-coverage))
(utils/format-number (- population-under-coverage demand-coverage)))]
[:td.col-pop-without-coverage
(some-> source-demand
(- population-under-coverage)
utils/format-number)]
[:td.col-effort
(some-> effort
(utils/format-effort analysis-type))]
(if (empty? changeset-summary)
[:td.col-actions]
[:td.col-actions.has-tooltip
[:p changeset-summary]
[:div.tooltip changeset-summary]])]
[:tr {:key (str "tr-" index)}
(map (fn [n] [:td {:key (str "td-" index "-" n)}]) (range 7))]))
(defn- generate-title
[num source-demand]
(str (common/pluralize num "scenario")
(if (some? source-demand)
(str " (Target population: " (utils/format-number source-demand) ")"))))
(defn- sort-scenarios
[scenarios key order]
(letfn [(keyfn [scenario]
(case key
:without-service (- (:population-under-coverage scenario) (:demand-coverage scenario))
; Column 'Without coverage' displays `demand-source - population-under-coverage`
:without-coverage (- (:population-under-coverage scenario))
(get scenario key)))]
(cond
(or (nil? key) (nil? order)) scenarios
:else (sort-by keyfn (if (= order :asc) #(< %1 %2) #(> %1 %2)) scenarios))))
(defn- next-order
[order]
(cond
(nil? order) :asc
(= order :asc) :desc
:else nil))
(defn- scenarios-sortable-header
[{:keys [sorting-key] :as props} title]
(let [column (rf/subscribe [:scenarios/sort-column])
order (rf/subscribe [:scenarios/sort-order])
new-props (-> props
(dissoc :sorting-key)
(assoc
:on-click #(rf/dispatch [:scenarios/change-sort-column-order sorting-key (if (= sorting-key @column) (next-order @order) :asc)])
:order @order
:sorted (and (= sorting-key @column) (not (nil? @order)))))]
[ui/sortable-table-header new-props title]))
(defn- scenarios-list
[scenarios current-project]
(let [num (count scenarios)
source-demand (get-in current-project [:engine-config :source-demand])
analysis-type (get-in current-project [:config :analysis-type])
sort-column (rf/subscribe [:scenarios/sort-column])
sort-order (rf/subscribe [:scenarios/sort-order])
sorted-scenarios (sort-scenarios scenarios @sort-column @sort-order)
demand-unit (get-demand-unit current-project)
provider-unit (get-provider-unit current-project)
capacity-unit (get-capacity-unit current-project)
effort-label (if (common/is-budget analysis-type) "Investment" "Effort")]
[:div.scenarios-content
[:table.mdc-data-table__table
[:caption (generate-title num source-demand)]
[:thead.rmwc-data-table__head
[:tr.rmwc-data-table__row.mdc-data-table__header-row
[:th.col-state ""]
[scenarios-sortable-header {:class [:col-name]
:align :left
:sorting-key :name}
"Name"]
[scenarios-sortable-header {:class [:col-demand-coverage]
:align :right
:sorting-key :demand-coverage
:tooltip (str (capitalize demand-unit) " within " provider-unit " catchment area, with access to " capacity-unit " within capacity.")}
"Population with service"]
[scenarios-sortable-header {:class [:col-pop-without-service]
:align :right
:sorting-key :without-service
:tooltip (str (capitalize demand-unit) " within " provider-unit " catchment area but without enough " capacity-unit " to provide service.")}
"Without service"]
[scenarios-sortable-header {:class [:col-pop-without-coverage]
:align :right
:sorting-key :without-coverage
:tooltip (str (capitalize demand-unit) " outside catchment area of " provider-unit ".")}
"Without coverage"]
[scenarios-sortable-header {:class [:col-effort]
:align :right
:sorting-key :effort}
effort-label]
[:th.col-actions [:p "Actions"]]]]
[:tbody
(map-indexed (fn [index scenario]
(scenarios-list-item (assoc scenario
:project-id (:id current-project)
:index index
:source-demand source-demand
:analysis-type analysis-type)))
(concat sorted-scenarios (repeat (- 5 num) nil)))]]]))
(defn- project-settings
[step]
[settings/current-project-settings-view {:read-only true :step step}])
(defn view-current-project
[active-tab]
(let [current-project (rf/subscribe [:projects2/current-project])
scenarios-sub (rf/subscribe [:scenarios/list])
page-params (rf/subscribe [:page-params])]
(fn [active-tab]
(let [scenarios (asdf/value @scenarios-sub)]
(when (asdf/should-reload? @scenarios-sub)
(rf/dispatch [:scenarios/load-scenarios]))
(cond
(asdf/reloading? scenarios) [common2/loading-placeholder]
:else
[ui/fixed-width (merge (common2/nav-params)
{:title (:name @current-project)
:tabs [project-tabs {:active active-tab}]
:secondary-actions (project-secondary-actions)})
[ui/panel {}
(case active-tab
:scenarios [scenarios-list scenarios @current-project]
:settings [project-settings (:step @page-params)])]])))))
| null | https://raw.githubusercontent.com/instedd/planwise/21d28bf55216df3986e4f1b6cbb5fa86bb9f30ad/client/src/planwise/client/projects2/components/dashboard.cljs | clojure | Column 'Without coverage' displays `demand-source - population-under-coverage` | (ns planwise.client.projects2.components.dashboard
(:require [reagent.core :as r]
[re-frame.core :refer [subscribe dispatch] :as rf]
[re-com.core :as rc]
[clojure.string :refer [blank? capitalize]]
[planwise.client.asdf :as asdf]
[planwise.client.components.common2 :as common2]
[planwise.client.routes :as routes]
[planwise.client.ui.common :as ui]
[planwise.client.ui.rmwc :as m]
[planwise.client.utils :as utils]
[planwise.client.projects2.components.settings :as settings]
[planwise.common :refer [get-consumer-unit get-demand-unit get-provider-unit get-capacity-unit] :as common]))
(defn- project-tabs
[{:keys [active] :or {active :scenarios}}]
[m/TabBar {:activeTabIndex ({:scenarios 0 :settings 1} active)
:on-change (fn [evt]
(let [tab-index (.-value (.-target evt))]
(case tab-index
0 (dispatch [:projects2/project-scenarios])
1 (dispatch [:projects2/project-settings]))))}
[m/Tab "Scenarios"]
[m/Tab "Settings"]])
(defn- project-secondary-actions
[]
[[ui/menu-item {:on-click #(dispatch [:projects2/open-reset-dialog])
:icon "undo"}
"Back to draft"]
[ui/menu-item {:on-click #(dispatch [:projects2/open-delete-dialog])
:icon "delete"}
"Delete project"]])
(defn- create-chip
[input]
(when (not (blank? input)) [m/ChipSet [m/Chip [m/ChipText input]]]))
(defn- scenarios-list-item
[{:keys [project-id id name label state demand-coverage effort changeset-summary geo-coverage population-under-coverage index source-demand analysis-type]}]
(if id
[:tr {:key id :on-click (fn [evt]
(if (or (.-shiftKey evt) (.-metaKey evt))
(.open js/window (routes/scenarios {:project-id project-id :id id}))
(dispatch [:scenarios/load-scenario {:id id}])))}
[:td.col-state (cond (= state "pending") [create-chip state]
(not= label "initial") [create-chip label])]
[:td.col-name name]
[:td.col-demand-coverage
(some-> demand-coverage utils/format-number)]
[:td.col-pop-without-service
(when (and (some? demand-coverage) (some? population-under-coverage))
(utils/format-number (- population-under-coverage demand-coverage)))]
[:td.col-pop-without-coverage
(some-> source-demand
(- population-under-coverage)
utils/format-number)]
[:td.col-effort
(some-> effort
(utils/format-effort analysis-type))]
(if (empty? changeset-summary)
[:td.col-actions]
[:td.col-actions.has-tooltip
[:p changeset-summary]
[:div.tooltip changeset-summary]])]
[:tr {:key (str "tr-" index)}
(map (fn [n] [:td {:key (str "td-" index "-" n)}]) (range 7))]))
(defn- generate-title
[num source-demand]
(str (common/pluralize num "scenario")
(if (some? source-demand)
(str " (Target population: " (utils/format-number source-demand) ")"))))
(defn- sort-scenarios
[scenarios key order]
(letfn [(keyfn [scenario]
(case key
:without-service (- (:population-under-coverage scenario) (:demand-coverage scenario))
:without-coverage (- (:population-under-coverage scenario))
(get scenario key)))]
(cond
(or (nil? key) (nil? order)) scenarios
:else (sort-by keyfn (if (= order :asc) #(< %1 %2) #(> %1 %2)) scenarios))))
(defn- next-order
[order]
(cond
(nil? order) :asc
(= order :asc) :desc
:else nil))
(defn- scenarios-sortable-header
[{:keys [sorting-key] :as props} title]
(let [column (rf/subscribe [:scenarios/sort-column])
order (rf/subscribe [:scenarios/sort-order])
new-props (-> props
(dissoc :sorting-key)
(assoc
:on-click #(rf/dispatch [:scenarios/change-sort-column-order sorting-key (if (= sorting-key @column) (next-order @order) :asc)])
:order @order
:sorted (and (= sorting-key @column) (not (nil? @order)))))]
[ui/sortable-table-header new-props title]))
(defn- scenarios-list
[scenarios current-project]
(let [num (count scenarios)
source-demand (get-in current-project [:engine-config :source-demand])
analysis-type (get-in current-project [:config :analysis-type])
sort-column (rf/subscribe [:scenarios/sort-column])
sort-order (rf/subscribe [:scenarios/sort-order])
sorted-scenarios (sort-scenarios scenarios @sort-column @sort-order)
demand-unit (get-demand-unit current-project)
provider-unit (get-provider-unit current-project)
capacity-unit (get-capacity-unit current-project)
effort-label (if (common/is-budget analysis-type) "Investment" "Effort")]
[:div.scenarios-content
[:table.mdc-data-table__table
[:caption (generate-title num source-demand)]
[:thead.rmwc-data-table__head
[:tr.rmwc-data-table__row.mdc-data-table__header-row
[:th.col-state ""]
[scenarios-sortable-header {:class [:col-name]
:align :left
:sorting-key :name}
"Name"]
[scenarios-sortable-header {:class [:col-demand-coverage]
:align :right
:sorting-key :demand-coverage
:tooltip (str (capitalize demand-unit) " within " provider-unit " catchment area, with access to " capacity-unit " within capacity.")}
"Population with service"]
[scenarios-sortable-header {:class [:col-pop-without-service]
:align :right
:sorting-key :without-service
:tooltip (str (capitalize demand-unit) " within " provider-unit " catchment area but without enough " capacity-unit " to provide service.")}
"Without service"]
[scenarios-sortable-header {:class [:col-pop-without-coverage]
:align :right
:sorting-key :without-coverage
:tooltip (str (capitalize demand-unit) " outside catchment area of " provider-unit ".")}
"Without coverage"]
[scenarios-sortable-header {:class [:col-effort]
:align :right
:sorting-key :effort}
effort-label]
[:th.col-actions [:p "Actions"]]]]
[:tbody
(map-indexed (fn [index scenario]
(scenarios-list-item (assoc scenario
:project-id (:id current-project)
:index index
:source-demand source-demand
:analysis-type analysis-type)))
(concat sorted-scenarios (repeat (- 5 num) nil)))]]]))
(defn- project-settings
[step]
[settings/current-project-settings-view {:read-only true :step step}])
(defn view-current-project
[active-tab]
(let [current-project (rf/subscribe [:projects2/current-project])
scenarios-sub (rf/subscribe [:scenarios/list])
page-params (rf/subscribe [:page-params])]
(fn [active-tab]
(let [scenarios (asdf/value @scenarios-sub)]
(when (asdf/should-reload? @scenarios-sub)
(rf/dispatch [:scenarios/load-scenarios]))
(cond
(asdf/reloading? scenarios) [common2/loading-placeholder]
:else
[ui/fixed-width (merge (common2/nav-params)
{:title (:name @current-project)
:tabs [project-tabs {:active active-tab}]
:secondary-actions (project-secondary-actions)})
[ui/panel {}
(case active-tab
:scenarios [scenarios-list scenarios @current-project]
:settings [project-settings (:step @page-params)])]])))))
|
c9029856fc0357f77c90832b27680dd90ba0d42ed46b58cf9d7be1a18f9999b4 | silky/quipper | Arith.hs | This file is part of Quipper . Copyright ( C ) 2011 - 2016 . Please see the
-- file COPYRIGHT for a list of authors, copyright holders, licensing,
-- and other details. All rights reserved.
--
-- ======================================================================
import Quipper
import QuipperLib.Arith
main :: IO ()
main = print_generic Preview labelled_add (qdint_shape 3) (qdint_shape 3)
labelled_add :: QDInt -> QDInt -> Circ (QDInt, QDInt,QDInt)
labelled_add x y = do
label (x,y) ("x","y")
xy <- q_add x y
label xy ("x","y","x+y")
return xy | null | https://raw.githubusercontent.com/silky/quipper/1ef6d031984923d8b7ded1c14f05db0995791633/tests/Arith.hs | haskell | file COPYRIGHT for a list of authors, copyright holders, licensing,
and other details. All rights reserved.
====================================================================== | This file is part of Quipper . Copyright ( C ) 2011 - 2016 . Please see the
import Quipper
import QuipperLib.Arith
main :: IO ()
main = print_generic Preview labelled_add (qdint_shape 3) (qdint_shape 3)
labelled_add :: QDInt -> QDInt -> Circ (QDInt, QDInt,QDInt)
labelled_add x y = do
label (x,y) ("x","y")
xy <- q_add x y
label xy ("x","y","x+y")
return xy |
854ed9dfaab44002ce2f50ec49aa944471ab09a0de118f103f1f9e2122583149 | antono/guix-debian | nano.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2012 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix 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 GNU . If not , see < / > .
(define-module (gnu packages nano)
#:use-module (guix licenses)
#:use-module (gnu packages gettext)
#:use-module (gnu packages ncurses)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu))
(define-public nano
(package
(name "nano")
(version "2.3.6")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.gz"))
(sha256
(base32
"0d4ml0v9yi37pjs211xs38w9whsj6530wz3kmrvwgh8jigqz6jx7"))))
(build-system gnu-build-system)
(inputs
`(("gettext" ,gnu-gettext)
("ncurses" ,ncurses)))
(home-page "-editor.org/")
(synopsis "Small, user-friendly console text editor")
(description
"GNU Nano is a small and simple text editor. In addition to basic
editing, it supports interactive search and replace, go to line and column
number, auto-indentation and more.")
(license gpl3+))) ; some files are under GPLv2+
| null | https://raw.githubusercontent.com/antono/guix-debian/85ef443788f0788a62010a942973d4f7714d10b4/gnu/packages/nano.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix 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.
some files are under GPLv2+ | Copyright © 2012 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages nano)
#:use-module (guix licenses)
#:use-module (gnu packages gettext)
#:use-module (gnu packages ncurses)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu))
(define-public nano
(package
(name "nano")
(version "2.3.6")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.gz"))
(sha256
(base32
"0d4ml0v9yi37pjs211xs38w9whsj6530wz3kmrvwgh8jigqz6jx7"))))
(build-system gnu-build-system)
(inputs
`(("gettext" ,gnu-gettext)
("ncurses" ,ncurses)))
(home-page "-editor.org/")
(synopsis "Small, user-friendly console text editor")
(description
"GNU Nano is a small and simple text editor. In addition to basic
editing, it supports interactive search and replace, go to line and column
number, auto-indentation and more.")
|
9fe57138ecd0501893baa526b9b219231ebe2b17eeb9582020e419196f43be68 | kupl/FixML | sub5.ml | type crazy2 = NIL | ZERO of crazy2 | ONE of crazy2 | MONE of crazy2
exception E
let rec crazy2add (a, b) =
let rec add (a, b) =
match (a, b) with
(ZERO c, ZERO d) -> ZERO(crazy2add(c, d))
|(ONE c, MONE d) -> ZERO(crazy2add(c, d))
|(MONE c, ONE d) -> ZERO(crazy2add(c, d))
| (ZERO c, ONE d) ->ONE(crazy2add(c, d))
| (ONE c, ZERO d) -> ONE(crazy2add(c, d))
| (ZERO c, MONE d) -> MONE(crazy2add(c, d))
| (MONE c, ZERO d) -> MONE(crazy2add(c, d))
| (ONE c, ONE d) -> ZERO(crazy2add(ONE(NIL),(crazy2add(c, d))))
| (MONE c, MONE d) -> ZERO(crazy2add(MONE(NIL),(crazy2add(c, d))))
| (NIL, b) -> b
| (a, NIL) -> a in
let rec trim a =
match a with
NIL -> NIL
|ONE b -> ONE(trim b)
|MONE b -> MONE(trim b)
|ZERO b ->
match b with
NIL -> NIL
|ONE c -> ZERO(trim b)
|MONE c -> ZERO(trim b)
|ZERO c -> trim(ZERO(trim b)) in
let rec zero a =
match a with
NIL -> ZERO NIL
|_ -> a in
zero(trim(add(a, b)))
| null | https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/benchmarks/crazy2add/crazy2add/submissions/sub5.ml | ocaml | type crazy2 = NIL | ZERO of crazy2 | ONE of crazy2 | MONE of crazy2
exception E
let rec crazy2add (a, b) =
let rec add (a, b) =
match (a, b) with
(ZERO c, ZERO d) -> ZERO(crazy2add(c, d))
|(ONE c, MONE d) -> ZERO(crazy2add(c, d))
|(MONE c, ONE d) -> ZERO(crazy2add(c, d))
| (ZERO c, ONE d) ->ONE(crazy2add(c, d))
| (ONE c, ZERO d) -> ONE(crazy2add(c, d))
| (ZERO c, MONE d) -> MONE(crazy2add(c, d))
| (MONE c, ZERO d) -> MONE(crazy2add(c, d))
| (ONE c, ONE d) -> ZERO(crazy2add(ONE(NIL),(crazy2add(c, d))))
| (MONE c, MONE d) -> ZERO(crazy2add(MONE(NIL),(crazy2add(c, d))))
| (NIL, b) -> b
| (a, NIL) -> a in
let rec trim a =
match a with
NIL -> NIL
|ONE b -> ONE(trim b)
|MONE b -> MONE(trim b)
|ZERO b ->
match b with
NIL -> NIL
|ONE c -> ZERO(trim b)
|MONE c -> ZERO(trim b)
|ZERO c -> trim(ZERO(trim b)) in
let rec zero a =
match a with
NIL -> ZERO NIL
|_ -> a in
zero(trim(add(a, b)))
|
|
90d65c88e5206a0a28920b38f1c73e6b263fb6ff906bb45a162b0570cb4b0614 | alanz/ghc-exactprint | SemicolonIf.hs | module Bar where
import Data.Text as Text
replace :: Text -> Text
replace = Text.map (\c -> if c == '_' then '.'; else c)
replace1 :: Text -> Text
replace1 = Text.map (\c -> if c == '_' ; then '.' else c)
replace2 :: Text -> Text
replace2 = Text.map (\c -> if c == '_'; then '.'; else c)
replace4 :: Text -> Text
replace4 = Text.map (\c -> if c == '_' then '.' else c)
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc80/SemicolonIf.hs | haskell | module Bar where
import Data.Text as Text
replace :: Text -> Text
replace = Text.map (\c -> if c == '_' then '.'; else c)
replace1 :: Text -> Text
replace1 = Text.map (\c -> if c == '_' ; then '.' else c)
replace2 :: Text -> Text
replace2 = Text.map (\c -> if c == '_'; then '.'; else c)
replace4 :: Text -> Text
replace4 = Text.map (\c -> if c == '_' then '.' else c)
|
|
c188b9841fe7b2abc22764e8984821c0b1620057bb7ba381b99cdd918944c933 | graninas/Hydra | Interpreters.hs | module Hydra.Core.Interpreters
( module X
) where
import Hydra.Core.ControlFlow.Interpreter as X
import Hydra.Core.Lang.Interpreter as X
import Hydra . Core . Logger . Interpreter as X
import Hydra.Core.Process.Interpreter as X
import Hydra.Core.Process.Impl as X
import Hydra.Core.Random.Interpreter as X
import Hydra.Core.State.Interpreter as X
| null | https://raw.githubusercontent.com/graninas/Hydra/60d591b1300528f5ffd93efa205012eebdd0286c/lib/hydra-church-free/src/Hydra/Core/Interpreters.hs | haskell | module Hydra.Core.Interpreters
( module X
) where
import Hydra.Core.ControlFlow.Interpreter as X
import Hydra.Core.Lang.Interpreter as X
import Hydra . Core . Logger . Interpreter as X
import Hydra.Core.Process.Interpreter as X
import Hydra.Core.Process.Impl as X
import Hydra.Core.Random.Interpreter as X
import Hydra.Core.State.Interpreter as X
|
|
8c6fa4cb72a187c937be266eab06f75e7e4bb6e056c3f3f12df47c548d5869ec | jwiegley/notes | Simple.hs | sourceGenerator :: Monad m
=> (forall s. ((Generator s -> Source m (Generatee s)) -> m a))
-> m a
sourceGenerator f = f $ \gen -> source (go gen)
where
go start z yield = loop start z
where
loop gen r =
let (gen', g) = generate gen
in yield r g >>= loop gen'
| null | https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/gists/6e2665b62008f020b881/Simple.hs | haskell | sourceGenerator :: Monad m
=> (forall s. ((Generator s -> Source m (Generatee s)) -> m a))
-> m a
sourceGenerator f = f $ \gen -> source (go gen)
where
go start z yield = loop start z
where
loop gen r =
let (gen', g) = generate gen
in yield r g >>= loop gen'
|
|
f2783edb1e707f935a36e4b9baa9f4fff78653c24924a8aa005fe8874a0b6263 | odis-labs/helix | Html.mli | (** Build HTML content. *)
open Stdweb
type node = Dom.Node.t
type html
(** The type for HTML elements or character data. *)
* { 1 : attr Attributes }
See the { { : -US/docs/Web/HTML/Attributes } MDN
HTML attribute reference } .
See the {{:-US/docs/Web/HTML/Attributes} MDN
HTML attribute reference}. *)
type attr
(** The type for attributes and their values. *)
val attr : string -> string -> attr
(** [attr name v] is an attribute [name] with value [v]. *)
val accept : string -> attr
(** See {{:-US/docs/Web/HTML/Attributes/accept}
accept}. *)
val accesskey : string -> attr
(** See
{{:-US/docs/Web/HTML/Global_attributes/accesskey}
accesskey}. *)
val action : string -> attr
(** See
{{:-US/docs/Web/HTML/Element/form#attr-action}
action}. *)
val autocomplete : string -> attr
(** See
{{:-US/docs/Web/HTML/Attributes/autocomplete}
autocomplete}. *)
val autofocus : attr
(** See
{{:-US/docs/Web/HTML/Global_attributes/autofocus}
autofocus}. *)
val charset : string -> attr
(** See {{:-US/docs/Web/HTML/Attributes}
charset}. *)
val checked : attr
(** See
{{:-US/docs/Web/HTML/Element/input#checked}
checked}. *)
val class_name : string -> attr
(** See
{{:-US/docs/Web/HTML/Global_attributes/class}
class}. *)
val cols : int -> attr
(** See
{{:-US/docs/Web/HTML/Element/textarea#attr-cols}
cols}. *)
val content : string -> attr
(** See
{{:-US/docs/Web/HTML/Element/meta#attr-content}
content}. *)
val contenteditable : bool -> attr
(** See
{{:-US/docs/Web/HTML/Global_attributes/contenteditable}
contenteditable}. *)
val defer : attr
(** See
{{:-US/docs/Web/HTML/Element/script#attr-defer}
defer}. *)
val dir : string -> attr
(** See
{{:-US/docs/Web/HTML/Global_attributes/dir}
dir}. *)
val disabled : attr
(** See
{{:-US/docs/Web/HTML/Attributes/disabled}
disabled}. *)
val draggable : bool -> attr
(** See
{{:-US/docs/Web/HTML/Global_attributes/draggable}
draggable}. *)
val for' : string -> attr
(** See {{:-US/docs/Web/HTML/Attributes/for}
for'}. *)
val height : int -> attr
(** See {{:-US/docs/Web/HTML/Attributes}
height}. *)
val hidden : attr
(** See
{{:-US/docs/Web/HTML/Global_attributes/hidden}
hidden}. *)
val href : string -> attr
(** See {{:-US/docs/Web/HTML/Attributes} href}. *)
val id : string -> attr
(** See
{{:-US/docs/Web/HTML/Global_attributes/id}
id}. *)
val lang : string -> attr
(** See
{{:-US/docs/Web/HTML/Global_attributes/lang}
lang}. *)
val list : string -> attr
(** See
{{:-US/docs/Web/HTML/Element/input#attr-list}
list}. *)
val media : string -> attr
(** See {{:-US/docs/Web/HTML/Attributes} media}. *)
val method' : string -> attr
(** See
{{:-US/docs/Web/HTML/Element/form#attr-method}
method}. *)
val name : string -> attr
(** See {{:-US/docs/Web/HTML/Attributes} name}. *)
val placeholder : string -> attr
(** See {{:-US/docs/Web/HTML/Attributes}
placeholder}. *)
val rel : string -> attr
(** See {{:-US/docs/Web/HTML/Attributes/rel}
rel}. *)
val required : attr
(** See
{{:-US/docs/Web/HTML/Attributes/required}
required}. *)
val rows : int -> attr
(** See
{{:-US/docs/Web/HTML/Element/textarea#attr-rows}
rows}. *)
val selected : attr
(** See
{{:-US/docs/Web/HTML/Element/option#attr-selected}
selected}. *)
val spellcheck : string -> attr
(** See
{{:-US/docs/Web/HTML/Global_attributes/spellcheck}
spellcheck}. *)
val src : string -> attr
(** See {{:-US/docs/Web/HTML/Attributes} src}. *)
val style : (string * string) list -> attr
(** See
{{:-US/docs/Web/HTML/Global_attributes/style}
style}. *)
val tabindex : int -> attr
(** See
{{:-US/docs/Web/HTML/Global_attributes/tabindex}
tabindex}. *)
val title : string -> attr
(** See
{{:-US/docs/Web/HTML/Global_attributes/title}
title}. *)
val type' : string -> attr
(** See {{:-US/docs/Web/HTML/Attributes} type}. *)
val value : string -> attr
(** See {{:-US/docs/Web/HTML/Attributes} value}. *)
val wrap : string -> attr
(** See
{{:-US/docs/Web/HTML/Element/textarea#attr-wrap}
wrap}. *)
val width : int -> attr
(** See {{:-US/docs/Web/HTML/Attributes} width}. *)
val class_list : string list -> attr
(** [class_list list] is similar to {!class_name} but accepts a list of class
names. *)
val class_flags : (string * bool) list -> attr
(** [class_flags list] is similar to {!class_list}, but can conditionally omit
class names depending on the boolean values in [list]. *)
* { 2 Event attributes }
val on : 'a Dom.Event.kind -> ('a Dom.Event.t -> unit) -> attr
val on_click : (Dom.Event.Mouse.t -> unit) -> attr
val on_input : (Dom.Event.Input.t -> unit) -> attr
val on_keydown : (Dom.Event.Keyboard.t -> unit) -> attr
(** Additional attribute operations. *)
module Attr : sig
type t = attr
(** The type for HTML attributes. *)
val empty : attr
(** [empty] is an attribute that doesn't get rendered. *)
val bool : string -> bool -> attr
* [ bool name value ] is [ attr name " " ] if [ value ] is [ true ] and { ! empty }
otherwise .
This sets the
{ { : -microsyntaxes.html#boolean-attributes }
boolean attribute } [ n ] to true . The attribute will be omitted if [ b ] is
false .
otherwise.
This sets the
{{:-microsyntaxes.html#boolean-attributes}
boolean attribute} [n] to true. The attribute will be omitted if [b] is
false. *)
val int : string -> int -> attr
(** [int name value] is [attr name (string_of_int i)]. *)
val on : bool -> t -> attr
(** [on cond attr] is [attr] if [cond] is [true] and {!empty} otherwise. *)
val on_some : attr option -> attr
(** [on_some option] is [attr] if [option] is [Some attr] and {!empty} if
[option] is [None]. *)
val on_ok : (attr, 'e) result -> attr
(** [on_ok result] is [attr] if [result] is [Ok attr] and {!empty} if [result]
is [Error _]. *)
val on_mount : (Dom.Element.t -> unit) -> attr
(** [on_mount f] is an HTML attribute that calls [f] with an element this
attribute is added to. *)
module Internal : sig
type t = { set : Dom.Element.t -> unit; remove : Dom.Element.t -> unit }
val of_attr : attr -> t
val to_attr : t -> attr
end
end
* { 1 : elem Elements }
val node : string -> attr list -> node list -> node
val elem : string -> attr list -> html list -> html
* [ elem name attrs children ] is an HTML element named [ name ] with attributes
[ attr ] and [ children ] .
[attr] and [children]. *)
val empty : html
(** [empty] is an empty element that will not be rendered. *)
val text : string -> html
(** [text s] is character data [s]. [s] will be escaped. *)
val int : int -> html
(** [int n] is [text (string_of_int n)]. *)
val nbsp : html
(** [nbsp] is [text "\u{00A0}"]. *)
val fragment : html list -> html
(** See {{:-US/docs/Web/API/DocumentFragment}
[DocumentFragment]}. *)
val a : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/a} a}. *)
val abbr : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/abbr}
abbr}. *)
val address : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/address}
address}. *)
val area : attr list -> html
(** See {{:-US/docs/Web/HTML/Element/area}
area}. *)
val article : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/article}
article}. *)
val aside : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/aside}
aside}. *)
val audio : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/audio}
audio}. *)
val b : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/b} b}. *)
val base : attr list -> html
(** See {{:-US/docs/Web/HTML/Element/base}
base}. *)
val bdi : attr list -> html list -> html
* See { { : -US/docs/Web/HTML/Element/bdi } bdi } .
val bdo : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/bdo} bdo}. *)
val blockquote : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/blockquote}
blockquote}. *)
val br : attr list -> html
(** See {{:-US/docs/Web/HTML/Element/br} br}. *)
val button : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/button}
button}. *)
val canvas : attr list -> html list -> html
* See { { : canvas } .
canvas}. *)
val caption : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/caption}
caption}. *)
val cite : attr list -> html list -> html
* See { { : -US/docs/Web/HTML/Element/cite }
cite } .
cite}. *)
val code : attr list -> string -> html
(** See {{:-US/docs/Web/HTML/Element/code}
code}. *)
val col : attr list -> html
* See { { : } col } .
val colgroup : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/colgroup}
colgroup}. *)
val command : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/command}
command}. *)
val datalist : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/datalist}
datalist}. *)
val dd : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/dd} dd}. *)
val del : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/del} del}. *)
val details : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/details}
details}. *)
val dfn : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/dfn} dfn}. *)
val div : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/div} div}. *)
val dl : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/dl} dl}. *)
val dt : attr list -> html list -> html
* See { { : } .
val em : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/em} em}. *)
val embed : attr list -> html
(** See {{:-US/docs/Web/HTML/Element/embed}
embed}. *)
val fieldset : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/fieldset}
fieldset}. *)
val figcaption : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/figcaption}
figcaption}. *)
val figure : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/figure}
figure}. *)
val footer : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/footer}
footer}. *)
val form : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/form}
form}. *)
val h1 : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/h1} h1}. *)
val h2 : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/h2} h2}. *)
val h3 : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/h3} h3}. *)
val h4 : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/h4} h4}. *)
val h5 : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/h5} h5}. *)
val h6 : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/h6} h6}. *)
val head : attr list -> html list -> html
* See { { : }
head } .
head}. *)
val header : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/header}
header}. *)
val hgroup : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/hgroup}
hgroup}. *)
val hr : attr list -> html
(** See {{:-US/docs/Web/HTML/Element/hr} hr}. *)
val html : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/html}
html}. *)
val i : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/i} i}. *)
val iframe : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/iframe}
iframe}. *)
val img : attr list -> html
* See { { : .
val input : attr list -> html
(** See {{:-US/docs/Web/HTML/Element/input}
input}. *)
val ins : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/ins} ins}. *)
val kbd : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/kbd} kbd}. *)
val keygen : attr list -> html list -> html
* See { { : }
keygen } .
keygen}. *)
val label : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/label}
label}. *)
val legend : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/legend}
legend}. *)
val li : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/li} li}. *)
val main : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/main}
main}. *)
val map : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/map} map}. *)
val mark : attr list -> html list -> html
* See { { : -US/docs/Web/HTML/Element/mark }
mark } .
mark}. *)
val menu : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/menu}
menu}. *)
val meta : attr list -> html
(** See {{:-US/docs/Web/HTML/Element/meta}
meta}. *)
val meter : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/meter}
meter}. *)
val nav : attr list -> html list -> html
* See { { : .
val object' : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/object}
object}. *)
val ol : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/ol} ol}. *)
val optgroup : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/optgroup}
optgroup}. *)
val option : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/option}
option}. *)
val output : attr list -> html list -> html
* See { { : }
output } .
output}. *)
val p : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/p} p}. *)
val param : attr list -> html
(** See {{:-US/docs/Web/HTML/Element/param}
param}. *)
val pre : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/pre} pre}. *)
val progress : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/progress}
progress}. *)
val q : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/q} q}. *)
val rp : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/rp} rp}. *)
val rt : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/rt} rt}. *)
val ruby : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/ruby}
ruby}. *)
val s : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/s} s}. *)
val samp : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/samp}
samp}. *)
val section : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/section}
section}. *)
val select : attr list -> html list -> html
* See { { : -US/docs/Web/HTML/Element/select }
select } .
select}. *)
val small : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/small}
small}. *)
val source : attr list -> html
(** See {{:-US/docs/Web/HTML/Element/source}
source}. *)
val span : attr list -> html list -> html
* See { { : -US/docs/Web/HTML/Element/span }
span } .
span}. *)
val strong : attr list -> html list -> html
* See { { : -US/docs/Web/HTML/Element/strong }
strong } .
strong}. *)
val sub : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/sub} sub}. *)
val summary : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/summary}
summary}. *)
val sup : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/sup} sup}. *)
val table : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/table}
table}. *)
val tbody : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/tbody}
tbody}. *)
val td : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/td} td}. *)
val textarea : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/textarea}
textarea}. *)
val tfoot : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/tfoot}
tfoot}. *)
val th : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/th} th}. *)
val thead : attr list -> html list -> html
* See { { : }
thead } .
thead}. *)
val time : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/time}
time}. *)
val tr : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/tr} tr}. *)
val track : attr list -> html
(** See {{:-US/docs/Web/HTML/Element/track}
track}. *)
val u : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/u} u}. *)
val ul : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/ul} ul}. *)
val var : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/var} var}. *)
val video : attr list -> html list -> html
(** See {{:-US/docs/Web/HTML/Element/video}
video}. *)
val wbr : attr list -> html
* See { { : -US/docs/Web/HTML/Element/wbr } wbr } .
(** Additional element operations. *)
module Elem : sig
type t = html
(** Type alias for HTML elements. *)
val of_some : ('a -> html) -> 'a option -> html
(** [of_some to_html option] is [to_html x] if [option] is [Some x] and
[empty] otherwise. *)
val of_ok : ('a -> html) -> ('a, 'e) result -> html
(** [of_ok to_html result] is [to_html x] if [result] is [Ok x] and [empty]
otherwise. *)
module Internal : sig
type t = { mount : Dom.Node.t -> unit; remove : unit -> unit }
val of_html : html -> t
val to_html : t -> html
end
end
* { 2 DOM helpers }
val render : Dom.Element.t -> html -> unit
| null | https://raw.githubusercontent.com/odis-labs/helix/365259b9d20a391fe94c7adffbd158fdec4d7f0c/src/html/Html.mli | ocaml | * Build HTML content.
* The type for HTML elements or character data.
* The type for attributes and their values.
* [attr name v] is an attribute [name] with value [v].
* See {{:-US/docs/Web/HTML/Attributes/accept}
accept}.
* See
{{:-US/docs/Web/HTML/Global_attributes/accesskey}
accesskey}.
* See
{{:-US/docs/Web/HTML/Element/form#attr-action}
action}.
* See
{{:-US/docs/Web/HTML/Attributes/autocomplete}
autocomplete}.
* See
{{:-US/docs/Web/HTML/Global_attributes/autofocus}
autofocus}.
* See {{:-US/docs/Web/HTML/Attributes}
charset}.
* See
{{:-US/docs/Web/HTML/Element/input#checked}
checked}.
* See
{{:-US/docs/Web/HTML/Global_attributes/class}
class}.
* See
{{:-US/docs/Web/HTML/Element/textarea#attr-cols}
cols}.
* See
{{:-US/docs/Web/HTML/Element/meta#attr-content}
content}.
* See
{{:-US/docs/Web/HTML/Global_attributes/contenteditable}
contenteditable}.
* See
{{:-US/docs/Web/HTML/Element/script#attr-defer}
defer}.
* See
{{:-US/docs/Web/HTML/Global_attributes/dir}
dir}.
* See
{{:-US/docs/Web/HTML/Attributes/disabled}
disabled}.
* See
{{:-US/docs/Web/HTML/Global_attributes/draggable}
draggable}.
* See {{:-US/docs/Web/HTML/Attributes/for}
for'}.
* See {{:-US/docs/Web/HTML/Attributes}
height}.
* See
{{:-US/docs/Web/HTML/Global_attributes/hidden}
hidden}.
* See {{:-US/docs/Web/HTML/Attributes} href}.
* See
{{:-US/docs/Web/HTML/Global_attributes/id}
id}.
* See
{{:-US/docs/Web/HTML/Global_attributes/lang}
lang}.
* See
{{:-US/docs/Web/HTML/Element/input#attr-list}
list}.
* See {{:-US/docs/Web/HTML/Attributes} media}.
* See
{{:-US/docs/Web/HTML/Element/form#attr-method}
method}.
* See {{:-US/docs/Web/HTML/Attributes} name}.
* See {{:-US/docs/Web/HTML/Attributes}
placeholder}.
* See {{:-US/docs/Web/HTML/Attributes/rel}
rel}.
* See
{{:-US/docs/Web/HTML/Attributes/required}
required}.
* See
{{:-US/docs/Web/HTML/Element/textarea#attr-rows}
rows}.
* See
{{:-US/docs/Web/HTML/Element/option#attr-selected}
selected}.
* See
{{:-US/docs/Web/HTML/Global_attributes/spellcheck}
spellcheck}.
* See {{:-US/docs/Web/HTML/Attributes} src}.
* See
{{:-US/docs/Web/HTML/Global_attributes/style}
style}.
* See
{{:-US/docs/Web/HTML/Global_attributes/tabindex}
tabindex}.
* See
{{:-US/docs/Web/HTML/Global_attributes/title}
title}.
* See {{:-US/docs/Web/HTML/Attributes} type}.
* See {{:-US/docs/Web/HTML/Attributes} value}.
* See
{{:-US/docs/Web/HTML/Element/textarea#attr-wrap}
wrap}.
* See {{:-US/docs/Web/HTML/Attributes} width}.
* [class_list list] is similar to {!class_name} but accepts a list of class
names.
* [class_flags list] is similar to {!class_list}, but can conditionally omit
class names depending on the boolean values in [list].
* Additional attribute operations.
* The type for HTML attributes.
* [empty] is an attribute that doesn't get rendered.
* [int name value] is [attr name (string_of_int i)].
* [on cond attr] is [attr] if [cond] is [true] and {!empty} otherwise.
* [on_some option] is [attr] if [option] is [Some attr] and {!empty} if
[option] is [None].
* [on_ok result] is [attr] if [result] is [Ok attr] and {!empty} if [result]
is [Error _].
* [on_mount f] is an HTML attribute that calls [f] with an element this
attribute is added to.
* [empty] is an empty element that will not be rendered.
* [text s] is character data [s]. [s] will be escaped.
* [int n] is [text (string_of_int n)].
* [nbsp] is [text "\u{00A0}"].
* See {{:-US/docs/Web/API/DocumentFragment}
[DocumentFragment]}.
* See {{:-US/docs/Web/HTML/Element/a} a}.
* See {{:-US/docs/Web/HTML/Element/abbr}
abbr}.
* See {{:-US/docs/Web/HTML/Element/address}
address}.
* See {{:-US/docs/Web/HTML/Element/area}
area}.
* See {{:-US/docs/Web/HTML/Element/article}
article}.
* See {{:-US/docs/Web/HTML/Element/aside}
aside}.
* See {{:-US/docs/Web/HTML/Element/audio}
audio}.
* See {{:-US/docs/Web/HTML/Element/b} b}.
* See {{:-US/docs/Web/HTML/Element/base}
base}.
* See {{:-US/docs/Web/HTML/Element/bdo} bdo}.
* See {{:-US/docs/Web/HTML/Element/blockquote}
blockquote}.
* See {{:-US/docs/Web/HTML/Element/br} br}.
* See {{:-US/docs/Web/HTML/Element/button}
button}.
* See {{:-US/docs/Web/HTML/Element/caption}
caption}.
* See {{:-US/docs/Web/HTML/Element/code}
code}.
* See {{:-US/docs/Web/HTML/Element/colgroup}
colgroup}.
* See {{:-US/docs/Web/HTML/Element/command}
command}.
* See {{:-US/docs/Web/HTML/Element/datalist}
datalist}.
* See {{:-US/docs/Web/HTML/Element/dd} dd}.
* See {{:-US/docs/Web/HTML/Element/del} del}.
* See {{:-US/docs/Web/HTML/Element/details}
details}.
* See {{:-US/docs/Web/HTML/Element/dfn} dfn}.
* See {{:-US/docs/Web/HTML/Element/div} div}.
* See {{:-US/docs/Web/HTML/Element/dl} dl}.
* See {{:-US/docs/Web/HTML/Element/em} em}.
* See {{:-US/docs/Web/HTML/Element/embed}
embed}.
* See {{:-US/docs/Web/HTML/Element/fieldset}
fieldset}.
* See {{:-US/docs/Web/HTML/Element/figcaption}
figcaption}.
* See {{:-US/docs/Web/HTML/Element/figure}
figure}.
* See {{:-US/docs/Web/HTML/Element/footer}
footer}.
* See {{:-US/docs/Web/HTML/Element/form}
form}.
* See {{:-US/docs/Web/HTML/Element/h1} h1}.
* See {{:-US/docs/Web/HTML/Element/h2} h2}.
* See {{:-US/docs/Web/HTML/Element/h3} h3}.
* See {{:-US/docs/Web/HTML/Element/h4} h4}.
* See {{:-US/docs/Web/HTML/Element/h5} h5}.
* See {{:-US/docs/Web/HTML/Element/h6} h6}.
* See {{:-US/docs/Web/HTML/Element/header}
header}.
* See {{:-US/docs/Web/HTML/Element/hgroup}
hgroup}.
* See {{:-US/docs/Web/HTML/Element/hr} hr}.
* See {{:-US/docs/Web/HTML/Element/html}
html}.
* See {{:-US/docs/Web/HTML/Element/i} i}.
* See {{:-US/docs/Web/HTML/Element/iframe}
iframe}.
* See {{:-US/docs/Web/HTML/Element/input}
input}.
* See {{:-US/docs/Web/HTML/Element/ins} ins}.
* See {{:-US/docs/Web/HTML/Element/kbd} kbd}.
* See {{:-US/docs/Web/HTML/Element/label}
label}.
* See {{:-US/docs/Web/HTML/Element/legend}
legend}.
* See {{:-US/docs/Web/HTML/Element/li} li}.
* See {{:-US/docs/Web/HTML/Element/main}
main}.
* See {{:-US/docs/Web/HTML/Element/map} map}.
* See {{:-US/docs/Web/HTML/Element/menu}
menu}.
* See {{:-US/docs/Web/HTML/Element/meta}
meta}.
* See {{:-US/docs/Web/HTML/Element/meter}
meter}.
* See {{:-US/docs/Web/HTML/Element/object}
object}.
* See {{:-US/docs/Web/HTML/Element/ol} ol}.
* See {{:-US/docs/Web/HTML/Element/optgroup}
optgroup}.
* See {{:-US/docs/Web/HTML/Element/option}
option}.
* See {{:-US/docs/Web/HTML/Element/p} p}.
* See {{:-US/docs/Web/HTML/Element/param}
param}.
* See {{:-US/docs/Web/HTML/Element/pre} pre}.
* See {{:-US/docs/Web/HTML/Element/progress}
progress}.
* See {{:-US/docs/Web/HTML/Element/q} q}.
* See {{:-US/docs/Web/HTML/Element/rp} rp}.
* See {{:-US/docs/Web/HTML/Element/rt} rt}.
* See {{:-US/docs/Web/HTML/Element/ruby}
ruby}.
* See {{:-US/docs/Web/HTML/Element/s} s}.
* See {{:-US/docs/Web/HTML/Element/samp}
samp}.
* See {{:-US/docs/Web/HTML/Element/section}
section}.
* See {{:-US/docs/Web/HTML/Element/small}
small}.
* See {{:-US/docs/Web/HTML/Element/source}
source}.
* See {{:-US/docs/Web/HTML/Element/sub} sub}.
* See {{:-US/docs/Web/HTML/Element/summary}
summary}.
* See {{:-US/docs/Web/HTML/Element/sup} sup}.
* See {{:-US/docs/Web/HTML/Element/table}
table}.
* See {{:-US/docs/Web/HTML/Element/tbody}
tbody}.
* See {{:-US/docs/Web/HTML/Element/td} td}.
* See {{:-US/docs/Web/HTML/Element/textarea}
textarea}.
* See {{:-US/docs/Web/HTML/Element/tfoot}
tfoot}.
* See {{:-US/docs/Web/HTML/Element/th} th}.
* See {{:-US/docs/Web/HTML/Element/time}
time}.
* See {{:-US/docs/Web/HTML/Element/tr} tr}.
* See {{:-US/docs/Web/HTML/Element/track}
track}.
* See {{:-US/docs/Web/HTML/Element/u} u}.
* See {{:-US/docs/Web/HTML/Element/ul} ul}.
* See {{:-US/docs/Web/HTML/Element/var} var}.
* See {{:-US/docs/Web/HTML/Element/video}
video}.
* Additional element operations.
* Type alias for HTML elements.
* [of_some to_html option] is [to_html x] if [option] is [Some x] and
[empty] otherwise.
* [of_ok to_html result] is [to_html x] if [result] is [Ok x] and [empty]
otherwise. |
open Stdweb
type node = Dom.Node.t
type html
* { 1 : attr Attributes }
See the { { : -US/docs/Web/HTML/Attributes } MDN
HTML attribute reference } .
See the {{:-US/docs/Web/HTML/Attributes} MDN
HTML attribute reference}. *)
type attr
val attr : string -> string -> attr
val accept : string -> attr
val accesskey : string -> attr
val action : string -> attr
val autocomplete : string -> attr
val autofocus : attr
val charset : string -> attr
val checked : attr
val class_name : string -> attr
val cols : int -> attr
val content : string -> attr
val contenteditable : bool -> attr
val defer : attr
val dir : string -> attr
val disabled : attr
val draggable : bool -> attr
val for' : string -> attr
val height : int -> attr
val hidden : attr
val href : string -> attr
val id : string -> attr
val lang : string -> attr
val list : string -> attr
val media : string -> attr
val method' : string -> attr
val name : string -> attr
val placeholder : string -> attr
val rel : string -> attr
val required : attr
val rows : int -> attr
val selected : attr
val spellcheck : string -> attr
val src : string -> attr
val style : (string * string) list -> attr
val tabindex : int -> attr
val title : string -> attr
val type' : string -> attr
val value : string -> attr
val wrap : string -> attr
val width : int -> attr
val class_list : string list -> attr
val class_flags : (string * bool) list -> attr
* { 2 Event attributes }
val on : 'a Dom.Event.kind -> ('a Dom.Event.t -> unit) -> attr
val on_click : (Dom.Event.Mouse.t -> unit) -> attr
val on_input : (Dom.Event.Input.t -> unit) -> attr
val on_keydown : (Dom.Event.Keyboard.t -> unit) -> attr
module Attr : sig
type t = attr
val empty : attr
val bool : string -> bool -> attr
* [ bool name value ] is [ attr name " " ] if [ value ] is [ true ] and { ! empty }
otherwise .
This sets the
{ { : -microsyntaxes.html#boolean-attributes }
boolean attribute } [ n ] to true . The attribute will be omitted if [ b ] is
false .
otherwise.
This sets the
{{:-microsyntaxes.html#boolean-attributes}
boolean attribute} [n] to true. The attribute will be omitted if [b] is
false. *)
val int : string -> int -> attr
val on : bool -> t -> attr
val on_some : attr option -> attr
val on_ok : (attr, 'e) result -> attr
val on_mount : (Dom.Element.t -> unit) -> attr
module Internal : sig
type t = { set : Dom.Element.t -> unit; remove : Dom.Element.t -> unit }
val of_attr : attr -> t
val to_attr : t -> attr
end
end
* { 1 : elem Elements }
val node : string -> attr list -> node list -> node
val elem : string -> attr list -> html list -> html
* [ elem name attrs children ] is an HTML element named [ name ] with attributes
[ attr ] and [ children ] .
[attr] and [children]. *)
val empty : html
val text : string -> html
val int : int -> html
val nbsp : html
val fragment : html list -> html
val a : attr list -> html list -> html
val abbr : attr list -> html list -> html
val address : attr list -> html list -> html
val area : attr list -> html
val article : attr list -> html list -> html
val aside : attr list -> html list -> html
val audio : attr list -> html list -> html
val b : attr list -> html list -> html
val base : attr list -> html
val bdi : attr list -> html list -> html
* See { { : -US/docs/Web/HTML/Element/bdi } bdi } .
val bdo : attr list -> html list -> html
val blockquote : attr list -> html list -> html
val br : attr list -> html
val button : attr list -> html list -> html
val canvas : attr list -> html list -> html
* See { { : canvas } .
canvas}. *)
val caption : attr list -> html list -> html
val cite : attr list -> html list -> html
* See { { : -US/docs/Web/HTML/Element/cite }
cite } .
cite}. *)
val code : attr list -> string -> html
val col : attr list -> html
* See { { : } col } .
val colgroup : attr list -> html list -> html
val command : attr list -> html list -> html
val datalist : attr list -> html list -> html
val dd : attr list -> html list -> html
val del : attr list -> html list -> html
val details : attr list -> html list -> html
val dfn : attr list -> html list -> html
val div : attr list -> html list -> html
val dl : attr list -> html list -> html
val dt : attr list -> html list -> html
* See { { : } .
val em : attr list -> html list -> html
val embed : attr list -> html
val fieldset : attr list -> html list -> html
val figcaption : attr list -> html list -> html
val figure : attr list -> html list -> html
val footer : attr list -> html list -> html
val form : attr list -> html list -> html
val h1 : attr list -> html list -> html
val h2 : attr list -> html list -> html
val h3 : attr list -> html list -> html
val h4 : attr list -> html list -> html
val h5 : attr list -> html list -> html
val h6 : attr list -> html list -> html
val head : attr list -> html list -> html
* See { { : }
head } .
head}. *)
val header : attr list -> html list -> html
val hgroup : attr list -> html list -> html
val hr : attr list -> html
val html : attr list -> html list -> html
val i : attr list -> html list -> html
val iframe : attr list -> html list -> html
val img : attr list -> html
* See { { : .
val input : attr list -> html
val ins : attr list -> html list -> html
val kbd : attr list -> html list -> html
val keygen : attr list -> html list -> html
* See { { : }
keygen } .
keygen}. *)
val label : attr list -> html list -> html
val legend : attr list -> html list -> html
val li : attr list -> html list -> html
val main : attr list -> html list -> html
val map : attr list -> html list -> html
val mark : attr list -> html list -> html
* See { { : -US/docs/Web/HTML/Element/mark }
mark } .
mark}. *)
val menu : attr list -> html list -> html
val meta : attr list -> html
val meter : attr list -> html list -> html
val nav : attr list -> html list -> html
* See { { : .
val object' : attr list -> html list -> html
val ol : attr list -> html list -> html
val optgroup : attr list -> html list -> html
val option : attr list -> html list -> html
val output : attr list -> html list -> html
* See { { : }
output } .
output}. *)
val p : attr list -> html list -> html
val param : attr list -> html
val pre : attr list -> html list -> html
val progress : attr list -> html list -> html
val q : attr list -> html list -> html
val rp : attr list -> html list -> html
val rt : attr list -> html list -> html
val ruby : attr list -> html list -> html
val s : attr list -> html list -> html
val samp : attr list -> html list -> html
val section : attr list -> html list -> html
val select : attr list -> html list -> html
* See { { : -US/docs/Web/HTML/Element/select }
select } .
select}. *)
val small : attr list -> html list -> html
val source : attr list -> html
val span : attr list -> html list -> html
* See { { : -US/docs/Web/HTML/Element/span }
span } .
span}. *)
val strong : attr list -> html list -> html
* See { { : -US/docs/Web/HTML/Element/strong }
strong } .
strong}. *)
val sub : attr list -> html list -> html
val summary : attr list -> html list -> html
val sup : attr list -> html list -> html
val table : attr list -> html list -> html
val tbody : attr list -> html list -> html
val td : attr list -> html list -> html
val textarea : attr list -> html list -> html
val tfoot : attr list -> html list -> html
val th : attr list -> html list -> html
val thead : attr list -> html list -> html
* See { { : }
thead } .
thead}. *)
val time : attr list -> html list -> html
val tr : attr list -> html list -> html
val track : attr list -> html
val u : attr list -> html list -> html
val ul : attr list -> html list -> html
val var : attr list -> html list -> html
val video : attr list -> html list -> html
val wbr : attr list -> html
* See { { : -US/docs/Web/HTML/Element/wbr } wbr } .
module Elem : sig
type t = html
val of_some : ('a -> html) -> 'a option -> html
val of_ok : ('a -> html) -> ('a, 'e) result -> html
module Internal : sig
type t = { mount : Dom.Node.t -> unit; remove : unit -> unit }
val of_html : html -> t
val to_html : t -> html
end
end
* { 2 DOM helpers }
val render : Dom.Element.t -> html -> unit
|
d3516c7fd8bc28a28e4b9b213e481f72920c161e20f504288483ee8560dfad6f | endobson/racket-grpc | status.rkt | #lang racket/base
(provide
ok-status
status-code
status-message
status?)
(struct status (code message) #:transparent)
(define ok-status (status 'ok ""))
| null | https://raw.githubusercontent.com/endobson/racket-grpc/7f3cca4b66f71490236c8db40f0011595f890fa0/status.rkt | racket | #lang racket/base
(provide
ok-status
status-code
status-message
status?)
(struct status (code message) #:transparent)
(define ok-status (status 'ok ""))
|
|
ba1ef4539af021b90a34d44673651bf8003eadaed02dab22f2f47cc8d18c79c9 | racket/rhombus-prototype | syntax-meta-value.rkt | #lang racket/base
(require (for-syntax racket/base
syntax/parse/pre))
(provide (for-syntax Syntax.meta_value))
(begin-for-syntax
(define Syntax.meta_value
(case-lambda
[(id/op)
(define id (extract-operator id/op))
(unless id
(raise-argument-error 'syntax_meta_value "identifier-or-operator?" id/op))
(syntax-local-value id)]
[(id/op fail)
(define id (extract-operator id/op))
(unless id
(raise-argument-error 'syntax_meta_value "identifier-or-operator??" id/op))
(syntax-local-value id (if (and (procedure? fail)
(procedure-arity-includes? fail 0))
fail
(lambda () fail)))]))
(define (extract-operator v)
(cond
[(identifier? v) v]
[(syntax? v)
(syntax-parse v
#:datum-literals (op)
[(op id) #'id]
[_ #f])]
[else #f])))
| null | https://raw.githubusercontent.com/racket/rhombus-prototype/dcf7fb9b002c0957fc0adbf9bd3475c26a8b2c01/rhombus/private/syntax-meta-value.rkt | racket | #lang racket/base
(require (for-syntax racket/base
syntax/parse/pre))
(provide (for-syntax Syntax.meta_value))
(begin-for-syntax
(define Syntax.meta_value
(case-lambda
[(id/op)
(define id (extract-operator id/op))
(unless id
(raise-argument-error 'syntax_meta_value "identifier-or-operator?" id/op))
(syntax-local-value id)]
[(id/op fail)
(define id (extract-operator id/op))
(unless id
(raise-argument-error 'syntax_meta_value "identifier-or-operator??" id/op))
(syntax-local-value id (if (and (procedure? fail)
(procedure-arity-includes? fail 0))
fail
(lambda () fail)))]))
(define (extract-operator v)
(cond
[(identifier? v) v]
[(syntax? v)
(syntax-parse v
#:datum-literals (op)
[(op id) #'id]
[_ #f])]
[else #f])))
|
|
25ea512af3fc69fd549db714b178d3319550e35e2d03b4cc6fba916bf599b444 | GaloisInc/pate | PairGraph.hs | # LANGUAGE DataKinds #
{-# LANGUAGE GADTs #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeApplications #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
# LANGUAGE PatternSynonyms #
module Pate.Verification.PairGraph
( Gas(..)
, initialGas
, PairGraph
, AbstractDomain
, initialDomain
, initialDomainSpec
, initializePairGraph
, chooseWorkItem
, updateDomain
, addReturnVector
, getReturnVectors
, freshDomain
, pairGraphComputeVerdict
, getCurrentDomain
, considerObservableEvent
, considerDesyncEvent
, recordMiscAnalysisError
, reportAnalysisErrors
, TotalityCounterexample(..)
, ObservableCounterexample(..)
, ppProgramDomains
, getOrphanedReturns
, addExtraEdge
, getExtraEdges
, addTerminalNode
, emptyReturnVector
, getEquivCondition
, setEquivCondition
, dropDomain
, markEdge
, addSyncPoint
, getSyncPoint
) where
import Prettyprinter
import Control.Monad (foldM)
import Control.Monad.IO.Class
import qualified Data.Foldable as F
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import Data.Parameterized.Classes
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Word (Word32)
import qualified Lumberjack as LJ
import qualified Data.Parameterized.TraversableF as TF
import qualified What4.Interface as W4
import qualified Data.Macaw.CFG as MM
import qualified Pate.Arch as PA
import qualified Pate.Block as PB
import qualified Pate.Equivalence as PE
import qualified Pate.Event as Event
import Pate.Monad
import Pate.Panic
import qualified Pate.PatchPair as PPa
import qualified Pate.Equivalence.Condition as PEC
import qualified Pate.Equivalence.Error as PEE
import qualified Pate.Verification.Domain as PVD
import qualified Pate.SimState as PS
import Pate.Verification.PairGraph.Node ( GraphNode(..), NodeEntry, NodeReturn, pattern GraphNodeEntry, pattern GraphNodeReturn, rootEntry, nodeBlocks, rootReturn, nodeFuns )
import Pate.Verification.StrongestPosts.CounterExample ( TotalityCounterexample(..), ObservableCounterexample(..) )
import qualified Pate.Verification.AbstractDomain as PAD
import Pate.Verification.AbstractDomain ( AbstractDomain, AbstractDomainSpec )
import Pate.TraceTree
-- | Gas is used to ensure that our fixpoint computation terminates
in a reasonable amount of time . Gas is expended each time
-- we widen an abstract domain along a control flow path
-- from some particular slice. It is intended to only
-- be used along loops or recursive cycles. Right now,
the amount of gas is set to a fairly small number ( 5 )
-- under the assumption that widening will stabalize
-- either quickly or not at all.
newtype Gas = Gas Word32
-- | Temporary constant value for the gas parameter.
-- Should make this configurable.
initialGas :: Gas
initialGas = Gas 5
| The PairGraph is the main datastructure tracking all the
-- information we compute when analysing a program. The analysis we
-- are doing is essentially a (context insensitive) forward dataflow
-- analysis.
--
-- The core assumption we make is that the pair of programs being
-- analysed are nearly the same, and thus have control flow that
-- advances nearly in lockstep. The abstract domains capture
-- information about where the program state differs and we
-- propagate that information forward through the program attempting
-- to compute a fixpoint, which will give us a sound
-- overapproximation of all the differences that may exist between
runs of the two programs .
--
-- As we compute the fixpoint we note cases where we discover a
-- location where we cannot keep the control-flow synchronized, or
-- where we discover some observable difference in the program
-- behavior. These "program desyncrhonization" and "observable
-- difference" occurences are ultimately the information we want to
-- deliver to the user.
--
-- We additionally track situations where we cut off the fixpoint
-- computation early as reportable situations that represent
-- limitations of the analysis; such situations represent potential
-- sources of unsoundness that may cause us to miss desyncronization
-- or observable difference events.
data PairGraph sym arch =
PairGraph
{ -- | The main data structure for the pair graph, which records the current abstract
-- domain value for each reachable graph node.
pairGraphDomains :: !(Map (GraphNode arch) (AbstractDomainSpec sym arch))
-- | This data structure records the amount of remaining "gas" corresponding to each
-- edge of the program graph. Initially, this map is empty. When we traverse an
edge for the first time , we record it 's initial amount of gas , which is later
-- decremented each time we perform an update along this edge in the future.
We stop propagating updates along this edge when the amount of gas reaches zero .
, pairGraphGas :: !(Map (GraphNode arch, GraphNode arch) Gas)
-- | The "worklist" which records the set of nodes that must be revisited.
-- Whenever we propagate a new abstract domain to a node, that node must
-- be revisited, and here we record all such nodes that must be examinied.
--
-- For now, this is just a set and we examine nodes in whatever order is defined
by their ' ' instance . It may make sense at some point to use a more sophisticated
-- mechanism to determine the order in which to visit nodes.
, pairGraphWorklist :: !(Set (GraphNode arch))
-- | The set of blocks where this function may return to. Whenever we see a function
-- call to the given FunPair, we record the program point pair where the function
-- returns to here. This is used to tell us where we need to propagate abstract domain
information when visiting a ReturnNode .
, pairGraphReturnVectors :: !(Map (NodeReturn arch) (Set (NodeEntry arch)))
TODO , I 'm not entirely sure I love this idea of tracking error conditions in this
-- data structure like this. It works for now, but maybe is worth thinking about some more.
-- Because of the monotonicity of the system, results can be reported as soon as they are
-- discovered, so perhaps they should be streamed directly to output somehow.
TODO , maybe this is the right place to include conditional equivalence conditions ?
-- | If we find a counterexample regarding observables in a particular block, record it here.
-- Later, this can be used to generate reports to the user. We also avoid checking for
-- additional counterexamples for the given block if we have already found one.
, pairGraphObservableReports :: !(Map (NodeEntry arch) (ObservableCounterexample sym (MM.ArchAddrWidth arch)))
-- | If we find a counterexample to the exit totality check, record it here. This occurs when
-- the programs have sufficiently-different control flow that they cannot be synchronized, or
-- when the analysis encounters some control-flow construct it doesn't know how to handle.
-- Once we find a desynchronization error for a particular block, we do not look for additional
-- involving that same block.
, pairGraphDesyncReports :: !(Map (NodeEntry arch) (TotalityCounterexample (MM.ArchAddrWidth arch)))
-- | Keep track of the target nodes whenever we run out of gas while trying to reach fixpoint.
-- This can be used to report to the user instances where the analysis may be incomplete.
, pairGraphGasExhausted :: !(Set (GraphNode arch))
-- | Other sorts of analysis errors not captured by the previous categories. These generally
arise from things like incompleteness of the SMT solvers , or other unexpected situations
-- that may impact the soundness of the analysis.
, pairGraphMiscAnalysisErrors :: !(Map (GraphNode arch) [PEE.EquivalenceError])
-- | Extra edges to follow when processing a node. These arise from analysis failures
-- when we can't determine how a function exits, but still want to continue analyzing
-- past all of its call sites.
, pairGraphExtraEdges :: !(Map (NodeEntry arch) (Set (GraphNode arch)))
-- | Avoid adding extra edges to these nodes, as we expect these functions
-- may not actually return on any path (i.e. they end in an abort or exit)
, pairGraphTerminalNodes :: !(Set (NodeReturn arch))
, pairGraphEquivConditions :: !(Map (GraphNode arch) (PEC.EquivConditionSpec sym arch))
-- | Any edges that have been followed at any point (which may later become infeasible
-- due to further analysis)
, pairGraphEdges :: !(Map (GraphNode arch) (Set (GraphNode arch)))
-- | Reverse map of the above (from descendants to ancestors)
, pairGraphBackEdges :: !(Map (GraphNode arch) (Set (GraphNode arch)))
-- | Mapping from singleton nodes to their "synchronization" point, representing
the case where two independent program analysis steps have occurred and now
-- their control-flows have re-synchronized
, pairGraphSyncPoint :: !(Map (NodeReturn arch) (Set (NodeReturn arch)))
}
ppProgramDomains ::
forall sym arch a.
( PA.ValidArch arch
, W4.IsSymExprBuilder sym
, ShowF (MM.ArchReg arch)
) =>
(W4.Pred sym -> Doc a) ->
PairGraph sym arch ->
Doc a
ppProgramDomains ppPred gr =
vcat
[ vcat [ pretty pPair
, PS.viewSpecBody adSpec $ \ad -> PAD.ppAbstractDomain ppPred ad
]
| (pPair, adSpec) <- Map.toList (pairGraphDomains gr)
]
-- | A totally empty initial pair graph.
emptyPairGraph :: PairGraph sym arch
emptyPairGraph =
PairGraph
{ pairGraphDomains = mempty
, pairGraphGas = mempty
, pairGraphWorklist = mempty
, pairGraphReturnVectors = mempty
, pairGraphObservableReports = mempty
, pairGraphDesyncReports = mempty
, pairGraphGasExhausted = mempty
, pairGraphMiscAnalysisErrors = mempty
, pairGraphExtraEdges = mempty
, pairGraphTerminalNodes = mempty
, pairGraphEquivConditions = mempty
, pairGraphEdges = mempty
, pairGraphBackEdges = mempty
, pairGraphSyncPoint = mempty
}
-- | Given a pair graph and a function pair, return the set of all
-- the sites we have encountered so far where this function may return to.
getReturnVectors ::
PairGraph sym arch ->
NodeReturn arch ->
Set (NodeEntry arch)
getReturnVectors gr fPair = fromMaybe mempty (Map.lookup fPair (pairGraphReturnVectors gr))
-- | Look up the current abstract domain for the given graph node.
getCurrentDomain ::
PairGraph sym arch ->
GraphNode arch ->
Maybe (AbstractDomainSpec sym arch)
getCurrentDomain pg nd = Map.lookup nd (pairGraphDomains pg)
getEdgesFrom ::
PairGraph sym arch ->
GraphNode arch ->
Set (GraphNode arch)
getEdgesFrom pg nd = case Map.lookup nd (pairGraphEdges pg) of
Just s -> s
Nothing -> Set.empty
getBackEdgesFrom ::
PairGraph sym arch ->
GraphNode arch ->
Set (GraphNode arch)
getBackEdgesFrom pg nd = case Map.lookup nd (pairGraphBackEdges pg) of
Just s -> s
Nothing -> Set.empty
-- | Delete the abstract domain for the given node, following
-- any reachable edges and discarding those domains as well
-- This is necessary if a domain is "narrowed": i.e. it moves
-- from assuming fewer equalities to assuming more equalities.
Marks any ancestors as requiring re - analysis
dropDomain ::
GraphNode arch ->
PairGraph sym arch ->
PairGraph sym arch
dropDomain nd pg = case getCurrentDomain pg nd of
Just{}->
let
-- clear this domain and all descendant domains
pg' = case Set.null (getBackEdgesFrom pg nd) of
-- don't drop the domain for a toplevel entrypoint, but mark it for
-- re-analysis
True -> pg { pairGraphWorklist = Set.insert nd (pairGraphWorklist pg) }
False -> pg { pairGraphDomains = Map.delete nd (pairGraphDomains pg), pairGraphWorklist = Set.delete nd (pairGraphWorklist pg) }
pg'' = Set.foldl' (\pg_ nd' -> dropDomain nd' pg_) pg' (getEdgesFrom pg nd)
-- mark all ancestors as requiring re-processing
in addAncestors Set.empty pg'' nd
Nothing -> pg
where
addAncestors :: Set (GraphNode arch) -> PairGraph sym arch -> GraphNode arch -> PairGraph sym arch
addAncestors considered pg_ nd_ = case Set.member nd_ considered of
True -> pg_
False -> case addToWorkList nd_ pg_ of
Just pg' -> pg'
-- if this node has no defined domain (i.e it was dropped as part of the previous
-- step) then we consider further ancestors
Nothing -> Set.foldl' (addAncestors (Set.insert nd_ considered)) pg_ (getBackEdgesFrom pg_ nd_)
getEquivCondition ::
PairGraph sym arch ->
GraphNode arch ->
Maybe (PEC.EquivConditionSpec sym arch)
getEquivCondition pg nd = Map.lookup nd (pairGraphEquivConditions pg)
setEquivCondition ::
GraphNode arch ->
PEC.EquivConditionSpec sym arch ->
PairGraph sym arch ->
PairGraph sym arch
setEquivCondition nd cond pg = pg { pairGraphEquivConditions = Map.insert nd cond (pairGraphEquivConditions pg) }
-- | If an observable counterexample has not already been found
-- for this block pair, run the given action to check if there
-- currently is one.
considerObservableEvent :: Monad m =>
PairGraph sym arch ->
NodeEntry arch ->
(m (Maybe (ObservableCounterexample sym (MM.ArchAddrWidth arch)), PairGraph sym arch)) ->
m (PairGraph sym arch)
considerObservableEvent gr bPair action =
case Map.lookup bPair (pairGraphObservableReports gr) of
-- we have already found observable event differences at this location, so skip the check
Just _ -> return gr
Nothing ->
do (mcex, gr') <- action
case mcex of
Nothing -> return gr'
Just cex -> return gr'{ pairGraphObservableReports = Map.insert bPair cex (pairGraphObservableReports gr) }
-- | If a program desync has not already be found
-- for this block pair, run the given action to check if there
-- currently is one.
considerDesyncEvent :: Monad m =>
IsTreeBuilder '(sym, arch) PEE.EquivalenceError m =>
PA.ValidArch arch =>
PairGraph sym arch ->
NodeEntry arch ->
(m (Maybe (TotalityCounterexample (MM.ArchAddrWidth arch)), PairGraph sym arch)) ->
m (PairGraph sym arch)
considerDesyncEvent gr bPair action =
case Map.lookup bPair (pairGraphDesyncReports gr) of
-- we have already found observable event differences at this location, so skip the check
Just cex -> do
withTracing @"totalityce" cex $
emitTraceWarning $ PEE.equivalenceError $ PEE.NonTotalBlockExits (nodeBlocks bPair)
return gr
Nothing ->
do (mcex, gr') <- action
case mcex of
Nothing -> return gr'
Just cex -> do
withTracing @"totalityce" cex $
emitTraceWarning $ PEE.equivalenceError $ PEE.NonTotalBlockExits (nodeBlocks bPair)
return gr'{ pairGraphDesyncReports = Map.insert bPair cex (pairGraphDesyncReports gr) }
| Record an error that occured during analysis that does n't fall into one of the
-- other, more structured, types of errors.
recordMiscAnalysisError ::
PairGraph sym arch ->
GraphNode arch ->
PEE.EquivalenceError ->
PairGraph sym arch
recordMiscAnalysisError gr nd er =
let m = Map.alter f nd (pairGraphMiscAnalysisErrors gr)
f Nothing = Just [er]
f (Just s) = Just (er:s)
in gr{ pairGraphMiscAnalysisErrors = m }
-- | TODO, Right now, this just prints error reports to stdout.
-- We should decide how and to what extent this should connect
-- to the `emitEvent` infrastructure.
reportAnalysisErrors
:: (PA.ValidArch arch, W4.IsExprBuilder sym, MonadIO m)
=> LJ.LogAction IO (Event.Event arch)
-> PairGraph sym arch
-> m ()
reportAnalysisErrors logAction gr =
do mapM_ reportObservables (Map.toList (pairGraphObservableReports gr))
mapM_ reportDesync (Map.toList (pairGraphDesyncReports gr))
mapM_ reportGasExhausted (Set.toList (pairGraphGasExhausted gr))
mapM_ reportMiscError (Map.toList (pairGraphMiscAnalysisErrors gr))
where
reportObservables (pPair, ocex) =
liftIO $ LJ.writeLog logAction (Event.StrongestPostObservable pPair ocex)
reportDesync (pPair, tcex) =
liftIO $ LJ.writeLog logAction (Event.StrongestPostDesync pPair tcex)
reportGasExhausted pPair =
liftIO $ LJ.writeLog logAction (Event.GasExhausted pPair)
reportMiscError (pPair, msgs) =
liftIO $ F.forM_ msgs $ \msg -> do
LJ.writeLog logAction (Event.StrongestPostMiscError pPair msg)
initialDomain :: EquivM sym arch (PAD.AbstractDomain sym arch v)
initialDomain = withSym $ \sym ->
PAD.AbstractDomain
<$> pure (PVD.universalDomain sym)
<*> (PPa.forBins $ \_ -> return $ PAD.emptyDomainVals)
<*> (PPa.forBins $ \_ -> PAD.emptyEvents sym)
initialDomainSpec ::
forall sym arch.
GraphNode arch ->
EquivM sym arch (PAD.AbstractDomainSpec sym arch)
initialDomainSpec (GraphNodeEntry blocks) = withTracing @"function_name" "initialDomainSpec" $
withFreshVars blocks $ \_vars -> do
dom <- initialDomain
return (mempty, dom)
initialDomainSpec (GraphNodeReturn fPair) = withTracing @"function_name" "initialDomainSpec" $ do
let blocks = TF.fmapF PB.functionEntryToConcreteBlock fPair
withFreshVars blocks $ \_vars -> do
dom <- initialDomain
return (mempty, dom)
-- | Given a list of top-level function entry points to analyse,
-- initialize a pair graph with default abstract domains for those
-- entry points and add them to the work list.
initializePairGraph :: forall sym arch.
[PB.FunPair arch] ->
EquivM sym arch (PairGraph sym arch)
initializePairGraph pPairs = foldM (\x y -> initPair x y) emptyPairGraph pPairs
where
initPair :: PairGraph sym arch -> PB.FunPair arch -> EquivM sym arch (PairGraph sym arch)
initPair gr fnPair =
do let bPair = TF.fmapF PB.functionEntryToConcreteBlock fnPair
withPair bPair $ do
-- initial state of the pair graph: choose the universal domain that equates as much as possible
let node = GraphNode (rootEntry bPair)
idom <- initialDomainSpec node
-- when the program is initialized, we assume no memory regions are allocated,
-- and therefore we pick a concrete initial region that doesn't overlap with
-- the global or stack regions.
--
-- in the event that this node is encountered again (i.e. the analysis entry
-- point is some intermediate program point), then this value domain will simply
-- be overridden as a result of widening
rootDom <- PS.forSpec idom $ \_ idom' -> do
vals' <- PPa.forBins $ \bin -> do
vals <- PPa.get bin (PAD.absDomVals idom')
FIXME : compute this from the global and stack regions
return $ vals { PAD.absMaxRegion = PAD.AbsIntConstant 3 }
return $ idom' { PAD.absDomVals = vals' }
let gr1 = freshDomain gr node rootDom
return $ emptyReturnVector gr1 (rootReturn fnPair)
-- | Given a pair graph, chose the next node in the graph to visit
-- from the work list, updating the necessary bookeeping. If the
-- work list is empty, return Nothing, indicating that we are done.
chooseWorkItem ::
PA.ValidArch arch =>
PairGraph sym arch ->
Maybe (PairGraph sym arch, GraphNode arch, AbstractDomainSpec sym arch)
chooseWorkItem gr =
-- choose the smallest pair from the worklist. This is a pretty brain-dead
-- heuristic. Perhaps we should do something more clever.
case Set.minView (pairGraphWorklist gr) of
Nothing -> Nothing
Just (nd, wl) -> case Map.lookup nd (pairGraphDomains gr) of
Nothing -> panic Verifier "choseoWorkItem" ["Could not find domain corresponding to block pair", show nd]
Just d -> Just (gr{ pairGraphWorklist = wl }, nd, d)
-- | Update the abstract domain for the target graph node,
-- decreasing the gas parameter as necessary.
If we have run out of Gas , return a ` Left ` value .
-- The domain will be updated, but the graph node will
-- not be added back to the work list.
-- Return a `Right` value if the update succeeded.
updateDomain ::
PairGraph sym arch {- ^ pair graph to update -} ->
GraphNode arch {- ^ point pair we are jumping from -} ->
GraphNode arch {- ^ point pair we are jumping to -} ->
AbstractDomainSpec sym arch {- ^ new domain value to insert -} ->
Either (PairGraph sym arch) (PairGraph sym arch)
updateDomain gr pFrom pTo d
| g > 0 = Right $ markEdge pFrom pTo $ gr
{ pairGraphDomains = Map.insert pTo d (pairGraphDomains gr)
, pairGraphGas = Map.insert (pFrom,pTo) (Gas (g-1)) (pairGraphGas gr)
, pairGraphWorklist = Set.insert pTo (pairGraphWorklist gr)
, pairGraphEdges = Map.insertWith Set.union pFrom (Set.singleton pTo) (pairGraphEdges gr)
, pairGraphBackEdges = Map.insertWith Set.union pTo (Set.singleton pFrom) (pairGraphBackEdges gr)
}
| otherwise =
Left $ markEdge pFrom pTo $ gr
{ pairGraphDomains = Map.insert pTo d (pairGraphDomains gr)
}
where
Lookup the amount of remaining gas . Initialize to a fresh value
-- if it is not in the map
Gas g = fromMaybe initialGas (Map.lookup (pFrom,pTo) (pairGraphGas gr))
emptyReturnVector ::
PairGraph sym arch ->
NodeReturn arch ->
PairGraph sym arch
emptyReturnVector gr ret = gr{ pairGraphReturnVectors = rvs }
where
rvs = Map.alter f ret (pairGraphReturnVectors gr)
f Nothing = Just (Set.empty)
f (Just s) = Just s
-- | When we encounter a function call, record where the function
-- returns to so that we can correctly propagate abstract domain
-- information from function returns to their call sites.
addReturnVector ::
PairGraph sym arch ->
NodeReturn arch {- ^ The function being called -} ->
NodeEntry arch {- ^ The program point where it returns to -} ->
PairGraph sym arch
addReturnVector gr funPair retPair =
-- If the domain graph already has a node corresponding to the
-- return point of the function we are calling, make sure
-- we explore the return site by adding the function return node
-- to the work list. This ensures that we explore the code following
-- the return even if the dataflow doesn't force a reexamination of
-- the body of the called function.
case Map.lookup (ReturnNode funPair) (pairGraphDomains gr) of
No node for the return from this function . Either this is the first
-- time we have found a call to this function, or previous explorations
-- never have not reached a return. There is nothing we need to do
-- other than register retPair as a return vector.
Nothing -> gr{ pairGraphReturnVectors = rvs }
We know there is at least one control - flow path through the function
-- we are calling that returns. We need to ensure that we propagate
-- information from the function return to retPair. The easiest way
-- to do this is to add the return node corresponding to funPair to
-- the worklist.
Just _ ->
gr{ pairGraphReturnVectors = rvs
, pairGraphWorklist = wl
}
where
Remember that is one of the places that funPair
-- can return to
rvs = Map.alter f funPair (pairGraphReturnVectors gr)
f Nothing = Just (Set.singleton retPair)
f (Just s) = Just (Set.insert retPair s)
wl = Set.insert (ReturnNode funPair) (pairGraphWorklist gr)
getSyncPoint ::
PairGraph sym arch ->
NodeReturn arch ->
Maybe (Set (NodeReturn arch))
getSyncPoint gr nd = Map.lookup nd (pairGraphSyncPoint gr)
addSyncPoint ::
PairGraph sym arch ->
NodeReturn arch {- ^ The singleton node, just before synchronization -} ->
NodeReturn arch {- ^ The pair node, after synchronization -} ->
PairGraph sym arch
addSyncPoint gr from to
| PPa.PatchPairSingle{} <- nodeFuns from
, PPa.PatchPair{} <- nodeFuns to =
gr { pairGraphSyncPoint = Map.insertWith Set.union from (Set.singleton to) (pairGraphSyncPoint gr) }
addSyncPoint _ _ _ = error "addSyncPoint: unexpected PatchPair shape"
-- | Add a node back to the worklist to be re-analyzed if there is
-- an existing abstract domain for it. Otherwise return Nothing.
addToWorkList ::
GraphNode arch ->
PairGraph sym arch ->
Maybe (PairGraph sym arch)
addToWorkList nd gr = case getCurrentDomain gr nd of
Just{} -> Just $ gr { pairGraphWorklist = Set.insert nd (pairGraphWorklist gr) }
Nothing -> Nothing
-- | Add an initial abstract domain value to a graph node, and
-- record it in the worklist to be visited.
freshDomain ::
PairGraph sym arch {- ^ pair graph to update -} ->
GraphNode arch {- ^ point pair we are jumping to -} ->
AbstractDomainSpec sym arch {- ^ new domain value to insert -} ->
PairGraph sym arch
freshDomain gr pTo d =
gr{ pairGraphDomains = Map.insert pTo d (pairGraphDomains gr)
, pairGraphWorklist = Set.insert pTo (pairGraphWorklist gr)
}
markEdge ::
GraphNode arch {- ^ from -} ->
GraphNode arch {- ^ to -} ->
PairGraph sym arch ->
PairGraph sym arch
markEdge from to gr =
gr { pairGraphEdges = Map.insertWith Set.union from (Set.singleton to) (pairGraphEdges gr)
, pairGraphBackEdges = Map.insertWith Set.union to (Set.singleton from) (pairGraphBackEdges gr)}
addExtraEdge ::
PairGraph sym arch ->
NodeEntry arch ->
GraphNode arch ->
PairGraph sym arch
addExtraEdge gr from to = markEdge (GraphNode from) to $
gr { pairGraphExtraEdges = Map.insertWith Set.union from (Set.singleton to) ( pairGraphExtraEdges gr)
}
getExtraEdges ::
PairGraph sym arch ->
NodeEntry arch ->
Set (GraphNode arch)
getExtraEdges gr e = case Map.lookup e (pairGraphExtraEdges gr) of
Just es -> es
Nothing -> Set.empty
-- | Mark a return node for a function as terminal, indicating that it
-- might not have any valid return paths.
-- A non-terminal function with no return paths is considered an analysis error, since
-- we can't continue analyzing past any of its call sites.
addTerminalNode ::
PairGraph sym arch ->
NodeReturn arch ->
PairGraph sym arch
addTerminalNode gr nd = gr { pairGraphTerminalNodes = Set.insert nd (pairGraphTerminalNodes gr) }
-- | Return the set of "orphaned" nodes in the current graph. An orphaned
-- node is a return node for a function where no return path was found
-- (i.e. we have a set of call sites for the function, but no post-equivalence
-- domain). This usually indicates some sort of analysis failure.
-- We exclude any terminal nodes here, since it is expected that a terminal
-- node might not have any return paths.
getOrphanedReturns ::
PairGraph sym arch ->
Set (NodeReturn arch)
getOrphanedReturns gr = do
let rets = (Map.keysSet (pairGraphReturnVectors gr)) Set.\\ (pairGraphTerminalNodes gr)
Set.filter (\ret -> not (Map.member (ReturnNode ret) (pairGraphDomains gr))) rets
-- | After computing the dataflow fixpoint, examine the generated
-- error reports to determine an overall verdict for the programs.
pairGraphComputeVerdict ::
PairGraph sym arch ->
EquivM sym arch PE.EquivalenceStatus
pairGraphComputeVerdict gr =
if Map.null (pairGraphObservableReports gr) &&
Map.null (pairGraphDesyncReports gr) &&
Set.null (pairGraphGasExhausted gr) then
return PE.Equivalent
else
return PE.Inequivalent
| null | https://raw.githubusercontent.com/GaloisInc/pate/a48c447156d95686c308a6d5ec696464120e0970/src/Pate/Verification/PairGraph.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE MultiWayIf #
# LANGUAGE RankNTypes #
| Gas is used to ensure that our fixpoint computation terminates
we widen an abstract domain along a control flow path
from some particular slice. It is intended to only
be used along loops or recursive cycles. Right now,
under the assumption that widening will stabalize
either quickly or not at all.
| Temporary constant value for the gas parameter.
Should make this configurable.
information we compute when analysing a program. The analysis we
are doing is essentially a (context insensitive) forward dataflow
analysis.
The core assumption we make is that the pair of programs being
analysed are nearly the same, and thus have control flow that
advances nearly in lockstep. The abstract domains capture
information about where the program state differs and we
propagate that information forward through the program attempting
to compute a fixpoint, which will give us a sound
overapproximation of all the differences that may exist between
As we compute the fixpoint we note cases where we discover a
location where we cannot keep the control-flow synchronized, or
where we discover some observable difference in the program
behavior. These "program desyncrhonization" and "observable
difference" occurences are ultimately the information we want to
deliver to the user.
We additionally track situations where we cut off the fixpoint
computation early as reportable situations that represent
limitations of the analysis; such situations represent potential
sources of unsoundness that may cause us to miss desyncronization
or observable difference events.
| The main data structure for the pair graph, which records the current abstract
domain value for each reachable graph node.
| This data structure records the amount of remaining "gas" corresponding to each
edge of the program graph. Initially, this map is empty. When we traverse an
decremented each time we perform an update along this edge in the future.
| The "worklist" which records the set of nodes that must be revisited.
Whenever we propagate a new abstract domain to a node, that node must
be revisited, and here we record all such nodes that must be examinied.
For now, this is just a set and we examine nodes in whatever order is defined
mechanism to determine the order in which to visit nodes.
| The set of blocks where this function may return to. Whenever we see a function
call to the given FunPair, we record the program point pair where the function
returns to here. This is used to tell us where we need to propagate abstract domain
data structure like this. It works for now, but maybe is worth thinking about some more.
Because of the monotonicity of the system, results can be reported as soon as they are
discovered, so perhaps they should be streamed directly to output somehow.
| If we find a counterexample regarding observables in a particular block, record it here.
Later, this can be used to generate reports to the user. We also avoid checking for
additional counterexamples for the given block if we have already found one.
| If we find a counterexample to the exit totality check, record it here. This occurs when
the programs have sufficiently-different control flow that they cannot be synchronized, or
when the analysis encounters some control-flow construct it doesn't know how to handle.
Once we find a desynchronization error for a particular block, we do not look for additional
involving that same block.
| Keep track of the target nodes whenever we run out of gas while trying to reach fixpoint.
This can be used to report to the user instances where the analysis may be incomplete.
| Other sorts of analysis errors not captured by the previous categories. These generally
that may impact the soundness of the analysis.
| Extra edges to follow when processing a node. These arise from analysis failures
when we can't determine how a function exits, but still want to continue analyzing
past all of its call sites.
| Avoid adding extra edges to these nodes, as we expect these functions
may not actually return on any path (i.e. they end in an abort or exit)
| Any edges that have been followed at any point (which may later become infeasible
due to further analysis)
| Reverse map of the above (from descendants to ancestors)
| Mapping from singleton nodes to their "synchronization" point, representing
their control-flows have re-synchronized
| A totally empty initial pair graph.
| Given a pair graph and a function pair, return the set of all
the sites we have encountered so far where this function may return to.
| Look up the current abstract domain for the given graph node.
| Delete the abstract domain for the given node, following
any reachable edges and discarding those domains as well
This is necessary if a domain is "narrowed": i.e. it moves
from assuming fewer equalities to assuming more equalities.
clear this domain and all descendant domains
don't drop the domain for a toplevel entrypoint, but mark it for
re-analysis
mark all ancestors as requiring re-processing
if this node has no defined domain (i.e it was dropped as part of the previous
step) then we consider further ancestors
| If an observable counterexample has not already been found
for this block pair, run the given action to check if there
currently is one.
we have already found observable event differences at this location, so skip the check
| If a program desync has not already be found
for this block pair, run the given action to check if there
currently is one.
we have already found observable event differences at this location, so skip the check
other, more structured, types of errors.
| TODO, Right now, this just prints error reports to stdout.
We should decide how and to what extent this should connect
to the `emitEvent` infrastructure.
| Given a list of top-level function entry points to analyse,
initialize a pair graph with default abstract domains for those
entry points and add them to the work list.
initial state of the pair graph: choose the universal domain that equates as much as possible
when the program is initialized, we assume no memory regions are allocated,
and therefore we pick a concrete initial region that doesn't overlap with
the global or stack regions.
in the event that this node is encountered again (i.e. the analysis entry
point is some intermediate program point), then this value domain will simply
be overridden as a result of widening
| Given a pair graph, chose the next node in the graph to visit
from the work list, updating the necessary bookeeping. If the
work list is empty, return Nothing, indicating that we are done.
choose the smallest pair from the worklist. This is a pretty brain-dead
heuristic. Perhaps we should do something more clever.
| Update the abstract domain for the target graph node,
decreasing the gas parameter as necessary.
The domain will be updated, but the graph node will
not be added back to the work list.
Return a `Right` value if the update succeeded.
^ pair graph to update
^ point pair we are jumping from
^ point pair we are jumping to
^ new domain value to insert
if it is not in the map
| When we encounter a function call, record where the function
returns to so that we can correctly propagate abstract domain
information from function returns to their call sites.
^ The function being called
^ The program point where it returns to
If the domain graph already has a node corresponding to the
return point of the function we are calling, make sure
we explore the return site by adding the function return node
to the work list. This ensures that we explore the code following
the return even if the dataflow doesn't force a reexamination of
the body of the called function.
time we have found a call to this function, or previous explorations
never have not reached a return. There is nothing we need to do
other than register retPair as a return vector.
we are calling that returns. We need to ensure that we propagate
information from the function return to retPair. The easiest way
to do this is to add the return node corresponding to funPair to
the worklist.
can return to
^ The singleton node, just before synchronization
^ The pair node, after synchronization
| Add a node back to the worklist to be re-analyzed if there is
an existing abstract domain for it. Otherwise return Nothing.
| Add an initial abstract domain value to a graph node, and
record it in the worklist to be visited.
^ pair graph to update
^ point pair we are jumping to
^ new domain value to insert
^ from
^ to
| Mark a return node for a function as terminal, indicating that it
might not have any valid return paths.
A non-terminal function with no return paths is considered an analysis error, since
we can't continue analyzing past any of its call sites.
| Return the set of "orphaned" nodes in the current graph. An orphaned
node is a return node for a function where no return path was found
(i.e. we have a set of call sites for the function, but no post-equivalence
domain). This usually indicates some sort of analysis failure.
We exclude any terminal nodes here, since it is expected that a terminal
node might not have any return paths.
| After computing the dataflow fixpoint, examine the generated
error reports to determine an overall verdict for the programs. | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeApplications #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
# LANGUAGE PatternSynonyms #
module Pate.Verification.PairGraph
( Gas(..)
, initialGas
, PairGraph
, AbstractDomain
, initialDomain
, initialDomainSpec
, initializePairGraph
, chooseWorkItem
, updateDomain
, addReturnVector
, getReturnVectors
, freshDomain
, pairGraphComputeVerdict
, getCurrentDomain
, considerObservableEvent
, considerDesyncEvent
, recordMiscAnalysisError
, reportAnalysisErrors
, TotalityCounterexample(..)
, ObservableCounterexample(..)
, ppProgramDomains
, getOrphanedReturns
, addExtraEdge
, getExtraEdges
, addTerminalNode
, emptyReturnVector
, getEquivCondition
, setEquivCondition
, dropDomain
, markEdge
, addSyncPoint
, getSyncPoint
) where
import Prettyprinter
import Control.Monad (foldM)
import Control.Monad.IO.Class
import qualified Data.Foldable as F
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import Data.Parameterized.Classes
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Word (Word32)
import qualified Lumberjack as LJ
import qualified Data.Parameterized.TraversableF as TF
import qualified What4.Interface as W4
import qualified Data.Macaw.CFG as MM
import qualified Pate.Arch as PA
import qualified Pate.Block as PB
import qualified Pate.Equivalence as PE
import qualified Pate.Event as Event
import Pate.Monad
import Pate.Panic
import qualified Pate.PatchPair as PPa
import qualified Pate.Equivalence.Condition as PEC
import qualified Pate.Equivalence.Error as PEE
import qualified Pate.Verification.Domain as PVD
import qualified Pate.SimState as PS
import Pate.Verification.PairGraph.Node ( GraphNode(..), NodeEntry, NodeReturn, pattern GraphNodeEntry, pattern GraphNodeReturn, rootEntry, nodeBlocks, rootReturn, nodeFuns )
import Pate.Verification.StrongestPosts.CounterExample ( TotalityCounterexample(..), ObservableCounterexample(..) )
import qualified Pate.Verification.AbstractDomain as PAD
import Pate.Verification.AbstractDomain ( AbstractDomain, AbstractDomainSpec )
import Pate.TraceTree
in a reasonable amount of time . Gas is expended each time
the amount of gas is set to a fairly small number ( 5 )
newtype Gas = Gas Word32
initialGas :: Gas
initialGas = Gas 5
| The PairGraph is the main datastructure tracking all the
runs of the two programs .
data PairGraph sym arch =
PairGraph
pairGraphDomains :: !(Map (GraphNode arch) (AbstractDomainSpec sym arch))
edge for the first time , we record it 's initial amount of gas , which is later
We stop propagating updates along this edge when the amount of gas reaches zero .
, pairGraphGas :: !(Map (GraphNode arch, GraphNode arch) Gas)
by their ' ' instance . It may make sense at some point to use a more sophisticated
, pairGraphWorklist :: !(Set (GraphNode arch))
information when visiting a ReturnNode .
, pairGraphReturnVectors :: !(Map (NodeReturn arch) (Set (NodeEntry arch)))
TODO , I 'm not entirely sure I love this idea of tracking error conditions in this
TODO , maybe this is the right place to include conditional equivalence conditions ?
, pairGraphObservableReports :: !(Map (NodeEntry arch) (ObservableCounterexample sym (MM.ArchAddrWidth arch)))
, pairGraphDesyncReports :: !(Map (NodeEntry arch) (TotalityCounterexample (MM.ArchAddrWidth arch)))
, pairGraphGasExhausted :: !(Set (GraphNode arch))
arise from things like incompleteness of the SMT solvers , or other unexpected situations
, pairGraphMiscAnalysisErrors :: !(Map (GraphNode arch) [PEE.EquivalenceError])
, pairGraphExtraEdges :: !(Map (NodeEntry arch) (Set (GraphNode arch)))
, pairGraphTerminalNodes :: !(Set (NodeReturn arch))
, pairGraphEquivConditions :: !(Map (GraphNode arch) (PEC.EquivConditionSpec sym arch))
, pairGraphEdges :: !(Map (GraphNode arch) (Set (GraphNode arch)))
, pairGraphBackEdges :: !(Map (GraphNode arch) (Set (GraphNode arch)))
the case where two independent program analysis steps have occurred and now
, pairGraphSyncPoint :: !(Map (NodeReturn arch) (Set (NodeReturn arch)))
}
ppProgramDomains ::
forall sym arch a.
( PA.ValidArch arch
, W4.IsSymExprBuilder sym
, ShowF (MM.ArchReg arch)
) =>
(W4.Pred sym -> Doc a) ->
PairGraph sym arch ->
Doc a
ppProgramDomains ppPred gr =
vcat
[ vcat [ pretty pPair
, PS.viewSpecBody adSpec $ \ad -> PAD.ppAbstractDomain ppPred ad
]
| (pPair, adSpec) <- Map.toList (pairGraphDomains gr)
]
emptyPairGraph :: PairGraph sym arch
emptyPairGraph =
PairGraph
{ pairGraphDomains = mempty
, pairGraphGas = mempty
, pairGraphWorklist = mempty
, pairGraphReturnVectors = mempty
, pairGraphObservableReports = mempty
, pairGraphDesyncReports = mempty
, pairGraphGasExhausted = mempty
, pairGraphMiscAnalysisErrors = mempty
, pairGraphExtraEdges = mempty
, pairGraphTerminalNodes = mempty
, pairGraphEquivConditions = mempty
, pairGraphEdges = mempty
, pairGraphBackEdges = mempty
, pairGraphSyncPoint = mempty
}
getReturnVectors ::
PairGraph sym arch ->
NodeReturn arch ->
Set (NodeEntry arch)
getReturnVectors gr fPair = fromMaybe mempty (Map.lookup fPair (pairGraphReturnVectors gr))
getCurrentDomain ::
PairGraph sym arch ->
GraphNode arch ->
Maybe (AbstractDomainSpec sym arch)
getCurrentDomain pg nd = Map.lookup nd (pairGraphDomains pg)
getEdgesFrom ::
PairGraph sym arch ->
GraphNode arch ->
Set (GraphNode arch)
getEdgesFrom pg nd = case Map.lookup nd (pairGraphEdges pg) of
Just s -> s
Nothing -> Set.empty
getBackEdgesFrom ::
PairGraph sym arch ->
GraphNode arch ->
Set (GraphNode arch)
getBackEdgesFrom pg nd = case Map.lookup nd (pairGraphBackEdges pg) of
Just s -> s
Nothing -> Set.empty
Marks any ancestors as requiring re - analysis
dropDomain ::
GraphNode arch ->
PairGraph sym arch ->
PairGraph sym arch
dropDomain nd pg = case getCurrentDomain pg nd of
Just{}->
let
pg' = case Set.null (getBackEdgesFrom pg nd) of
True -> pg { pairGraphWorklist = Set.insert nd (pairGraphWorklist pg) }
False -> pg { pairGraphDomains = Map.delete nd (pairGraphDomains pg), pairGraphWorklist = Set.delete nd (pairGraphWorklist pg) }
pg'' = Set.foldl' (\pg_ nd' -> dropDomain nd' pg_) pg' (getEdgesFrom pg nd)
in addAncestors Set.empty pg'' nd
Nothing -> pg
where
addAncestors :: Set (GraphNode arch) -> PairGraph sym arch -> GraphNode arch -> PairGraph sym arch
addAncestors considered pg_ nd_ = case Set.member nd_ considered of
True -> pg_
False -> case addToWorkList nd_ pg_ of
Just pg' -> pg'
Nothing -> Set.foldl' (addAncestors (Set.insert nd_ considered)) pg_ (getBackEdgesFrom pg_ nd_)
getEquivCondition ::
PairGraph sym arch ->
GraphNode arch ->
Maybe (PEC.EquivConditionSpec sym arch)
getEquivCondition pg nd = Map.lookup nd (pairGraphEquivConditions pg)
setEquivCondition ::
GraphNode arch ->
PEC.EquivConditionSpec sym arch ->
PairGraph sym arch ->
PairGraph sym arch
setEquivCondition nd cond pg = pg { pairGraphEquivConditions = Map.insert nd cond (pairGraphEquivConditions pg) }
considerObservableEvent :: Monad m =>
PairGraph sym arch ->
NodeEntry arch ->
(m (Maybe (ObservableCounterexample sym (MM.ArchAddrWidth arch)), PairGraph sym arch)) ->
m (PairGraph sym arch)
considerObservableEvent gr bPair action =
case Map.lookup bPair (pairGraphObservableReports gr) of
Just _ -> return gr
Nothing ->
do (mcex, gr') <- action
case mcex of
Nothing -> return gr'
Just cex -> return gr'{ pairGraphObservableReports = Map.insert bPair cex (pairGraphObservableReports gr) }
considerDesyncEvent :: Monad m =>
IsTreeBuilder '(sym, arch) PEE.EquivalenceError m =>
PA.ValidArch arch =>
PairGraph sym arch ->
NodeEntry arch ->
(m (Maybe (TotalityCounterexample (MM.ArchAddrWidth arch)), PairGraph sym arch)) ->
m (PairGraph sym arch)
considerDesyncEvent gr bPair action =
case Map.lookup bPair (pairGraphDesyncReports gr) of
Just cex -> do
withTracing @"totalityce" cex $
emitTraceWarning $ PEE.equivalenceError $ PEE.NonTotalBlockExits (nodeBlocks bPair)
return gr
Nothing ->
do (mcex, gr') <- action
case mcex of
Nothing -> return gr'
Just cex -> do
withTracing @"totalityce" cex $
emitTraceWarning $ PEE.equivalenceError $ PEE.NonTotalBlockExits (nodeBlocks bPair)
return gr'{ pairGraphDesyncReports = Map.insert bPair cex (pairGraphDesyncReports gr) }
| Record an error that occured during analysis that does n't fall into one of the
recordMiscAnalysisError ::
PairGraph sym arch ->
GraphNode arch ->
PEE.EquivalenceError ->
PairGraph sym arch
recordMiscAnalysisError gr nd er =
let m = Map.alter f nd (pairGraphMiscAnalysisErrors gr)
f Nothing = Just [er]
f (Just s) = Just (er:s)
in gr{ pairGraphMiscAnalysisErrors = m }
reportAnalysisErrors
:: (PA.ValidArch arch, W4.IsExprBuilder sym, MonadIO m)
=> LJ.LogAction IO (Event.Event arch)
-> PairGraph sym arch
-> m ()
reportAnalysisErrors logAction gr =
do mapM_ reportObservables (Map.toList (pairGraphObservableReports gr))
mapM_ reportDesync (Map.toList (pairGraphDesyncReports gr))
mapM_ reportGasExhausted (Set.toList (pairGraphGasExhausted gr))
mapM_ reportMiscError (Map.toList (pairGraphMiscAnalysisErrors gr))
where
reportObservables (pPair, ocex) =
liftIO $ LJ.writeLog logAction (Event.StrongestPostObservable pPair ocex)
reportDesync (pPair, tcex) =
liftIO $ LJ.writeLog logAction (Event.StrongestPostDesync pPair tcex)
reportGasExhausted pPair =
liftIO $ LJ.writeLog logAction (Event.GasExhausted pPair)
reportMiscError (pPair, msgs) =
liftIO $ F.forM_ msgs $ \msg -> do
LJ.writeLog logAction (Event.StrongestPostMiscError pPair msg)
initialDomain :: EquivM sym arch (PAD.AbstractDomain sym arch v)
initialDomain = withSym $ \sym ->
PAD.AbstractDomain
<$> pure (PVD.universalDomain sym)
<*> (PPa.forBins $ \_ -> return $ PAD.emptyDomainVals)
<*> (PPa.forBins $ \_ -> PAD.emptyEvents sym)
initialDomainSpec ::
forall sym arch.
GraphNode arch ->
EquivM sym arch (PAD.AbstractDomainSpec sym arch)
initialDomainSpec (GraphNodeEntry blocks) = withTracing @"function_name" "initialDomainSpec" $
withFreshVars blocks $ \_vars -> do
dom <- initialDomain
return (mempty, dom)
initialDomainSpec (GraphNodeReturn fPair) = withTracing @"function_name" "initialDomainSpec" $ do
let blocks = TF.fmapF PB.functionEntryToConcreteBlock fPair
withFreshVars blocks $ \_vars -> do
dom <- initialDomain
return (mempty, dom)
initializePairGraph :: forall sym arch.
[PB.FunPair arch] ->
EquivM sym arch (PairGraph sym arch)
initializePairGraph pPairs = foldM (\x y -> initPair x y) emptyPairGraph pPairs
where
initPair :: PairGraph sym arch -> PB.FunPair arch -> EquivM sym arch (PairGraph sym arch)
initPair gr fnPair =
do let bPair = TF.fmapF PB.functionEntryToConcreteBlock fnPair
withPair bPair $ do
let node = GraphNode (rootEntry bPair)
idom <- initialDomainSpec node
rootDom <- PS.forSpec idom $ \_ idom' -> do
vals' <- PPa.forBins $ \bin -> do
vals <- PPa.get bin (PAD.absDomVals idom')
FIXME : compute this from the global and stack regions
return $ vals { PAD.absMaxRegion = PAD.AbsIntConstant 3 }
return $ idom' { PAD.absDomVals = vals' }
let gr1 = freshDomain gr node rootDom
return $ emptyReturnVector gr1 (rootReturn fnPair)
chooseWorkItem ::
PA.ValidArch arch =>
PairGraph sym arch ->
Maybe (PairGraph sym arch, GraphNode arch, AbstractDomainSpec sym arch)
chooseWorkItem gr =
case Set.minView (pairGraphWorklist gr) of
Nothing -> Nothing
Just (nd, wl) -> case Map.lookup nd (pairGraphDomains gr) of
Nothing -> panic Verifier "choseoWorkItem" ["Could not find domain corresponding to block pair", show nd]
Just d -> Just (gr{ pairGraphWorklist = wl }, nd, d)
If we have run out of Gas , return a ` Left ` value .
updateDomain ::
Either (PairGraph sym arch) (PairGraph sym arch)
updateDomain gr pFrom pTo d
| g > 0 = Right $ markEdge pFrom pTo $ gr
{ pairGraphDomains = Map.insert pTo d (pairGraphDomains gr)
, pairGraphGas = Map.insert (pFrom,pTo) (Gas (g-1)) (pairGraphGas gr)
, pairGraphWorklist = Set.insert pTo (pairGraphWorklist gr)
, pairGraphEdges = Map.insertWith Set.union pFrom (Set.singleton pTo) (pairGraphEdges gr)
, pairGraphBackEdges = Map.insertWith Set.union pTo (Set.singleton pFrom) (pairGraphBackEdges gr)
}
| otherwise =
Left $ markEdge pFrom pTo $ gr
{ pairGraphDomains = Map.insert pTo d (pairGraphDomains gr)
}
where
Lookup the amount of remaining gas . Initialize to a fresh value
Gas g = fromMaybe initialGas (Map.lookup (pFrom,pTo) (pairGraphGas gr))
emptyReturnVector ::
PairGraph sym arch ->
NodeReturn arch ->
PairGraph sym arch
emptyReturnVector gr ret = gr{ pairGraphReturnVectors = rvs }
where
rvs = Map.alter f ret (pairGraphReturnVectors gr)
f Nothing = Just (Set.empty)
f (Just s) = Just s
addReturnVector ::
PairGraph sym arch ->
PairGraph sym arch
addReturnVector gr funPair retPair =
case Map.lookup (ReturnNode funPair) (pairGraphDomains gr) of
No node for the return from this function . Either this is the first
Nothing -> gr{ pairGraphReturnVectors = rvs }
We know there is at least one control - flow path through the function
Just _ ->
gr{ pairGraphReturnVectors = rvs
, pairGraphWorklist = wl
}
where
Remember that is one of the places that funPair
rvs = Map.alter f funPair (pairGraphReturnVectors gr)
f Nothing = Just (Set.singleton retPair)
f (Just s) = Just (Set.insert retPair s)
wl = Set.insert (ReturnNode funPair) (pairGraphWorklist gr)
getSyncPoint ::
PairGraph sym arch ->
NodeReturn arch ->
Maybe (Set (NodeReturn arch))
getSyncPoint gr nd = Map.lookup nd (pairGraphSyncPoint gr)
addSyncPoint ::
PairGraph sym arch ->
PairGraph sym arch
addSyncPoint gr from to
| PPa.PatchPairSingle{} <- nodeFuns from
, PPa.PatchPair{} <- nodeFuns to =
gr { pairGraphSyncPoint = Map.insertWith Set.union from (Set.singleton to) (pairGraphSyncPoint gr) }
addSyncPoint _ _ _ = error "addSyncPoint: unexpected PatchPair shape"
addToWorkList ::
GraphNode arch ->
PairGraph sym arch ->
Maybe (PairGraph sym arch)
addToWorkList nd gr = case getCurrentDomain gr nd of
Just{} -> Just $ gr { pairGraphWorklist = Set.insert nd (pairGraphWorklist gr) }
Nothing -> Nothing
freshDomain ::
PairGraph sym arch
freshDomain gr pTo d =
gr{ pairGraphDomains = Map.insert pTo d (pairGraphDomains gr)
, pairGraphWorklist = Set.insert pTo (pairGraphWorklist gr)
}
markEdge ::
PairGraph sym arch ->
PairGraph sym arch
markEdge from to gr =
gr { pairGraphEdges = Map.insertWith Set.union from (Set.singleton to) (pairGraphEdges gr)
, pairGraphBackEdges = Map.insertWith Set.union to (Set.singleton from) (pairGraphBackEdges gr)}
addExtraEdge ::
PairGraph sym arch ->
NodeEntry arch ->
GraphNode arch ->
PairGraph sym arch
addExtraEdge gr from to = markEdge (GraphNode from) to $
gr { pairGraphExtraEdges = Map.insertWith Set.union from (Set.singleton to) ( pairGraphExtraEdges gr)
}
getExtraEdges ::
PairGraph sym arch ->
NodeEntry arch ->
Set (GraphNode arch)
getExtraEdges gr e = case Map.lookup e (pairGraphExtraEdges gr) of
Just es -> es
Nothing -> Set.empty
addTerminalNode ::
PairGraph sym arch ->
NodeReturn arch ->
PairGraph sym arch
addTerminalNode gr nd = gr { pairGraphTerminalNodes = Set.insert nd (pairGraphTerminalNodes gr) }
getOrphanedReturns ::
PairGraph sym arch ->
Set (NodeReturn arch)
getOrphanedReturns gr = do
let rets = (Map.keysSet (pairGraphReturnVectors gr)) Set.\\ (pairGraphTerminalNodes gr)
Set.filter (\ret -> not (Map.member (ReturnNode ret) (pairGraphDomains gr))) rets
pairGraphComputeVerdict ::
PairGraph sym arch ->
EquivM sym arch PE.EquivalenceStatus
pairGraphComputeVerdict gr =
if Map.null (pairGraphObservableReports gr) &&
Map.null (pairGraphDesyncReports gr) &&
Set.null (pairGraphGasExhausted gr) then
return PE.Equivalent
else
return PE.Inequivalent
|
7dbff36de3656a0c15652e11da2eb888d49143421c7b983acf004ccaf4652972 | morphismtech/squeal | Exception.hs | |
Module : Squeal . PostgreSQL.Session . Exception
Description : exceptions
Copyright : ( c ) , 2019
Maintainer :
Stability : experimental
exceptions
Module: Squeal.PostgreSQL.Session.Exception
Description: exceptions
Copyright: (c) Eitan Chatav, 2019
Maintainer:
Stability: experimental
exceptions
-}
# LANGUAGE
OverloadedStrings
, PatternSynonyms
#
OverloadedStrings
, PatternSynonyms
#-}
module Squeal.PostgreSQL.Session.Exception
( SquealException (..)
, pattern UniqueViolation
, pattern CheckViolation
, pattern SerializationFailure
, pattern DeadlockDetected
, SQLState (..)
, LibPQ.ExecStatus (..)
, catchSqueal
, handleSqueal
, trySqueal
, throwSqueal
) where
import Control.Monad.Catch
import Data.ByteString (ByteString)
import Data.Text (Text)
import qualified Database.PostgreSQL.LibPQ as LibPQ
-- $setup
-- >>> import Squeal.PostgreSQL
| the state of LibPQ
data SQLState = SQLState
{ sqlExecStatus :: LibPQ.ExecStatus
, sqlStateCode :: ByteString
-- ^ -appendix.html
, sqlErrorMessage :: ByteString
} deriving (Eq, Show)
-- | `Exception`s that can be thrown by Squeal.
data SquealException
= SQLException SQLState
-- ^ SQL exception state
| ConnectionException Text
-- ^ `Database.PostgreSQL.LibPQ` function connection exception
| DecodingException Text Text
-- ^ decoding exception function and error message
| ColumnsException Text LibPQ.Column
-- ^ unexpected number of columns
| RowsException Text LibPQ.Row LibPQ.Row
-- ^ too few rows, expected at least and actual number of rows
deriving (Eq, Show)
instance Exception SquealException
-- | A pattern for unique violation exceptions.
pattern UniqueViolation :: ByteString -> SquealException
pattern UniqueViolation msg =
SQLException (SQLState LibPQ.FatalError "23505" msg)
-- | A pattern for check constraint violation exceptions.
pattern CheckViolation :: ByteString -> SquealException
pattern CheckViolation msg =
SQLException (SQLState LibPQ.FatalError "23514" msg)
-- | A pattern for serialization failure exceptions.
pattern SerializationFailure :: ByteString -> SquealException
pattern SerializationFailure msg =
SQLException (SQLState LibPQ.FatalError "40001" msg)
-- | A pattern for deadlock detection exceptions.
pattern DeadlockDetected :: ByteString -> SquealException
pattern DeadlockDetected msg =
SQLException (SQLState LibPQ.FatalError "40P01" msg)
-- | Catch `SquealException`s.
catchSqueal
:: MonadCatch m
=> m a
-> (SquealException -> m a) -- ^ handler
-> m a
catchSqueal = catch
-- | Handle `SquealException`s.
handleSqueal
:: MonadCatch m
=> (SquealException -> m a) -- ^ handler
-> m a -> m a
handleSqueal = handle
-- | `Either` return a `SquealException` or a result.
trySqueal :: MonadCatch m => m a -> m (Either SquealException a)
trySqueal = try
-- | Throw `SquealException`s.
throwSqueal :: MonadThrow m => SquealException -> m a
throwSqueal = throwM
| null | https://raw.githubusercontent.com/morphismtech/squeal/a639fea5e48a1d3cecc9e0f296e97c1c82f16e97/squeal-postgresql/src/Squeal/PostgreSQL/Session/Exception.hs | haskell | $setup
>>> import Squeal.PostgreSQL
^ -appendix.html
| `Exception`s that can be thrown by Squeal.
^ SQL exception state
^ `Database.PostgreSQL.LibPQ` function connection exception
^ decoding exception function and error message
^ unexpected number of columns
^ too few rows, expected at least and actual number of rows
| A pattern for unique violation exceptions.
| A pattern for check constraint violation exceptions.
| A pattern for serialization failure exceptions.
| A pattern for deadlock detection exceptions.
| Catch `SquealException`s.
^ handler
| Handle `SquealException`s.
^ handler
| `Either` return a `SquealException` or a result.
| Throw `SquealException`s. | |
Module : Squeal . PostgreSQL.Session . Exception
Description : exceptions
Copyright : ( c ) , 2019
Maintainer :
Stability : experimental
exceptions
Module: Squeal.PostgreSQL.Session.Exception
Description: exceptions
Copyright: (c) Eitan Chatav, 2019
Maintainer:
Stability: experimental
exceptions
-}
# LANGUAGE
OverloadedStrings
, PatternSynonyms
#
OverloadedStrings
, PatternSynonyms
#-}
module Squeal.PostgreSQL.Session.Exception
( SquealException (..)
, pattern UniqueViolation
, pattern CheckViolation
, pattern SerializationFailure
, pattern DeadlockDetected
, SQLState (..)
, LibPQ.ExecStatus (..)
, catchSqueal
, handleSqueal
, trySqueal
, throwSqueal
) where
import Control.Monad.Catch
import Data.ByteString (ByteString)
import Data.Text (Text)
import qualified Database.PostgreSQL.LibPQ as LibPQ
| the state of LibPQ
data SQLState = SQLState
{ sqlExecStatus :: LibPQ.ExecStatus
, sqlStateCode :: ByteString
, sqlErrorMessage :: ByteString
} deriving (Eq, Show)
data SquealException
= SQLException SQLState
| ConnectionException Text
| DecodingException Text Text
| ColumnsException Text LibPQ.Column
| RowsException Text LibPQ.Row LibPQ.Row
deriving (Eq, Show)
instance Exception SquealException
pattern UniqueViolation :: ByteString -> SquealException
pattern UniqueViolation msg =
SQLException (SQLState LibPQ.FatalError "23505" msg)
pattern CheckViolation :: ByteString -> SquealException
pattern CheckViolation msg =
SQLException (SQLState LibPQ.FatalError "23514" msg)
pattern SerializationFailure :: ByteString -> SquealException
pattern SerializationFailure msg =
SQLException (SQLState LibPQ.FatalError "40001" msg)
pattern DeadlockDetected :: ByteString -> SquealException
pattern DeadlockDetected msg =
SQLException (SQLState LibPQ.FatalError "40P01" msg)
catchSqueal
:: MonadCatch m
=> m a
-> m a
catchSqueal = catch
handleSqueal
:: MonadCatch m
-> m a -> m a
handleSqueal = handle
trySqueal :: MonadCatch m => m a -> m (Either SquealException a)
trySqueal = try
throwSqueal :: MonadThrow m => SquealException -> m a
throwSqueal = throwM
|
5e1bfcf4ce603567669db7828726ae3083aac7d6a678c67526bcec0eb30f18c6 | webyrd/n-grams-for-synthesis | teaselp_demo_expert_ordering.scm | (define *output-table-file-name* "tmp/variant-expert-ordering-with-application-and-lookup-optimizations-table.scm")
(define allow-incomplete-search? #f)
(define lookup-optimization? #t)
(load "mk-vicare.scm")
(load "mk.scm")
(load "test-check.scm")
(load "interp-app-optimization.scm")
(load "construct-ordering.scm")
(load "interp-expert.scm")
(display "Testing expert ordering with foldr\n")
(time
(run 1 (defn)
(let ((g1 (gensym "g1"))
(g2 (gensym "g2"))
(g3 (gensym "g3"))
(g4 (gensym "g4"))
(g5 (gensym "g5"))
(g6 (gensym "g6"))
(g7 (gensym "g7")))
(fresh (q)
(absento g1 defn)
(absento g2 defn)
(absento g3 defn)
(absento g4 defn)
(absento g5 defn)
(absento g6 defn)
(absento g7 defn)
(absento 'match defn)
(fresh (a)
(== `(lambda (f acc xs)
,a)
defn))
(evalo `(letrec ((foldr ,defn))
(list
(foldr ',g2 ',g1 '())
(foldr (lambda (a d) (cons a d)) ',g3 '(,g4))
(foldr (lambda (a d) (cons a d)) ',g4 '(,g5 ,g6))
(foldr (lambda (v1 v2) (equal? v1 v2)) ',g7 '(,g7))))
(list
g1
`(,g4 . ,g3)
`(,g5 ,g6 . ,g4)
#t
))))))
(display "Testing expert ordering with append\n")
(display "Warning this won't terminate\n")
(time
(run 1 (prog)
(fresh ()
(absento 'a prog)
(absento 'b prog)
(absento 'c prog)
(absento 'd prog)
(absento 'e prog)
(absento 'f prog)
(evalo
`(letrec ((append ,prog))
(list
(append '() '())
(append '(a) '(b))
(append '(c d) '(e f))))
'(()
(a b)
(c d e f))))))
| null | https://raw.githubusercontent.com/webyrd/n-grams-for-synthesis/b53b071e53445337d3fe20db0249363aeb9f3e51/teaselp_demo_expert_ordering.scm | scheme | (define *output-table-file-name* "tmp/variant-expert-ordering-with-application-and-lookup-optimizations-table.scm")
(define allow-incomplete-search? #f)
(define lookup-optimization? #t)
(load "mk-vicare.scm")
(load "mk.scm")
(load "test-check.scm")
(load "interp-app-optimization.scm")
(load "construct-ordering.scm")
(load "interp-expert.scm")
(display "Testing expert ordering with foldr\n")
(time
(run 1 (defn)
(let ((g1 (gensym "g1"))
(g2 (gensym "g2"))
(g3 (gensym "g3"))
(g4 (gensym "g4"))
(g5 (gensym "g5"))
(g6 (gensym "g6"))
(g7 (gensym "g7")))
(fresh (q)
(absento g1 defn)
(absento g2 defn)
(absento g3 defn)
(absento g4 defn)
(absento g5 defn)
(absento g6 defn)
(absento g7 defn)
(absento 'match defn)
(fresh (a)
(== `(lambda (f acc xs)
,a)
defn))
(evalo `(letrec ((foldr ,defn))
(list
(foldr ',g2 ',g1 '())
(foldr (lambda (a d) (cons a d)) ',g3 '(,g4))
(foldr (lambda (a d) (cons a d)) ',g4 '(,g5 ,g6))
(foldr (lambda (v1 v2) (equal? v1 v2)) ',g7 '(,g7))))
(list
g1
`(,g4 . ,g3)
`(,g5 ,g6 . ,g4)
#t
))))))
(display "Testing expert ordering with append\n")
(display "Warning this won't terminate\n")
(time
(run 1 (prog)
(fresh ()
(absento 'a prog)
(absento 'b prog)
(absento 'c prog)
(absento 'd prog)
(absento 'e prog)
(absento 'f prog)
(evalo
`(letrec ((append ,prog))
(list
(append '() '())
(append '(a) '(b))
(append '(c d) '(e f))))
'(()
(a b)
(c d e f))))))
|
|
2b1f78b7477e0e81c7bd727f91e63ed3ce9dca23d88ee1608792b8f94e1608dc | Plutonomicon/plutarch-plutus | TypeFamily.hs | # LANGUAGE UndecidableInstances #
module Plutarch.Internal.TypeFamily (ToPType, ToPType2, UnTerm, Snd) where
import Data.Kind (Type)
import GHC.TypeLits (ErrorMessage (Text), TypeError)
import Plutarch.Internal (PType, Term)
-- | Convert a list of `Term s a` to a list of `a`.
type ToPType :: [Type] -> [PType]
type family ToPType as where
ToPType '[] = '[]
ToPType (a ': as) = UnTerm a ': ToPType as
type ToPType2 :: [[Type]] -> [[PType]]
type family ToPType2 as where
ToPType2 '[] = '[]
ToPType2 (a ': as) = ToPType a ': ToPType2 as
type UnTerm :: Type -> PType
type family UnTerm x where
UnTerm (Term _ a) = a
UnTerm _ = TypeError ('Text "Non-term in Plutarch data type not allowed")
type family Snd ab where
Snd '(_, b) = b
| null | https://raw.githubusercontent.com/Plutonomicon/plutarch-plutus/d3df05ce67d8b5a3d2ca851a6e5a1b8ff8cb358f/Plutarch/Internal/TypeFamily.hs | haskell | | Convert a list of `Term s a` to a list of `a`. | # LANGUAGE UndecidableInstances #
module Plutarch.Internal.TypeFamily (ToPType, ToPType2, UnTerm, Snd) where
import Data.Kind (Type)
import GHC.TypeLits (ErrorMessage (Text), TypeError)
import Plutarch.Internal (PType, Term)
type ToPType :: [Type] -> [PType]
type family ToPType as where
ToPType '[] = '[]
ToPType (a ': as) = UnTerm a ': ToPType as
type ToPType2 :: [[Type]] -> [[PType]]
type family ToPType2 as where
ToPType2 '[] = '[]
ToPType2 (a ': as) = ToPType a ': ToPType2 as
type UnTerm :: Type -> PType
type family UnTerm x where
UnTerm (Term _ a) = a
UnTerm _ = TypeError ('Text "Non-term in Plutarch data type not allowed")
type family Snd ab where
Snd '(_, b) = b
|
e538e64016f7919b3bb6b1f35b75be671525b6b4ea6715bf96e214d8769f27d6 | zcaudate/hara | seq.clj | (ns hara.data.base.seq)
(defn positions
"find positions of elements matching the predicate
(positions even? [5 5 4 4 3 3 2 2])
=> [2 3 6 7]"
{:added "3.0"}
[pred coll]
(keep-indexed (fn [idx x]
(when (pred x)
idx))
coll))
(defn remove-index
"removes element at the specified index
(remove-index [:a :b :c :d] 2)
=> [:a :b :d]"
{:added "3.0"}
[coll i]
(cond (vector? coll)
(reduce conj
(subvec coll 0 i)
(subvec coll (inc i) (count coll)))
:else
(keep-indexed #(if (not= %1 i) %2) coll)))
(defn index-of
"finds the index of the first matching element in an array
(index-of even? [1 2 3 4]) => 1
(index-of keyword? [1 2 :hello 4]) => 2"
{:added "3.0"}
[pred coll]
(loop [[x & more :as coll] coll
i 0]
(cond (empty? coll) -1
(pred x) i
:else
(recur more (inc i)))))
(defn element-of
"finds the element within an array
(element-of keyword? [1 2 :hello 4])
=> :hello"
{:added "3.0"}
[pred coll]
(loop [[x & more :as coll] coll]
(cond (empty? coll) nil
(pred x) x
:else
(recur more))))
(defn flatten-all
"flattens all elements the collection
(flatten-all [1 2 #{3 {4 5}}])
=> [1 2 3 4 5]"
{:added "3.0"}
[x]
(filter (complement coll?)
(rest (tree-seq coll? seq x))))
| null | https://raw.githubusercontent.com/zcaudate/hara/481316c1f5c2aeba5be6e01ae673dffc46a63ec9/src/hara/data/base/seq.clj | clojure | (ns hara.data.base.seq)
(defn positions
"find positions of elements matching the predicate
(positions even? [5 5 4 4 3 3 2 2])
=> [2 3 6 7]"
{:added "3.0"}
[pred coll]
(keep-indexed (fn [idx x]
(when (pred x)
idx))
coll))
(defn remove-index
"removes element at the specified index
(remove-index [:a :b :c :d] 2)
=> [:a :b :d]"
{:added "3.0"}
[coll i]
(cond (vector? coll)
(reduce conj
(subvec coll 0 i)
(subvec coll (inc i) (count coll)))
:else
(keep-indexed #(if (not= %1 i) %2) coll)))
(defn index-of
"finds the index of the first matching element in an array
(index-of even? [1 2 3 4]) => 1
(index-of keyword? [1 2 :hello 4]) => 2"
{:added "3.0"}
[pred coll]
(loop [[x & more :as coll] coll
i 0]
(cond (empty? coll) -1
(pred x) i
:else
(recur more (inc i)))))
(defn element-of
"finds the element within an array
(element-of keyword? [1 2 :hello 4])
=> :hello"
{:added "3.0"}
[pred coll]
(loop [[x & more :as coll] coll]
(cond (empty? coll) nil
(pred x) x
:else
(recur more))))
(defn flatten-all
"flattens all elements the collection
(flatten-all [1 2 #{3 {4 5}}])
=> [1 2 3 4 5]"
{:added "3.0"}
[x]
(filter (complement coll?)
(rest (tree-seq coll? seq x))))
|
|
9d02a5cec10c7dc944f1a22bee8c13e6bcc9347280e763025e7bfd7f4bc50de0 | cedlemo/OCaml-libmpdclient | mpd_lwt_client_idle_loop.ml |
* Copyright 2017 ,
* This file is part of .
*
* OCaml - libmpdclient is free software : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* h : noh::j
* any later version .
*
* OCaml - libmpdclient 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 . If not , see < / > .
* Copyright 2017 Cedric LE MOIGNE,
* This file is part of OCaml-libmpdclient.
*
* OCaml-libmpdclient is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* h:noh::j
* any later version.
*
* OCaml-libmpdclient 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 OCaml-libmpdclient. If not, see </>.
*)
open Lwt
open Mpd
(* Simple client that connects to a mpd server with the "idle" command and get
* all the events of the mpd server.
* Leave with Crtl+C *)
let host = "127.0.0.1"
let port = 6600
let on_mpd_event = function
| "mixer" -> print_endline "Mixer related command has been executed"; Lwt.return true
| _ as event_name -> print_endline (("-" ^ event_name) ^ "-"); Lwt.return false
let main_thread =
Lwt.catch
(fun () ->
Mpd.Connection_lwt.initialize host port
>>= fun connection ->
Lwt_io.write_line Lwt_io.stdout "Client on"
>>= fun () ->
Mpd.Client_lwt.initialize connection
>>= fun client ->
Lwt_io.write_line Lwt_io.stdout (Mpd.Client_lwt.mpd_banner client)
>>= fun () ->
Mpd.Client_lwt.idle_loop client on_mpd_event
>>= fun () ->
Lwt.return 0
)
(function
| Mpd.Connection_lwt.Lwt_unix_exn message ->
Lwt_io.write_line Lwt_io.stderr message
>>= fun () ->
Lwt.return 125
| _ ->
Lwt_io.write_line Lwt_io.stderr "Uncaught exception. Exiting ..."
>>= fun () ->
Lwt.return 125
)
let () = exit (Lwt_main.run main_thread)
| null | https://raw.githubusercontent.com/cedlemo/OCaml-libmpdclient/49922f4fa0c1471324c613301675ffc06ff3147c/samples/mpd_lwt_client_idle_loop.ml | ocaml | Simple client that connects to a mpd server with the "idle" command and get
* all the events of the mpd server.
* Leave with Crtl+C |
* Copyright 2017 ,
* This file is part of .
*
* OCaml - libmpdclient is free software : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* h : noh::j
* any later version .
*
* OCaml - libmpdclient 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 . If not , see < / > .
* Copyright 2017 Cedric LE MOIGNE,
* This file is part of OCaml-libmpdclient.
*
* OCaml-libmpdclient is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* h:noh::j
* any later version.
*
* OCaml-libmpdclient 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 OCaml-libmpdclient. If not, see </>.
*)
open Lwt
open Mpd
let host = "127.0.0.1"
let port = 6600
let on_mpd_event = function
| "mixer" -> print_endline "Mixer related command has been executed"; Lwt.return true
| _ as event_name -> print_endline (("-" ^ event_name) ^ "-"); Lwt.return false
let main_thread =
Lwt.catch
(fun () ->
Mpd.Connection_lwt.initialize host port
>>= fun connection ->
Lwt_io.write_line Lwt_io.stdout "Client on"
>>= fun () ->
Mpd.Client_lwt.initialize connection
>>= fun client ->
Lwt_io.write_line Lwt_io.stdout (Mpd.Client_lwt.mpd_banner client)
>>= fun () ->
Mpd.Client_lwt.idle_loop client on_mpd_event
>>= fun () ->
Lwt.return 0
)
(function
| Mpd.Connection_lwt.Lwt_unix_exn message ->
Lwt_io.write_line Lwt_io.stderr message
>>= fun () ->
Lwt.return 125
| _ ->
Lwt_io.write_line Lwt_io.stderr "Uncaught exception. Exiting ..."
>>= fun () ->
Lwt.return 125
)
let () = exit (Lwt_main.run main_thread)
|
0e7eb0e54ce9c0ad76b5692a4679cbbdf64ef7d423f758454f69f7708e203693 | 8c6794b6/haskell-sc-scratch | Server3.hs | {-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveDataTypeable #-}
|
Module : $ Header$
CopyRight : ( c ) 8c6794b6
License : :
Stability : unstable
Portability : non - portable ( GHC concurrency , DeriveDataTypeable )
Server to manage patterns , take 3 .
Using TVar instead of MVar , not using ReaderMonad .
Module : $Header$
CopyRight : (c) 8c6794b6
License : BSD3
Maintainer :
Stability : unstable
Portability : non-portable (GHC concurrency, DeriveDataTypeable)
Server to manage patterns, take 3.
Using TVar instead of MVar, not using ReaderMonad.
-}
module Sound.SC3.Lepton.Pattern.Server3 where
import Control.Concurrent
import Control.Monad
import Control.Monad.Reader
import Control.Concurrent.STM
import Control.Exception (bracket)
import Data.ByteString.Lazy (ByteString)
import Data.Data (Data, Typeable)
import Data.Binary (decode)
import Sound.OSC.FD
import Sound.SC3 (n_free, withNotifications)
import qualified Codec.Compression.Zlib as Z
import qualified Data.ByteString.Char8 as C8
import qualified Data.Foldable as F
import qualified Data.Map as M
import Sound.SC3.Lepton.Pattern
------------------------------------------------------------------------------
-- * Types
data Protocol = Tcp | Udp deriving (Eq,Show,Data,Typeable)
data ConInfo = ConInfo
{ ciHost :: String
, ciPort :: Int
, ciProtocol :: Protocol
} deriving (Eq, Show)
data Con = UDPCon UDP | TCPCon TCP
instance Transport Con where
sendOSC (UDPCon c) o = sendOSC c o
sendOSC (TCPCon c) o = sendOSC c o
recvPacket (UDPCon c) = recvPacket c
recvPacket (TCPCon c) = recvPacket c
close (UDPCon c) = close c
close (TCPCon c) = close c
data ServerEnv = ServerEnv
{ seThreads :: TVar (M.Map String ThreadInfo)
, sePort :: Int
, seLept :: UDP
, seSC :: ConInfo }
data ThreadInfo = Running ThreadId | Stopped deriving (Eq, Show)
------------------------------------------------------------------------------
-- * Guts
-- XXX: Why not ReaderT IO?
-- I thought wrapping with monad transformer makes the code slow.
-- But haven't benchmarked and compared, yet.... biased, not good.
--
XXX : Why using TVar instead of MVar ?
Thought STM will work better here , but not much difference .
-- | Guts of server message receiving loop.
--
When shutting down , side connection would be closed and
-- all threads in server env will be killed.
--
go ::
Int
-- ^ Port of pattern server
-> String
-- ^ Host of scsynth to connect
-> Protocol
-- ^ Protocol of scsynth to connect
-> Int
-- ^ Port of scsynth to connect
-> IO ()
go lport shost sprtc sport = bracket acquire tidyup work where
acquire = do
putStrLn $ "Starting server with port " ++ show lport
tv <- atomically $ newTVar M.empty
lcon <- udpServer "127.0.0.1" lport
let scon = ConInfo shost sport sprtc
putStrLn $
concat [ "Using scsynth [host:", shost
, ", port:", show sport, ", protocol:", show sprtc, "]"]
return $ ServerEnv tv lport lcon scon
tidyup e = do
close $ seLept e
tmap <- atomically $ readTVar $ seThreads e
F.forM_ tmap $ \tinfo ->
case tinfo of
Running tid -> killThread tid
Stopped -> return ()
work = loop
-- | Guts of server loop.
Receives OSC message from side connection , sends message to
-- scsynth.
loop :: ServerEnv -> IO ()
loop env = forever $ do
msg <- recvPacket $ seLept env
handleMessage env msg
| Handle bundled and non - bundles OSC message .
handleMessage :: ServerEnv -> Packet -> IO ()
handleMessage env msg = case msg of
Packet_Bundle (Bundle t msgs) -> mapM_ (sendMsg env (Just t)) msgs
Packet_Message msg' -> sendMsg env Nothing msg'
-- | Pattern match OSC message and send to scsynth server.
sendMsg
:: ServerEnv
-- ^ Environment for server
-> Maybe Time
^ Offset time of OSC message
-> Message
-- ^ OSC message body
-> IO ()
sendMsg env t msg = case msg of
Message "/l_new" [ASCII_String name, Blob b] ->
runLNew env t (C8.unpack name) b
Message "/l_free" [ASCII_String name] ->
runLFree env t (C8.unpack name)
Message "/l_freeAll" [] -> runLFreeAll env t
Message "/l_dump" [] -> runLDump env
_ ->
putStrLn $ "Unknown: " ++ show msg
-- | Run new pattern.
runLNew
:: ServerEnv
-- ^ Environment for server
-> Maybe Time
^ Offset time of OSC message
-> String
-- ^ Name of thread
-> ByteString
-- ^ Serialized pattern
-> IO ()
runLNew env tm name blob = do
--
XXX : No gurantee for thread Map to contain un - managed threads .
--
Since forkIO is invoked between atomic STM actions ,
unless using unsafePerformIO , forkIO need to be called outside of
STM action .
--
tmap <- atomically $ readTVar $ seThreads env
let !maybeKill = case M.lookup name tmap of
Just (Running tid) -> killThread tid
_ -> return ()
tid <- forkIO $ do
maybePause tm
maybeKill
mkThread env tm name blob
atomically $ writeTVar (seThreads env) $ M.insert name (Running tid) tmap
-- | Free specified thread.
runLFree
:: ServerEnv
-- ^ Environment for server
-> Maybe Time
-- ^ Offset time for sending message
-> String
-- ^ Thread name to kill
-> IO ()
runLFree env tm name = do
tmap <- atomically $ readTVar $ seThreads env
case M.lookup name tmap of
Just (Running tid) -> do
maybePause tm
killThread tid
atomically $
writeTVar (seThreads env) $ M.delete name tmap
_ -> putStrLn $ "Thread " ++ name ++ " does not exist"
-- | Free all thread in server environment.
runLFreeAll
:: ServerEnv
-- ^ Server environment
-> Maybe Time
-- ^ Offset time for sending message
-> IO ()
runLFreeAll env tm = do
let tv = seThreads env
tmap <- atomically $ readTVar tv
maybePause tm
F.forM_ tmap $ \tinfo -> case tinfo of
Running tid -> do
killThread tid
putStrLn $ unwords ["Thread:", show tid, "killed"]
_ -> return ()
atomically $ writeTVar tv $ M.empty
-- | Dump info of given server environment.
runLDump :: ServerEnv -> IO ()
runLDump env = do
tmap <- atomically $ readTVar $ seThreads env
putStrLn "========== Threads ==========="
F.forM_ (M.toList tmap) $ \(name,ti) ->
putStrLn $ name ++ ": " ++ show ti
-- | Play given patttern with new thread.
-- When the given pattern is finite, forked thread will update thread
-- status of itself in server env when finished playing the pattern.
mkThread
:: ServerEnv
-- ^ Environment for server
-> Maybe Time
-- ^ Offset time
-> String
-- ^ Name for new thread
-> ByteString
-- ^ Serialized pattern
-> IO ()
mkThread env time0 name blob = case decodePattern blob of
Left err -> print err
Right pat' -> do
withTransport (fromConInfo (seSC env)) $ \fd ->
let acquire = do
-- sendOSC fd (notify True)
trid <- newNid
return (fd, trid)
tidyup (fd',trid) = do
-- sendOSC fd' $ bundle immediately [notify False, n_free [tid]]
sendOSC fd' $ n_free [trid]
close fd'
--
-- XXX:
-- When below cleanup were done, creating new thread with same name
-- will make unmanaged thread in ServerEnv. Commented out for
-- supporting creation of thread with same name.
--
-- atomically $ do
-- let tv = seThreads env
-- tmap <- readTVar tv
writeTVar tv ( M.delete name tmap )
--
work (fd',trid) = do
time' <- maybe time return time0
runReaderT (withNotifications $ runMsgFrom time' pat' trid) fd'
atomically $ do
let tv = seThreads env
tmap <- readTVar tv
writeTVar tv $ M.adjust (const Stopped) name tmap
in bracket acquire tidyup work
-- | Open new connection from host, port, and protocol information.
fromConInfo :: ConInfo -> IO Con
fromConInfo (ConInfo h p ptc) = case ptc of
Udp -> UDPCon `fmap` openUDP h p
Tcp -> TCPCon `fmap` openTCP h p
-- | Pause until given time when Just time was given.
Will not pause when was given , nor given time was past .
maybePause :: Maybe Time -> IO ()
maybePause = F.mapM_ $ \time0 -> do
dt <- (time0 -) `fmap` time
let (q,_) = properFraction (dt * 1e6)
when (dt > 0) $ threadDelay q
-- | Decode compressed pattern bytestring.
decodePattern :: ByteString -> Either String (L () (ToOSC Double))
decodePattern = t2l . decode . Z.decompress
| null | https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/hsc3-lepton/src/lib/Sound/SC3/Lepton/Pattern/Server3.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE DeriveDataTypeable #
----------------------------------------------------------------------------
* Types
----------------------------------------------------------------------------
* Guts
XXX: Why not ReaderT IO?
I thought wrapping with monad transformer makes the code slow.
But haven't benchmarked and compared, yet.... biased, not good.
| Guts of server message receiving loop.
all threads in server env will be killed.
^ Port of pattern server
^ Host of scsynth to connect
^ Protocol of scsynth to connect
^ Port of scsynth to connect
| Guts of server loop.
scsynth.
| Pattern match OSC message and send to scsynth server.
^ Environment for server
^ OSC message body
| Run new pattern.
^ Environment for server
^ Name of thread
^ Serialized pattern
| Free specified thread.
^ Environment for server
^ Offset time for sending message
^ Thread name to kill
| Free all thread in server environment.
^ Server environment
^ Offset time for sending message
| Dump info of given server environment.
| Play given patttern with new thread.
When the given pattern is finite, forked thread will update thread
status of itself in server env when finished playing the pattern.
^ Environment for server
^ Offset time
^ Name for new thread
^ Serialized pattern
sendOSC fd (notify True)
sendOSC fd' $ bundle immediately [notify False, n_free [tid]]
XXX:
When below cleanup were done, creating new thread with same name
will make unmanaged thread in ServerEnv. Commented out for
supporting creation of thread with same name.
atomically $ do
let tv = seThreads env
tmap <- readTVar tv
| Open new connection from host, port, and protocol information.
| Pause until given time when Just time was given.
| Decode compressed pattern bytestring. | |
Module : $ Header$
CopyRight : ( c ) 8c6794b6
License : :
Stability : unstable
Portability : non - portable ( GHC concurrency , DeriveDataTypeable )
Server to manage patterns , take 3 .
Using TVar instead of MVar , not using ReaderMonad .
Module : $Header$
CopyRight : (c) 8c6794b6
License : BSD3
Maintainer :
Stability : unstable
Portability : non-portable (GHC concurrency, DeriveDataTypeable)
Server to manage patterns, take 3.
Using TVar instead of MVar, not using ReaderMonad.
-}
module Sound.SC3.Lepton.Pattern.Server3 where
import Control.Concurrent
import Control.Monad
import Control.Monad.Reader
import Control.Concurrent.STM
import Control.Exception (bracket)
import Data.ByteString.Lazy (ByteString)
import Data.Data (Data, Typeable)
import Data.Binary (decode)
import Sound.OSC.FD
import Sound.SC3 (n_free, withNotifications)
import qualified Codec.Compression.Zlib as Z
import qualified Data.ByteString.Char8 as C8
import qualified Data.Foldable as F
import qualified Data.Map as M
import Sound.SC3.Lepton.Pattern
data Protocol = Tcp | Udp deriving (Eq,Show,Data,Typeable)
data ConInfo = ConInfo
{ ciHost :: String
, ciPort :: Int
, ciProtocol :: Protocol
} deriving (Eq, Show)
data Con = UDPCon UDP | TCPCon TCP
instance Transport Con where
sendOSC (UDPCon c) o = sendOSC c o
sendOSC (TCPCon c) o = sendOSC c o
recvPacket (UDPCon c) = recvPacket c
recvPacket (TCPCon c) = recvPacket c
close (UDPCon c) = close c
close (TCPCon c) = close c
data ServerEnv = ServerEnv
{ seThreads :: TVar (M.Map String ThreadInfo)
, sePort :: Int
, seLept :: UDP
, seSC :: ConInfo }
data ThreadInfo = Running ThreadId | Stopped deriving (Eq, Show)
XXX : Why using TVar instead of MVar ?
Thought STM will work better here , but not much difference .
When shutting down , side connection would be closed and
go ::
Int
-> String
-> Protocol
-> Int
-> IO ()
go lport shost sprtc sport = bracket acquire tidyup work where
acquire = do
putStrLn $ "Starting server with port " ++ show lport
tv <- atomically $ newTVar M.empty
lcon <- udpServer "127.0.0.1" lport
let scon = ConInfo shost sport sprtc
putStrLn $
concat [ "Using scsynth [host:", shost
, ", port:", show sport, ", protocol:", show sprtc, "]"]
return $ ServerEnv tv lport lcon scon
tidyup e = do
close $ seLept e
tmap <- atomically $ readTVar $ seThreads e
F.forM_ tmap $ \tinfo ->
case tinfo of
Running tid -> killThread tid
Stopped -> return ()
work = loop
Receives OSC message from side connection , sends message to
loop :: ServerEnv -> IO ()
loop env = forever $ do
msg <- recvPacket $ seLept env
handleMessage env msg
| Handle bundled and non - bundles OSC message .
handleMessage :: ServerEnv -> Packet -> IO ()
handleMessage env msg = case msg of
Packet_Bundle (Bundle t msgs) -> mapM_ (sendMsg env (Just t)) msgs
Packet_Message msg' -> sendMsg env Nothing msg'
sendMsg
:: ServerEnv
-> Maybe Time
^ Offset time of OSC message
-> Message
-> IO ()
sendMsg env t msg = case msg of
Message "/l_new" [ASCII_String name, Blob b] ->
runLNew env t (C8.unpack name) b
Message "/l_free" [ASCII_String name] ->
runLFree env t (C8.unpack name)
Message "/l_freeAll" [] -> runLFreeAll env t
Message "/l_dump" [] -> runLDump env
_ ->
putStrLn $ "Unknown: " ++ show msg
runLNew
:: ServerEnv
-> Maybe Time
^ Offset time of OSC message
-> String
-> ByteString
-> IO ()
runLNew env tm name blob = do
XXX : No gurantee for thread Map to contain un - managed threads .
Since forkIO is invoked between atomic STM actions ,
unless using unsafePerformIO , forkIO need to be called outside of
STM action .
tmap <- atomically $ readTVar $ seThreads env
let !maybeKill = case M.lookup name tmap of
Just (Running tid) -> killThread tid
_ -> return ()
tid <- forkIO $ do
maybePause tm
maybeKill
mkThread env tm name blob
atomically $ writeTVar (seThreads env) $ M.insert name (Running tid) tmap
runLFree
:: ServerEnv
-> Maybe Time
-> String
-> IO ()
runLFree env tm name = do
tmap <- atomically $ readTVar $ seThreads env
case M.lookup name tmap of
Just (Running tid) -> do
maybePause tm
killThread tid
atomically $
writeTVar (seThreads env) $ M.delete name tmap
_ -> putStrLn $ "Thread " ++ name ++ " does not exist"
runLFreeAll
:: ServerEnv
-> Maybe Time
-> IO ()
runLFreeAll env tm = do
let tv = seThreads env
tmap <- atomically $ readTVar tv
maybePause tm
F.forM_ tmap $ \tinfo -> case tinfo of
Running tid -> do
killThread tid
putStrLn $ unwords ["Thread:", show tid, "killed"]
_ -> return ()
atomically $ writeTVar tv $ M.empty
runLDump :: ServerEnv -> IO ()
runLDump env = do
tmap <- atomically $ readTVar $ seThreads env
putStrLn "========== Threads ==========="
F.forM_ (M.toList tmap) $ \(name,ti) ->
putStrLn $ name ++ ": " ++ show ti
mkThread
:: ServerEnv
-> Maybe Time
-> String
-> ByteString
-> IO ()
mkThread env time0 name blob = case decodePattern blob of
Left err -> print err
Right pat' -> do
withTransport (fromConInfo (seSC env)) $ \fd ->
let acquire = do
trid <- newNid
return (fd, trid)
tidyup (fd',trid) = do
sendOSC fd' $ n_free [trid]
close fd'
writeTVar tv ( M.delete name tmap )
work (fd',trid) = do
time' <- maybe time return time0
runReaderT (withNotifications $ runMsgFrom time' pat' trid) fd'
atomically $ do
let tv = seThreads env
tmap <- readTVar tv
writeTVar tv $ M.adjust (const Stopped) name tmap
in bracket acquire tidyup work
fromConInfo :: ConInfo -> IO Con
fromConInfo (ConInfo h p ptc) = case ptc of
Udp -> UDPCon `fmap` openUDP h p
Tcp -> TCPCon `fmap` openTCP h p
Will not pause when was given , nor given time was past .
maybePause :: Maybe Time -> IO ()
maybePause = F.mapM_ $ \time0 -> do
dt <- (time0 -) `fmap` time
let (q,_) = properFraction (dt * 1e6)
when (dt > 0) $ threadDelay q
decodePattern :: ByteString -> Either String (L () (ToOSC Double))
decodePattern = t2l . decode . Z.decompress
|
75acd96827c78d7437a61cf4df25d5032d124c7bfa07de8463fc9e1444351b55 | openbadgefactory/salava | async.clj | (ns salava.social.async
(:require [salava.social.db :as db]
[salava.core.util :refer [publish]]))
(defn subscribe [ctx]
{:event (fn [data] (db/insert-social-event! ctx data))})
| null | https://raw.githubusercontent.com/openbadgefactory/salava/97f05992406e4dcbe3c4bff75c04378d19606b61/src/clj/salava/social/async.clj | clojure | (ns salava.social.async
(:require [salava.social.db :as db]
[salava.core.util :refer [publish]]))
(defn subscribe [ctx]
{:event (fn [data] (db/insert-social-event! ctx data))})
|
|
7d8414e615d5ca57a4ddee981cc7981064f831818fce2e43695c63912801fa4a | joinr/clclojure | keywordfunc.lisp | ;;This is a legacy implementation of keywords-as-functions.
;;We'll probably revisit this.
(defpackage :clclojure.keywordfunc
(:use :common-lisp ;:clclojure.base
:common-utils)
(:export :keyfn? :key-accessor :->keyaccess :keyaccess-func :keyaccess-key :with-keyfn))
(in-package :clclojure.keywordfunc)
(defparameter keyfns (make-hash-table))
(defun keyfn? (k)
(gethash k keyfns))
;;this is the general template for implementing
;;keyword access...
( defun : a ( m ) ( gethash : a m ) )
( defun ( setf : a ) ( new - value m )
( setf ( gethash : a m )
;; new-value))
(defun key-accessor (k)
(let ((m (gensym "map"))
(v (gensym "newval")))
`(progn (defun ,k (,m) (gethash ,k ,m))
(defun (,'setf ,k) (,v ,m)
(,'setf (,'gethash ,k ,m) ,v))
( , ' setf ( gethash , ) , k )
)))
;;for localized keyaccess, i.e. inside
;;lets and friends....
(defclass keyaccess ()
((key :initarg :key :accessor keyaccess-key)
(func :accessor keyaccess-func))
(:metaclass sb-mop::funcallable-standard-class))
(defmethod initialize-instance :after ((obj keyaccess) &key)
(with-slots (key func) obj
(setf func (lambda (ht)
(gethash key ht)))
(sb-mop::set-funcallable-instance-function
obj func)
(eval (key-accessor key))
(setf (gethash key keyfns) obj)
))
;;keyaccessors print like keywords.
(defmethod print-object ((obj keyaccess) stream)
(prin1 (keyaccess-key obj) stream))
(defun ->keyaccess (k)
(or
(gethash k keyfns)
(make-instance 'keyaccess :key k)))
;;now, to get the last step of "real" keyword access, we need to
;;detect when keyword literals used, and create keyword accessors for
them . One dirty way of doing that , is to use a reader macro for
;;keywords, and ensure that every single keyword that's read has a
.
;;That's effective, maybe not efficient, since we're duplicating our
;;keywords everywhere. A more efficient, but harder to implement,
;;technique is to macroexpand and walk the code inside a unified-let*. In
;;theory, we can detect any forms used in the function position, and
;;if they're keywords, compile them into keyword accessors.
(defmacro with-keyfn (expr)
(let ((k (first expr))
)
(if (keywordp k)
(if (not (keyfn? k))
(progn (format nil "adding keyword access for: ~a " k )
(eval (key-accessor k))
`,expr))
`,expr)))
;;dumb testing
;; (defparameter ht (make-hash-table))
;; (with-keyfn (:a ht))
;; (with-keyfn (:b ht))
( setf (: a ht ) : )
( setf (: b ht ) : )
;; (with-keyfn (:a ht))
;; (with-keyfn (:b ht))
| null | https://raw.githubusercontent.com/joinr/clclojure/8b51214891c4da6dfbec393dffac70846ee1d0c5/keywordfunc.lisp | lisp | This is a legacy implementation of keywords-as-functions.
We'll probably revisit this.
:clclojure.base
this is the general template for implementing
keyword access...
new-value))
for localized keyaccess, i.e. inside
lets and friends....
keyaccessors print like keywords.
now, to get the last step of "real" keyword access, we need to
detect when keyword literals used, and create keyword accessors for
keywords, and ensure that every single keyword that's read has a
That's effective, maybe not efficient, since we're duplicating our
keywords everywhere. A more efficient, but harder to implement,
technique is to macroexpand and walk the code inside a unified-let*. In
theory, we can detect any forms used in the function position, and
if they're keywords, compile them into keyword accessors.
dumb testing
(defparameter ht (make-hash-table))
(with-keyfn (:a ht))
(with-keyfn (:b ht))
(with-keyfn (:a ht))
(with-keyfn (:b ht)) | (defpackage :clclojure.keywordfunc
:common-utils)
(:export :keyfn? :key-accessor :->keyaccess :keyaccess-func :keyaccess-key :with-keyfn))
(in-package :clclojure.keywordfunc)
(defparameter keyfns (make-hash-table))
(defun keyfn? (k)
(gethash k keyfns))
( defun : a ( m ) ( gethash : a m ) )
( defun ( setf : a ) ( new - value m )
( setf ( gethash : a m )
(defun key-accessor (k)
(let ((m (gensym "map"))
(v (gensym "newval")))
`(progn (defun ,k (,m) (gethash ,k ,m))
(defun (,'setf ,k) (,v ,m)
(,'setf (,'gethash ,k ,m) ,v))
( , ' setf ( gethash , ) , k )
)))
(defclass keyaccess ()
((key :initarg :key :accessor keyaccess-key)
(func :accessor keyaccess-func))
(:metaclass sb-mop::funcallable-standard-class))
(defmethod initialize-instance :after ((obj keyaccess) &key)
(with-slots (key func) obj
(setf func (lambda (ht)
(gethash key ht)))
(sb-mop::set-funcallable-instance-function
obj func)
(eval (key-accessor key))
(setf (gethash key keyfns) obj)
))
(defmethod print-object ((obj keyaccess) stream)
(prin1 (keyaccess-key obj) stream))
(defun ->keyaccess (k)
(or
(gethash k keyfns)
(make-instance 'keyaccess :key k)))
them . One dirty way of doing that , is to use a reader macro for
.
(defmacro with-keyfn (expr)
(let ((k (first expr))
)
(if (keywordp k)
(if (not (keyfn? k))
(progn (format nil "adding keyword access for: ~a " k )
(eval (key-accessor k))
`,expr))
`,expr)))
( setf (: a ht ) : )
( setf (: b ht ) : )
|
175f6538c9fafcbef31b748e38901512dd5b5d7102ab3da8b91e2bba75bef1ba | microsoftarchive/clj-bugsnag | core.clj | (ns clj-bugsnag.core
(:require [clj-stacktrace.core :refer [parse-exception]]
[clj-stacktrace.repl :refer [method-str]]
[clojure.java.shell :refer [sh]]
[clj-http.client :as http]
[environ.core :refer [env]]
[clojure.data.json :as json]
[clojure.repl :as repl]
[clojure.string :as string]
[clojure.walk :as walk]))
(def git-rev
(delay
(try
(string/trim (:out (sh "git" "rev-parse" "HEAD")))
(catch Exception ex "git revision not available"))))
(defn- find-source-snippet
[around, function-name]
(try
(let [fn-sym (symbol function-name)
fn-var (find-var fn-sym)
source (repl/source-fn fn-sym)
start (-> fn-var meta :line)
indexed-lines (map-indexed (fn [i, line]
[(+ i start), (string/trimr line)])
(string/split-lines source))]
(into {} (filter #(<= (- around 3) (first %) (+ around 3)) indexed-lines)))
(catch Exception ex
nil)))
(defn- transform-stacktrace
[trace-elems project-ns]
(try
(vec (for [{:keys [file line ns] :as elem} trace-elems
:let [project? (.startsWith (or ns "_") project-ns)
method (method-str elem)
code (when (.endsWith (or file "") ".clj")
(find-source-snippet line (.replace (or method "") "[fn]" "")))]]
{:file file,
:lineNumber line,
:method method,
:inProject project?,
:code code}))
(catch Exception ex
[{:file "clj-bugsnag/core.clj",
:lineNumber 1,
:code {1 (str ex)
2 "thrown while building stack trace."}}])))
(defn- stringify
[thing]
(if (or (map? thing) (string? thing) (number? thing) (sequential? thing))
thing
(str thing)))
(defn exception->json
[exception options]
(let [ex (parse-exception exception)
class-name (.getName (:class ex))
project-ns (get options :project-ns "\000")
stacktrace (transform-stacktrace (:trace-elems ex) project-ns)
base-meta (if-let [d (ex-data exception)]
{"ex–data" d}
{})]
{:apiKey (:api-key options (env :bugsnag-key))
:notifier {:name "clj-bugsnag"
:version "0.2.2"
:url "-bugsnag"}
:events [{:payloadVersion "2"
:exceptions [{:errorClass class-name
:message (:message ex)
:stacktrace stacktrace}]
:context (:context options)
:groupingHash (or (:group options)
(if (isa? (type exception) clojure.lang.ExceptionInfo)
(:message ex)
class-name))
:severity (or (:severity options) "error")
:user (:user options)
:app {:version (if (contains? options :version)
(:version options)
@git-rev)
:releaseStage (or (:environment options) "production")}
:device {:hostname (.. java.net.InetAddress getLocalHost getHostName)}
:metaData (walk/postwalk stringify (merge base-meta (:meta options)))}]}))
(defn notify
"Main interface for manually reporting exceptions.
When not :api-key is provided in options,
tries to load BUGSNAG_KEY var from enviroment."
([exception]
(notify exception nil))
([exception, options]
(let [params (exception->json exception options)
url "/"]
(http/post url {:form-params params
:content-type :json}))))
| null | https://raw.githubusercontent.com/microsoftarchive/clj-bugsnag/28aa693d548720fb36e1adfd968e413639be30e8/src/clj_bugsnag/core.clj | clojure | (ns clj-bugsnag.core
(:require [clj-stacktrace.core :refer [parse-exception]]
[clj-stacktrace.repl :refer [method-str]]
[clojure.java.shell :refer [sh]]
[clj-http.client :as http]
[environ.core :refer [env]]
[clojure.data.json :as json]
[clojure.repl :as repl]
[clojure.string :as string]
[clojure.walk :as walk]))
(def git-rev
(delay
(try
(string/trim (:out (sh "git" "rev-parse" "HEAD")))
(catch Exception ex "git revision not available"))))
(defn- find-source-snippet
[around, function-name]
(try
(let [fn-sym (symbol function-name)
fn-var (find-var fn-sym)
source (repl/source-fn fn-sym)
start (-> fn-var meta :line)
indexed-lines (map-indexed (fn [i, line]
[(+ i start), (string/trimr line)])
(string/split-lines source))]
(into {} (filter #(<= (- around 3) (first %) (+ around 3)) indexed-lines)))
(catch Exception ex
nil)))
(defn- transform-stacktrace
[trace-elems project-ns]
(try
(vec (for [{:keys [file line ns] :as elem} trace-elems
:let [project? (.startsWith (or ns "_") project-ns)
method (method-str elem)
code (when (.endsWith (or file "") ".clj")
(find-source-snippet line (.replace (or method "") "[fn]" "")))]]
{:file file,
:lineNumber line,
:method method,
:inProject project?,
:code code}))
(catch Exception ex
[{:file "clj-bugsnag/core.clj",
:lineNumber 1,
:code {1 (str ex)
2 "thrown while building stack trace."}}])))
(defn- stringify
[thing]
(if (or (map? thing) (string? thing) (number? thing) (sequential? thing))
thing
(str thing)))
(defn exception->json
[exception options]
(let [ex (parse-exception exception)
class-name (.getName (:class ex))
project-ns (get options :project-ns "\000")
stacktrace (transform-stacktrace (:trace-elems ex) project-ns)
base-meta (if-let [d (ex-data exception)]
{"ex–data" d}
{})]
{:apiKey (:api-key options (env :bugsnag-key))
:notifier {:name "clj-bugsnag"
:version "0.2.2"
:url "-bugsnag"}
:events [{:payloadVersion "2"
:exceptions [{:errorClass class-name
:message (:message ex)
:stacktrace stacktrace}]
:context (:context options)
:groupingHash (or (:group options)
(if (isa? (type exception) clojure.lang.ExceptionInfo)
(:message ex)
class-name))
:severity (or (:severity options) "error")
:user (:user options)
:app {:version (if (contains? options :version)
(:version options)
@git-rev)
:releaseStage (or (:environment options) "production")}
:device {:hostname (.. java.net.InetAddress getLocalHost getHostName)}
:metaData (walk/postwalk stringify (merge base-meta (:meta options)))}]}))
(defn notify
"Main interface for manually reporting exceptions.
When not :api-key is provided in options,
tries to load BUGSNAG_KEY var from enviroment."
([exception]
(notify exception nil))
([exception, options]
(let [params (exception->json exception options)
url "/"]
(http/post url {:form-params params
:content-type :json}))))
|
|
adb7cbc2c72f3a12fea1c521d16789daf65e4f5785b87a92569a75123fbd6f00 | kupl/LearnML | patch.ml | type formula =
| True
| False
| Not of formula
| AndAlso of (formula * formula)
| OrElse of (formula * formula)
| Imply of (formula * formula)
| Equal of (exp * exp)
and exp = Num of int | Plus of (exp * exp) | Minus of (exp * exp)
let rec eval_op (op : exp) : int =
match op with
| Num a -> a
| Minus (exp1, exp2) -> eval_op exp1 - eval_op exp2
| Plus (exp1, exp2) -> eval_op exp1 + eval_op exp2
and eval (f : formula) : bool =
match f with
| True -> true
| False -> false
| Not f -> not (eval f)
| AndAlso (f1, f2) -> eval f1 && eval f2
| OrElse (f1, f2) -> eval f1 || eval f2
| Imply (f1, f2) -> if eval f1 = false || eval f2 = true then true else false
| Equal (exp1, exp2) -> if eval_op exp1 = eval_op exp2 then true else false
| null | https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/formula/sub50/patch.ml | ocaml | type formula =
| True
| False
| Not of formula
| AndAlso of (formula * formula)
| OrElse of (formula * formula)
| Imply of (formula * formula)
| Equal of (exp * exp)
and exp = Num of int | Plus of (exp * exp) | Minus of (exp * exp)
let rec eval_op (op : exp) : int =
match op with
| Num a -> a
| Minus (exp1, exp2) -> eval_op exp1 - eval_op exp2
| Plus (exp1, exp2) -> eval_op exp1 + eval_op exp2
and eval (f : formula) : bool =
match f with
| True -> true
| False -> false
| Not f -> not (eval f)
| AndAlso (f1, f2) -> eval f1 && eval f2
| OrElse (f1, f2) -> eval f1 || eval f2
| Imply (f1, f2) -> if eval f1 = false || eval f2 = true then true else false
| Equal (exp1, exp2) -> if eval_op exp1 = eval_op exp2 then true else false
|
|
31da0369bfd8b4b2cde310db2dd80691c68151c7a2ec0220a83f1cb55381542d | skinkade/uniformity | rsa.cljs | (ns uniformity.internals.js.rsa
(:require [uniformity.internals.js.node-browser-compat :refer [crypto-type crypto]]
[cljs.core.async :refer [go chan <! put!]]
[cljs.core.async.interop :refer [p->c]]
[async-error.core :refer-macros [go-try <?]]))
(def subtle (.-subtle crypto))
(defn browser-rsa-generate-keypair
[^number bits]
(go-try
(when-not (or (= bits 2048)
(= bits 3072)
(= bits 4092))
(throw (js/Error. "RSA key size must be one of 2048, 3072, or 4096")))
(let [pub-chan (chan 1)
priv-chan (chan 1)
params (clj->js {"name" "RSA-OAEP"
"modulusLength" bits
"publicExponent" (js/Uint8Array. [0x01, 0x00, 0x01])
"hash" "SHA-256"})
extractable true
key-usages ["encrypt" "decrypt"]]
(-> (.generateKey subtle
params
extractable
key-usages)
(.then (fn [keypair]
((-> (.exportKey ^Object subtle
"spki"
(.-publicKey keypair))
(.then (fn [key] (js/Uint8Array. key)))
(.then (fn [key] (put! pub-chan key))))
(-> (.exportKey subtle
"pkcs8"
(.-privateKey keypair))
(.then (fn [key] (js/Uint8Array. key)))
(.then (fn [key] (put! priv-chan key))))))))
{:public (<? pub-chan)
:private (<? priv-chan)})))
(defn browser-rsa-encrypt
[^js/Uint8Array plaintext
^js/Uint8Array pubkey]
(-> (.importKey subtle
"spki"
pubkey
(clj->js {"name" "RSA-OAEP"
"hash" "SHA-256"})
true
["encrypt"])
(.then (fn [cryptokey]
(.encrypt ^Object subtle
(clj->js {"name" "RSA-OAEP"})
cryptokey
plaintext)))
(.then (fn [ciphertext] (js/Uint8Array. ciphertext)))
p->c))
(defn browser-rsa-decrypt
[^js/Uint8Array ciphertext
^js/Uint8Array pubkey]
(-> (.importKey subtle
"pkcs8"
pubkey
(clj->js {"name" "RSA-OAEP"
"hash" "SHA-256"})
true
["decrypt"])
(.then (fn [cryptokey]
(.decrypt ^Object subtle
(clj->js {"name" "RSA-OAEP"})
cryptokey
ciphertext)))
(.then (fn [plaintext] (js/Uint8Array. plaintext)))
p->c))
(defn node-rsa-generate-keypair
[^number bits]
(go-try
(when-not (or (= bits 2048)
(= bits 3072)
(= bits 4092))
(throw (js/Error. "RSA key size must be one of 2048, 3072, or 4096")))
(let [pubkey-chan (chan 1)
privkey-chan (chan 1)
err-chan (chan 1)]
(.generateKeyPair ^Object crypto
"rsa"
(clj->js {"modulusLength" bits})
(fn [err pubkey privkey]
(if (some? err)
(put! err-chan err)
(do (put! err-chan false)
(->> (.export pubkey (clj->js {"type" "spki"
"format" "der"}))
js/Uint8Array.
(put! pubkey-chan))
(->> (.export privkey (clj->js {"type" "pkcs8"
"format" "der"}))
js/Uint8Array.
(put! privkey-chan))))))
(<? err-chan)
{:public (<? pubkey-chan)
:private (<? privkey-chan)})))
(defn node-rsa-encrypt
[^js/Uint8Array plaintext
^js/Uint8Array pubkey]
(go-try
(let [key-opts (clj->js {"key" pubkey
"format" "der"
"type" "spki"})
crypto-pubkey (.createPublicKey ^Object crypto key-opts)
rsa-opts (clj->js {"key" crypto-pubkey
"oaepHash" "sha256"})
ciphertext (.publicEncrypt ^Object crypto rsa-opts plaintext)]
(js/Uint8Array. ciphertext))))
(defn node-rsa-decrypt
^js/Uint8Array
[^js/Uint8Array ciphertext
^js/Uint8Array privkey]
(go-try
(let [key-options (clj->js {"key" privkey
"format" "der"
"type" "pkcs8"})
privkey (.createPrivateKey ^Object crypto key-options)
rsa-opts (clj->js {"key" privkey
"oaepHash" "sha256"})]
(js/Uint8Array. (.privateDecrypt ^Object crypto rsa-opts ciphertext)))))
(def rsa-generate-keypair
(if (= :browser crypto-type)
#'browser-rsa-generate-keypair
#'node-rsa-generate-keypair))
(def rsa-encrypt
(if (= :browser crypto-type)
#'browser-rsa-encrypt
#'node-rsa-encrypt))
(def rsa-decrypt
(if (= :browser crypto-type)
#'browser-rsa-decrypt
#'node-rsa-decrypt))
| null | https://raw.githubusercontent.com/skinkade/uniformity/e9d007a7be833e70b4358c02700fd81866de775a/src/uniformity/internals/js/rsa.cljs | clojure | (ns uniformity.internals.js.rsa
(:require [uniformity.internals.js.node-browser-compat :refer [crypto-type crypto]]
[cljs.core.async :refer [go chan <! put!]]
[cljs.core.async.interop :refer [p->c]]
[async-error.core :refer-macros [go-try <?]]))
(def subtle (.-subtle crypto))
(defn browser-rsa-generate-keypair
[^number bits]
(go-try
(when-not (or (= bits 2048)
(= bits 3072)
(= bits 4092))
(throw (js/Error. "RSA key size must be one of 2048, 3072, or 4096")))
(let [pub-chan (chan 1)
priv-chan (chan 1)
params (clj->js {"name" "RSA-OAEP"
"modulusLength" bits
"publicExponent" (js/Uint8Array. [0x01, 0x00, 0x01])
"hash" "SHA-256"})
extractable true
key-usages ["encrypt" "decrypt"]]
(-> (.generateKey subtle
params
extractable
key-usages)
(.then (fn [keypair]
((-> (.exportKey ^Object subtle
"spki"
(.-publicKey keypair))
(.then (fn [key] (js/Uint8Array. key)))
(.then (fn [key] (put! pub-chan key))))
(-> (.exportKey subtle
"pkcs8"
(.-privateKey keypair))
(.then (fn [key] (js/Uint8Array. key)))
(.then (fn [key] (put! priv-chan key))))))))
{:public (<? pub-chan)
:private (<? priv-chan)})))
(defn browser-rsa-encrypt
[^js/Uint8Array plaintext
^js/Uint8Array pubkey]
(-> (.importKey subtle
"spki"
pubkey
(clj->js {"name" "RSA-OAEP"
"hash" "SHA-256"})
true
["encrypt"])
(.then (fn [cryptokey]
(.encrypt ^Object subtle
(clj->js {"name" "RSA-OAEP"})
cryptokey
plaintext)))
(.then (fn [ciphertext] (js/Uint8Array. ciphertext)))
p->c))
(defn browser-rsa-decrypt
[^js/Uint8Array ciphertext
^js/Uint8Array pubkey]
(-> (.importKey subtle
"pkcs8"
pubkey
(clj->js {"name" "RSA-OAEP"
"hash" "SHA-256"})
true
["decrypt"])
(.then (fn [cryptokey]
(.decrypt ^Object subtle
(clj->js {"name" "RSA-OAEP"})
cryptokey
ciphertext)))
(.then (fn [plaintext] (js/Uint8Array. plaintext)))
p->c))
(defn node-rsa-generate-keypair
[^number bits]
(go-try
(when-not (or (= bits 2048)
(= bits 3072)
(= bits 4092))
(throw (js/Error. "RSA key size must be one of 2048, 3072, or 4096")))
(let [pubkey-chan (chan 1)
privkey-chan (chan 1)
err-chan (chan 1)]
(.generateKeyPair ^Object crypto
"rsa"
(clj->js {"modulusLength" bits})
(fn [err pubkey privkey]
(if (some? err)
(put! err-chan err)
(do (put! err-chan false)
(->> (.export pubkey (clj->js {"type" "spki"
"format" "der"}))
js/Uint8Array.
(put! pubkey-chan))
(->> (.export privkey (clj->js {"type" "pkcs8"
"format" "der"}))
js/Uint8Array.
(put! privkey-chan))))))
(<? err-chan)
{:public (<? pubkey-chan)
:private (<? privkey-chan)})))
(defn node-rsa-encrypt
[^js/Uint8Array plaintext
^js/Uint8Array pubkey]
(go-try
(let [key-opts (clj->js {"key" pubkey
"format" "der"
"type" "spki"})
crypto-pubkey (.createPublicKey ^Object crypto key-opts)
rsa-opts (clj->js {"key" crypto-pubkey
"oaepHash" "sha256"})
ciphertext (.publicEncrypt ^Object crypto rsa-opts plaintext)]
(js/Uint8Array. ciphertext))))
(defn node-rsa-decrypt
^js/Uint8Array
[^js/Uint8Array ciphertext
^js/Uint8Array privkey]
(go-try
(let [key-options (clj->js {"key" privkey
"format" "der"
"type" "pkcs8"})
privkey (.createPrivateKey ^Object crypto key-options)
rsa-opts (clj->js {"key" privkey
"oaepHash" "sha256"})]
(js/Uint8Array. (.privateDecrypt ^Object crypto rsa-opts ciphertext)))))
(def rsa-generate-keypair
(if (= :browser crypto-type)
#'browser-rsa-generate-keypair
#'node-rsa-generate-keypair))
(def rsa-encrypt
(if (= :browser crypto-type)
#'browser-rsa-encrypt
#'node-rsa-encrypt))
(def rsa-decrypt
(if (= :browser crypto-type)
#'browser-rsa-decrypt
#'node-rsa-decrypt))
|
|
a4b9baefd4f586c09eba63b49914aa3d1b5c9666ab8efdafb70827a169eb4529 | AccelerateHS/accelerate | Stats.hs | # LANGUAGE CPP #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
-- |
-- Module : Data.Array.Accelerate.Debug.Internal.Stats
Copyright : [ 2008 .. 2020 ] The Accelerate Team
-- License : BSD3
--
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC extensions )
--
-- Tick-count statistics collection of the compiler passes, for debugging
-- purposes.
--
module Data.Array.Accelerate.Debug.Internal.Stats (
simplCount, resetSimplCount, dumpSimplStats,
inline, ruleFired, knownBranch, caseElim, caseDefault, betaReduce, substitution, simplifierDone, fusionDone,
) where
import Data.Array.Accelerate.Debug.Internal.Flags
import Data.Array.Accelerate.Debug.Internal.Trace
import Data.Function ( on )
import Data.IORef
import Data.List ( groupBy, sortBy )
import Data.Map ( Map )
import Data.Ord ( comparing )
import Data.Text ( Text )
import Data.Text.Lazy.Builder
import Formatting
import Prettyprinter hiding ( annotate, Doc )
import Prettyprinter.Internal ( SimpleDocStream(..), textSpaces )
import Prettyprinter.Render.Util.Panic ( panicUncaughtFail )
import System.IO.Unsafe
import qualified Data.Map as Map
import qualified Prettyprinter as Pretty
-- Recording statistics
-- --------------------
ruleFired, inline, knownBranch, caseElim, caseDefault, betaReduce, substitution :: Text -> a -> a
inline = annotate Inline
ruleFired = annotate RuleFired
knownBranch = annotate KnownBranch
caseElim = annotate CaseElim
caseDefault = annotate CaseDefault
betaReduce = annotate BetaReduce
substitution = annotate Substitution
simplifierDone, fusionDone :: a -> a
simplifierDone = tick SimplifierDone
fusionDone = tick FusionDone
-- Add an entry to the statistics counters
--
tick :: Tick -> a -> a
#ifdef ACCELERATE_DEBUG
# NOINLINE tick #
tick t expr = unsafeDupablePerformIO $ do
modifyIORef' statistics (simplTick t)
return expr
#else
# INLINE tick #
tick _ expr = expr
#endif
-- Add an entry to the statistics counters with an annotation
--
annotate :: (Id -> Tick) -> Text -> a -> a
annotate name ctx = tick (name (Id ctx))
-- Simplifier counts
-- -----------------
data SimplStats
= Simple {-# UNPACK #-} !Int -- when we don't want detailed stats
| Detail {
ticks :: {-# UNPACK #-} !Int, -- total ticks
details :: !TickCount -- how many of each type
}
instance Show SimplStats where
show = show . pprSimplCount
-- Stores the current statistics counters
--
# NOINLINE statistics #
statistics :: IORef SimplStats
statistics = unsafePerformIO $ newIORef =<< initSimplCount
Initialise the statistics counters . If we are dumping the stats
-- (-ddump-simpl-stats) record extra information, else just a total tick count.
--
initSimplCount :: IO SimplStats
#ifdef ACCELERATE_DEBUG
initSimplCount = do
d <- getFlag dump_simpl_stats
return $! if d then Detail { ticks = 0, details = Map.empty }
else Simple 0
#else
initSimplCount = return $! Simple 0
#endif
-- Reset the statistics counters. Do this at the beginning at each HOAS -> de
Bruijn conversion + optimisation pass .
--
resetSimplCount :: IO ()
#ifdef ACCELERATE_DEBUG
resetSimplCount = writeIORef statistics =<< initSimplCount
#else
resetSimplCount = return ()
#endif
-- Display simplifier statistics. The counts are reset afterwards.
--
# INLINEABLE dumpSimplStats #
dumpSimplStats :: IO ()
#ifdef ACCELERATE_DEBUG
dumpSimplStats = do
when dump_simpl_stats $ do
stats <- simplCount
putTraceMsg builder (render (layoutPretty defaultLayoutOptions stats))
resetSimplCount
where
-- stolen from Data.Text.Prettyprint.Doc.Render.Text.renderLazy
render = \case
SFail -> panicUncaughtFail
SEmpty -> mempty
SChar c rest -> singleton c <> render rest
SText _l t rest -> fromText t <> render rest
SLine i rest -> singleton '\n' <> (fromText (textSpaces i) <> render rest)
SAnnPush _ann rest -> render rest
SAnnPop rest -> render rest
#else
dumpSimplStats = return ()
#endif
-- Tick a counter
--
simplTick :: Tick -> SimplStats -> SimplStats
simplTick _ (Simple n) = Simple (n+1)
simplTick t (Detail n dts) = Detail (n+1) (dts `addTick` t)
Pretty print the tick counts . Remarkably reminiscent of GHC style ...
--
pprSimplCount :: SimplStats -> Doc
pprSimplCount (Simple n) = "Total ticks:" <+> pretty n
pprSimplCount (Detail n dts)
= vcat [ "Total ticks:" <+> pretty n
, mempty
, pprTickCount dts
]
simplCount :: IO Doc
simplCount = pprSimplCount `fmap` readIORef statistics
-- Ticks
-- -----
type Doc = Pretty.Doc ()
type TickCount = Map Tick Int
data Id = Id Text
deriving (Eq, Ord)
data Tick
= Inline Id
| RuleFired Id
| KnownBranch Id
| CaseElim Id
| CaseDefault Id
| BetaReduce Id
| Substitution Id
-- tick at each iteration
| SimplifierDone
| FusionDone
deriving (Eq, Ord)
addTick :: TickCount -> Tick -> TickCount
addTick tc t =
Map.alter f t tc
where
f Nothing = Just 1
f (Just x) = let x' = x+1 in x' `seq` Just x'
pprTickCount :: TickCount -> Doc
pprTickCount counts =
vcat (map pprTickGroup groups)
where
groups = groupBy sameTag (Map.toList counts)
sameTag = (==) `on` tickToTag . fst
pprTickGroup :: [(Tick,Int)] -> Doc
pprTickGroup [] = error "pprTickGroup"
pprTickGroup grp =
hang 2 (vcat $ (pretty groupTotal <+> groupName)
: [ pretty n <+> pprTickCtx t | (t,n) <- sortBy (flip (comparing snd)) grp ])
where
groupName = tickToStr (fst (head grp))
groupTotal = sum [n | (_,n) <- grp]
tickToTag :: Tick -> Int
tickToTag Inline{} = 0
tickToTag RuleFired{} = 1
tickToTag KnownBranch{} = 2
tickToTag CaseElim{} = 3
tickToTag CaseDefault{} = 4
tickToTag BetaReduce{} = 5
tickToTag Substitution{} = 6
tickToTag SimplifierDone = 99
tickToTag FusionDone = 100
tickToStr :: Tick -> Doc
tickToStr Inline{} = "Inline"
tickToStr RuleFired{} = "RuleFired"
tickToStr KnownBranch{} = "KnownBranch"
tickToStr CaseElim{} = "CaseElim"
tickToStr CaseDefault{} = "CaseDefault"
tickToStr BetaReduce{} = "BetaReduce"
tickToStr Substitution{} = "Substitution"
tickToStr SimplifierDone = "SimplifierDone"
tickToStr FusionDone = "FusionDone"
pprTickCtx :: Tick -> Doc
pprTickCtx (Inline v) = pprId v
pprTickCtx (RuleFired v) = pprId v
pprTickCtx (KnownBranch v) = pprId v
pprTickCtx (CaseElim v) = pprId v
pprTickCtx (CaseDefault v) = pprId v
pprTickCtx (BetaReduce v) = pprId v
pprTickCtx (Substitution v) = pprId v
pprTickCtx SimplifierDone = mempty
pprTickCtx FusionDone = mempty
pprId :: Id -> Doc
pprId (Id s) = pretty s
| null | https://raw.githubusercontent.com/AccelerateHS/accelerate/80a9d9aa13609f895540d4859c0a8691cff6d2e3/src/Data/Array/Accelerate/Debug/Internal/Stats.hs | haskell | # LANGUAGE OverloadedStrings #
|
Module : Data.Array.Accelerate.Debug.Internal.Stats
License : BSD3
Stability : experimental
Tick-count statistics collection of the compiler passes, for debugging
purposes.
Recording statistics
--------------------
Add an entry to the statistics counters
Add an entry to the statistics counters with an annotation
Simplifier counts
-----------------
# UNPACK #
when we don't want detailed stats
# UNPACK #
total ticks
how many of each type
Stores the current statistics counters
(-ddump-simpl-stats) record extra information, else just a total tick count.
Reset the statistics counters. Do this at the beginning at each HOAS -> de
Display simplifier statistics. The counts are reset afterwards.
stolen from Data.Text.Prettyprint.Doc.Render.Text.renderLazy
Tick a counter
Ticks
-----
tick at each iteration | # LANGUAGE CPP #
# LANGUAGE LambdaCase #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
Copyright : [ 2008 .. 2020 ] The Accelerate Team
Maintainer : < >
Portability : non - portable ( GHC extensions )
module Data.Array.Accelerate.Debug.Internal.Stats (
simplCount, resetSimplCount, dumpSimplStats,
inline, ruleFired, knownBranch, caseElim, caseDefault, betaReduce, substitution, simplifierDone, fusionDone,
) where
import Data.Array.Accelerate.Debug.Internal.Flags
import Data.Array.Accelerate.Debug.Internal.Trace
import Data.Function ( on )
import Data.IORef
import Data.List ( groupBy, sortBy )
import Data.Map ( Map )
import Data.Ord ( comparing )
import Data.Text ( Text )
import Data.Text.Lazy.Builder
import Formatting
import Prettyprinter hiding ( annotate, Doc )
import Prettyprinter.Internal ( SimpleDocStream(..), textSpaces )
import Prettyprinter.Render.Util.Panic ( panicUncaughtFail )
import System.IO.Unsafe
import qualified Data.Map as Map
import qualified Prettyprinter as Pretty
ruleFired, inline, knownBranch, caseElim, caseDefault, betaReduce, substitution :: Text -> a -> a
inline = annotate Inline
ruleFired = annotate RuleFired
knownBranch = annotate KnownBranch
caseElim = annotate CaseElim
caseDefault = annotate CaseDefault
betaReduce = annotate BetaReduce
substitution = annotate Substitution
simplifierDone, fusionDone :: a -> a
simplifierDone = tick SimplifierDone
fusionDone = tick FusionDone
tick :: Tick -> a -> a
#ifdef ACCELERATE_DEBUG
# NOINLINE tick #
tick t expr = unsafeDupablePerformIO $ do
modifyIORef' statistics (simplTick t)
return expr
#else
# INLINE tick #
tick _ expr = expr
#endif
annotate :: (Id -> Tick) -> Text -> a -> a
annotate name ctx = tick (name (Id ctx))
data SimplStats
| Detail {
}
instance Show SimplStats where
show = show . pprSimplCount
# NOINLINE statistics #
statistics :: IORef SimplStats
statistics = unsafePerformIO $ newIORef =<< initSimplCount
Initialise the statistics counters . If we are dumping the stats
initSimplCount :: IO SimplStats
#ifdef ACCELERATE_DEBUG
initSimplCount = do
d <- getFlag dump_simpl_stats
return $! if d then Detail { ticks = 0, details = Map.empty }
else Simple 0
#else
initSimplCount = return $! Simple 0
#endif
Bruijn conversion + optimisation pass .
resetSimplCount :: IO ()
#ifdef ACCELERATE_DEBUG
resetSimplCount = writeIORef statistics =<< initSimplCount
#else
resetSimplCount = return ()
#endif
# INLINEABLE dumpSimplStats #
dumpSimplStats :: IO ()
#ifdef ACCELERATE_DEBUG
dumpSimplStats = do
when dump_simpl_stats $ do
stats <- simplCount
putTraceMsg builder (render (layoutPretty defaultLayoutOptions stats))
resetSimplCount
where
render = \case
SFail -> panicUncaughtFail
SEmpty -> mempty
SChar c rest -> singleton c <> render rest
SText _l t rest -> fromText t <> render rest
SLine i rest -> singleton '\n' <> (fromText (textSpaces i) <> render rest)
SAnnPush _ann rest -> render rest
SAnnPop rest -> render rest
#else
dumpSimplStats = return ()
#endif
simplTick :: Tick -> SimplStats -> SimplStats
simplTick _ (Simple n) = Simple (n+1)
simplTick t (Detail n dts) = Detail (n+1) (dts `addTick` t)
Pretty print the tick counts . Remarkably reminiscent of GHC style ...
pprSimplCount :: SimplStats -> Doc
pprSimplCount (Simple n) = "Total ticks:" <+> pretty n
pprSimplCount (Detail n dts)
= vcat [ "Total ticks:" <+> pretty n
, mempty
, pprTickCount dts
]
simplCount :: IO Doc
simplCount = pprSimplCount `fmap` readIORef statistics
type Doc = Pretty.Doc ()
type TickCount = Map Tick Int
data Id = Id Text
deriving (Eq, Ord)
data Tick
= Inline Id
| RuleFired Id
| KnownBranch Id
| CaseElim Id
| CaseDefault Id
| BetaReduce Id
| Substitution Id
| SimplifierDone
| FusionDone
deriving (Eq, Ord)
addTick :: TickCount -> Tick -> TickCount
addTick tc t =
Map.alter f t tc
where
f Nothing = Just 1
f (Just x) = let x' = x+1 in x' `seq` Just x'
pprTickCount :: TickCount -> Doc
pprTickCount counts =
vcat (map pprTickGroup groups)
where
groups = groupBy sameTag (Map.toList counts)
sameTag = (==) `on` tickToTag . fst
pprTickGroup :: [(Tick,Int)] -> Doc
pprTickGroup [] = error "pprTickGroup"
pprTickGroup grp =
hang 2 (vcat $ (pretty groupTotal <+> groupName)
: [ pretty n <+> pprTickCtx t | (t,n) <- sortBy (flip (comparing snd)) grp ])
where
groupName = tickToStr (fst (head grp))
groupTotal = sum [n | (_,n) <- grp]
tickToTag :: Tick -> Int
tickToTag Inline{} = 0
tickToTag RuleFired{} = 1
tickToTag KnownBranch{} = 2
tickToTag CaseElim{} = 3
tickToTag CaseDefault{} = 4
tickToTag BetaReduce{} = 5
tickToTag Substitution{} = 6
tickToTag SimplifierDone = 99
tickToTag FusionDone = 100
tickToStr :: Tick -> Doc
tickToStr Inline{} = "Inline"
tickToStr RuleFired{} = "RuleFired"
tickToStr KnownBranch{} = "KnownBranch"
tickToStr CaseElim{} = "CaseElim"
tickToStr CaseDefault{} = "CaseDefault"
tickToStr BetaReduce{} = "BetaReduce"
tickToStr Substitution{} = "Substitution"
tickToStr SimplifierDone = "SimplifierDone"
tickToStr FusionDone = "FusionDone"
pprTickCtx :: Tick -> Doc
pprTickCtx (Inline v) = pprId v
pprTickCtx (RuleFired v) = pprId v
pprTickCtx (KnownBranch v) = pprId v
pprTickCtx (CaseElim v) = pprId v
pprTickCtx (CaseDefault v) = pprId v
pprTickCtx (BetaReduce v) = pprId v
pprTickCtx (Substitution v) = pprId v
pprTickCtx SimplifierDone = mempty
pprTickCtx FusionDone = mempty
pprId :: Id -> Doc
pprId (Id s) = pretty s
|
fb06458001cf931afa9d5d73feeb4d75b84f7484854ed3178cf139f7d643482e | mzp/coq-ruby | gset.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
$ I d : gset.ml 5920 2004 - 07 - 16 20:01:26Z herbelin $
(* Sets using the generic comparison function of ocaml. Code borrowed from
the ocaml standard library. *)
type 'a t = Empty | Node of 'a t * 'a * 'a t * int
Sets are represented by balanced binary trees ( the heights of the
children differ by at most 2
children differ by at most 2 *)
let height = function
Empty -> 0
| Node(_, _, _, h) -> h
Creates a new node with left son l , value x and right son and r must be balanced and | height l - height r | < = 2 .
Inline expansion of height for better speed .
l and r must be balanced and | height l - height r | <= 2.
Inline expansion of height for better speed. *)
let create l x r =
let hl = match l with Empty -> 0 | Node(_,_,_,h) -> h in
let hr = match r with Empty -> 0 | Node(_,_,_,h) -> h in
Node(l, x, r, (if hl >= hr then hl + 1 else hr + 1))
Same as create , but performs one step of rebalancing if necessary .
Assumes l and .
Inline expansion of create for better speed in the most frequent case
where no rebalancing is required .
Assumes l and r balanced.
Inline expansion of create for better speed in the most frequent case
where no rebalancing is required. *)
let bal l x r =
let hl = match l with Empty -> 0 | Node(_,_,_,h) -> h in
let hr = match r with Empty -> 0 | Node(_,_,_,h) -> h in
if hl > hr + 2 then begin
match l with
Empty -> invalid_arg "Set.bal"
| Node(ll, lv, lr, _) ->
if height ll >= height lr then
create ll lv (create lr x r)
else begin
match lr with
Empty -> invalid_arg "Set.bal"
| Node(lrl, lrv, lrr, _)->
create (create ll lv lrl) lrv (create lrr x r)
end
end else if hr > hl + 2 then begin
match r with
Empty -> invalid_arg "Set.bal"
| Node(rl, rv, rr, _) ->
if height rr >= height rl then
create (create l x rl) rv rr
else begin
match rl with
Empty -> invalid_arg "Set.bal"
| Node(rll, rlv, rlr, _) ->
create (create l x rll) rlv (create rlr rv rr)
end
end else
Node(l, x, r, (if hl >= hr then hl + 1 else hr + 1))
Same as bal , but repeat rebalancing until the final result
is balanced .
is balanced. *)
let rec join l x r =
match bal l x r with
Empty -> invalid_arg "Set.join"
| Node(l', x', r', _) as t' ->
let d = height l' - height r' in
if d < -2 or d > 2 then join l' x' r' else t'
Merge two trees l and r into one .
All elements of l must precede the elements of r.
Assumes | height l - height r | < = 2 .
All elements of l must precede the elements of r.
Assumes | height l - height r | <= 2. *)
let rec merge t1 t2 =
match (t1, t2) with
(Empty, t) -> t
| (t, Empty) -> t
| (Node(l1, v1, r1, h1), Node(l2, v2, r2, h2)) ->
bal l1 v1 (bal (merge r1 l2) v2 r2)
(* Same as merge, but does not assume anything about l and r. *)
let rec concat t1 t2 =
match (t1, t2) with
(Empty, t) -> t
| (t, Empty) -> t
| (Node(l1, v1, r1, h1), Node(l2, v2, r2, h2)) ->
join l1 v1 (join (concat r1 l2) v2 r2)
(* Splitting *)
let rec split x = function
Empty ->
(Empty, None, Empty)
| Node(l, v, r, _) ->
let c = Pervasives.compare x v in
if c = 0 then (l, Some v, r)
else if c < 0 then
let (ll, vl, rl) = split x l in (ll, vl, join rl v r)
else
let (lr, vr, rr) = split x r in (join l v lr, vr, rr)
(* Implementation of the set operations *)
let empty = Empty
let is_empty = function Empty -> true | _ -> false
let rec mem x = function
Empty -> false
| Node(l, v, r, _) ->
let c = Pervasives.compare x v in
c = 0 || mem x (if c < 0 then l else r)
let rec add x = function
Empty -> Node(Empty, x, Empty, 1)
| Node(l, v, r, _) as t ->
let c = Pervasives.compare x v in
if c = 0 then t else
if c < 0 then bal (add x l) v r else bal l v (add x r)
let singleton x = Node(Empty, x, Empty, 1)
let rec remove x = function
Empty -> Empty
| Node(l, v, r, _) ->
let c = Pervasives.compare x v in
if c = 0 then merge l r else
if c < 0 then bal (remove x l) v r else bal l v (remove x r)
let rec union s1 s2 =
match (s1, s2) with
(Empty, t2) -> t2
| (t1, Empty) -> t1
| (Node(l1, v1, r1, h1), Node(l2, v2, r2, h2)) ->
if h1 >= h2 then
if h2 = 1 then add v2 s1 else begin
let (l2, _, r2) = split v1 s2 in
join (union l1 l2) v1 (union r1 r2)
end
else
if h1 = 1 then add v1 s2 else begin
let (l1, _, r1) = split v2 s1 in
join (union l1 l2) v2 (union r1 r2)
end
let rec inter s1 s2 =
match (s1, s2) with
(Empty, t2) -> Empty
| (t1, Empty) -> Empty
| (Node(l1, v1, r1, _), t2) ->
match split v1 t2 with
(l2, None, r2) ->
concat (inter l1 l2) (inter r1 r2)
| (l2, Some _, r2) ->
join (inter l1 l2) v1 (inter r1 r2)
let rec diff s1 s2 =
match (s1, s2) with
(Empty, t2) -> Empty
| (t1, Empty) -> t1
| (Node(l1, v1, r1, _), t2) ->
match split v1 t2 with
(l2, None, r2) ->
join (diff l1 l2) v1 (diff r1 r2)
| (l2, Some _, r2) ->
concat (diff l1 l2) (diff r1 r2)
let rec compare_aux l1 l2 =
match (l1, l2) with
([], []) -> 0
| ([], _) -> -1
| (_, []) -> 1
| (Empty :: t1, Empty :: t2) ->
compare_aux t1 t2
| (Node(Empty, v1, r1, _) :: t1, Node(Empty, v2, r2, _) :: t2) ->
let c = compare v1 v2 in
if c <> 0 then c else compare_aux (r1::t1) (r2::t2)
| (Node(l1, v1, r1, _) :: t1, t2) ->
compare_aux (l1 :: Node(Empty, v1, r1, 0) :: t1) t2
| (t1, Node(l2, v2, r2, _) :: t2) ->
compare_aux t1 (l2 :: Node(Empty, v2, r2, 0) :: t2)
let compare s1 s2 =
compare_aux [s1] [s2]
let equal s1 s2 =
compare s1 s2 = 0
let rec subset s1 s2 =
match (s1, s2) with
Empty, _ ->
true
| _, Empty ->
false
| Node (l1, v1, r1, _), (Node (l2, v2, r2, _) as t2) ->
let c = Pervasives.compare v1 v2 in
if c = 0 then
subset l1 l2 && subset r1 r2
else if c < 0 then
subset (Node (l1, v1, Empty, 0)) l2 && subset r1 t2
else
subset (Node (Empty, v1, r1, 0)) r2 && subset l1 t2
let rec iter f = function
Empty -> ()
| Node(l, v, r, _) -> iter f l; f v; iter f r
let rec fold f s accu =
match s with
Empty -> accu
| Node(l, v, r, _) -> fold f l (f v (fold f r accu))
let rec cardinal = function
Empty -> 0
| Node(l, v, r, _) -> cardinal l + 1 + cardinal r
let rec elements_aux accu = function
Empty -> accu
| Node(l, v, r, _) -> elements_aux (v :: elements_aux accu r) l
let elements s =
elements_aux [] s
let rec min_elt = function
Empty -> raise Not_found
| Node(Empty, v, r, _) -> v
| Node(l, v, r, _) -> min_elt l
let rec max_elt = function
Empty -> raise Not_found
| Node(l, v, Empty, _) -> v
| Node(l, v, r, _) -> max_elt r
let choose = min_elt
| null | https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/lib/gset.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
Sets using the generic comparison function of ocaml. Code borrowed from
the ocaml standard library.
Same as merge, but does not assume anything about l and r.
Splitting
Implementation of the set operations | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
$ I d : gset.ml 5920 2004 - 07 - 16 20:01:26Z herbelin $
type 'a t = Empty | Node of 'a t * 'a * 'a t * int
Sets are represented by balanced binary trees ( the heights of the
children differ by at most 2
children differ by at most 2 *)
let height = function
Empty -> 0
| Node(_, _, _, h) -> h
Creates a new node with left son l , value x and right son and r must be balanced and | height l - height r | < = 2 .
Inline expansion of height for better speed .
l and r must be balanced and | height l - height r | <= 2.
Inline expansion of height for better speed. *)
let create l x r =
let hl = match l with Empty -> 0 | Node(_,_,_,h) -> h in
let hr = match r with Empty -> 0 | Node(_,_,_,h) -> h in
Node(l, x, r, (if hl >= hr then hl + 1 else hr + 1))
Same as create , but performs one step of rebalancing if necessary .
Assumes l and .
Inline expansion of create for better speed in the most frequent case
where no rebalancing is required .
Assumes l and r balanced.
Inline expansion of create for better speed in the most frequent case
where no rebalancing is required. *)
let bal l x r =
let hl = match l with Empty -> 0 | Node(_,_,_,h) -> h in
let hr = match r with Empty -> 0 | Node(_,_,_,h) -> h in
if hl > hr + 2 then begin
match l with
Empty -> invalid_arg "Set.bal"
| Node(ll, lv, lr, _) ->
if height ll >= height lr then
create ll lv (create lr x r)
else begin
match lr with
Empty -> invalid_arg "Set.bal"
| Node(lrl, lrv, lrr, _)->
create (create ll lv lrl) lrv (create lrr x r)
end
end else if hr > hl + 2 then begin
match r with
Empty -> invalid_arg "Set.bal"
| Node(rl, rv, rr, _) ->
if height rr >= height rl then
create (create l x rl) rv rr
else begin
match rl with
Empty -> invalid_arg "Set.bal"
| Node(rll, rlv, rlr, _) ->
create (create l x rll) rlv (create rlr rv rr)
end
end else
Node(l, x, r, (if hl >= hr then hl + 1 else hr + 1))
Same as bal , but repeat rebalancing until the final result
is balanced .
is balanced. *)
let rec join l x r =
match bal l x r with
Empty -> invalid_arg "Set.join"
| Node(l', x', r', _) as t' ->
let d = height l' - height r' in
if d < -2 or d > 2 then join l' x' r' else t'
Merge two trees l and r into one .
All elements of l must precede the elements of r.
Assumes | height l - height r | < = 2 .
All elements of l must precede the elements of r.
Assumes | height l - height r | <= 2. *)
let rec merge t1 t2 =
match (t1, t2) with
(Empty, t) -> t
| (t, Empty) -> t
| (Node(l1, v1, r1, h1), Node(l2, v2, r2, h2)) ->
bal l1 v1 (bal (merge r1 l2) v2 r2)
let rec concat t1 t2 =
match (t1, t2) with
(Empty, t) -> t
| (t, Empty) -> t
| (Node(l1, v1, r1, h1), Node(l2, v2, r2, h2)) ->
join l1 v1 (join (concat r1 l2) v2 r2)
let rec split x = function
Empty ->
(Empty, None, Empty)
| Node(l, v, r, _) ->
let c = Pervasives.compare x v in
if c = 0 then (l, Some v, r)
else if c < 0 then
let (ll, vl, rl) = split x l in (ll, vl, join rl v r)
else
let (lr, vr, rr) = split x r in (join l v lr, vr, rr)
let empty = Empty
let is_empty = function Empty -> true | _ -> false
let rec mem x = function
Empty -> false
| Node(l, v, r, _) ->
let c = Pervasives.compare x v in
c = 0 || mem x (if c < 0 then l else r)
let rec add x = function
Empty -> Node(Empty, x, Empty, 1)
| Node(l, v, r, _) as t ->
let c = Pervasives.compare x v in
if c = 0 then t else
if c < 0 then bal (add x l) v r else bal l v (add x r)
let singleton x = Node(Empty, x, Empty, 1)
let rec remove x = function
Empty -> Empty
| Node(l, v, r, _) ->
let c = Pervasives.compare x v in
if c = 0 then merge l r else
if c < 0 then bal (remove x l) v r else bal l v (remove x r)
let rec union s1 s2 =
match (s1, s2) with
(Empty, t2) -> t2
| (t1, Empty) -> t1
| (Node(l1, v1, r1, h1), Node(l2, v2, r2, h2)) ->
if h1 >= h2 then
if h2 = 1 then add v2 s1 else begin
let (l2, _, r2) = split v1 s2 in
join (union l1 l2) v1 (union r1 r2)
end
else
if h1 = 1 then add v1 s2 else begin
let (l1, _, r1) = split v2 s1 in
join (union l1 l2) v2 (union r1 r2)
end
let rec inter s1 s2 =
match (s1, s2) with
(Empty, t2) -> Empty
| (t1, Empty) -> Empty
| (Node(l1, v1, r1, _), t2) ->
match split v1 t2 with
(l2, None, r2) ->
concat (inter l1 l2) (inter r1 r2)
| (l2, Some _, r2) ->
join (inter l1 l2) v1 (inter r1 r2)
let rec diff s1 s2 =
match (s1, s2) with
(Empty, t2) -> Empty
| (t1, Empty) -> t1
| (Node(l1, v1, r1, _), t2) ->
match split v1 t2 with
(l2, None, r2) ->
join (diff l1 l2) v1 (diff r1 r2)
| (l2, Some _, r2) ->
concat (diff l1 l2) (diff r1 r2)
let rec compare_aux l1 l2 =
match (l1, l2) with
([], []) -> 0
| ([], _) -> -1
| (_, []) -> 1
| (Empty :: t1, Empty :: t2) ->
compare_aux t1 t2
| (Node(Empty, v1, r1, _) :: t1, Node(Empty, v2, r2, _) :: t2) ->
let c = compare v1 v2 in
if c <> 0 then c else compare_aux (r1::t1) (r2::t2)
| (Node(l1, v1, r1, _) :: t1, t2) ->
compare_aux (l1 :: Node(Empty, v1, r1, 0) :: t1) t2
| (t1, Node(l2, v2, r2, _) :: t2) ->
compare_aux t1 (l2 :: Node(Empty, v2, r2, 0) :: t2)
let compare s1 s2 =
compare_aux [s1] [s2]
let equal s1 s2 =
compare s1 s2 = 0
let rec subset s1 s2 =
match (s1, s2) with
Empty, _ ->
true
| _, Empty ->
false
| Node (l1, v1, r1, _), (Node (l2, v2, r2, _) as t2) ->
let c = Pervasives.compare v1 v2 in
if c = 0 then
subset l1 l2 && subset r1 r2
else if c < 0 then
subset (Node (l1, v1, Empty, 0)) l2 && subset r1 t2
else
subset (Node (Empty, v1, r1, 0)) r2 && subset l1 t2
let rec iter f = function
Empty -> ()
| Node(l, v, r, _) -> iter f l; f v; iter f r
let rec fold f s accu =
match s with
Empty -> accu
| Node(l, v, r, _) -> fold f l (f v (fold f r accu))
let rec cardinal = function
Empty -> 0
| Node(l, v, r, _) -> cardinal l + 1 + cardinal r
let rec elements_aux accu = function
Empty -> accu
| Node(l, v, r, _) -> elements_aux (v :: elements_aux accu r) l
let elements s =
elements_aux [] s
let rec min_elt = function
Empty -> raise Not_found
| Node(Empty, v, r, _) -> v
| Node(l, v, r, _) -> min_elt l
let rec max_elt = function
Empty -> raise Not_found
| Node(l, v, Empty, _) -> v
| Node(l, v, r, _) -> max_elt r
let choose = min_elt
|
7363e3736ae3b01bb23ad0d86ae89923773f703d522decc730988dbc384e63f1 | mjambon/atdgen | test_atdgen_type_conv.ml | open Sexplib.Std
let my_record = Test_type_conv_t.({ fst=123; snd="testing" })
let cmrs : (float Test_type_conv_t.contains_my_record) list =
let open Test_type_conv_t in
[ `C1 123
; `C2 123.0
; `C3 my_record ]
let sexps =
[my_record |> Test_type_conv_t.sexp_of_my_record] @
(List.map (Test_type_conv_t.sexp_of_contains_my_record sexp_of_float) cmrs)
let () =
sexps
|> sexp_of_list (fun x -> x)
|> Sexplib.Sexp.to_string
|> print_endline
| null | https://raw.githubusercontent.com/mjambon/atdgen/9b031da2f182a1fa60bc76ff3a3228ff7b45a8a3/test/test_atdgen_type_conv.ml | ocaml | open Sexplib.Std
let my_record = Test_type_conv_t.({ fst=123; snd="testing" })
let cmrs : (float Test_type_conv_t.contains_my_record) list =
let open Test_type_conv_t in
[ `C1 123
; `C2 123.0
; `C3 my_record ]
let sexps =
[my_record |> Test_type_conv_t.sexp_of_my_record] @
(List.map (Test_type_conv_t.sexp_of_contains_my_record sexp_of_float) cmrs)
let () =
sexps
|> sexp_of_list (fun x -> x)
|> Sexplib.Sexp.to_string
|> print_endline
|
|
46744790493b32a61a1b88dcf7954b1adf7657cdac444ae58c145504fc727113 | ThoughtWorksInc/stonecutter | user_list.clj | (ns stonecutter.view.user-list
(:require [net.cgrand.enlive-html :as html]
[stonecutter.view.view-helpers :as vh]
[stonecutter.routes :as r]
[stonecutter.config :as config]))
(def library-m (vh/load-template "public/library.html"))
(def empty-user-list-item (first (html/select library-m [:.clj--user-list__item__empty])))
(def user-with-confirmed-email-list-item
(first (html/select library-m [:.clj-library--user-list__user-with-confirmed-email :.clj--user-item])))
(def unconfirmed-email-icon (first (html/select library-m [:.clj--user-item__email-unconfirmed])))
(def user-displaying-both-confirmed-and-unconfirmed-email
(html/at user-with-confirmed-email-list-item
[:.clj--user-item__email-address] (html/prepend unconfirmed-email-icon)))
(defn user-list-items [users]
(html/at user-displaying-both-confirmed-and-unconfirmed-email
[:.clj--user-item]
(html/clone-for [user users]
[:.clj--user-item__email-confirmed] (when (:confirmed? user) identity)
[:.clj--user-item__email-unconfirmed] (when-not (:confirmed? user) identity)
[:.clj--user-item__toggle] (if (= (:role user) (:trusted config/roles))
(html/set-attr :checked "checked")
(html/remove-attr :checked))
[:.clj--user-item__label] (html/set-attr :for (:login user))
[:.clj--user-item__toggle] (html/set-attr :id (:login user))
[:.clj--user-item__email-input] (html/set-attr :value (:login user))
[:.clj--user-item__email-address__text] (html/content (:login user))
[:.clj--user-item__full-name] (html/content (str (:first-name user) " " (:last-name user))))))
(defn add-user-list [enlive-m users]
(if-not (empty? users)
(html/at enlive-m [:.clj--user-list] (html/content (user-list-items users)))
(html/at enlive-m [:.clj--user-list] (html/content empty-user-list-item))))
(defn not-an-admin? [user]
(not (= (:admin config/roles) (:role user))))
(defn set-flash-message [enlive-m request]
(let [translation-key (get-in request [:flash :translation-key])
updated-account-email (get-in request [:flash :updated-account-email])
enlive-m-with-user-login (html/at enlive-m [:.clj--flash-message-login] (html/content updated-account-email))]
(case translation-key
:user-trusted (html/at enlive-m-with-user-login [:.clj--flash-message-text] (html/set-attr :data-l8n "content:flash/user-trusted"))
:user-untrusted (html/at enlive-m-with-user-login [:.clj--flash-message-text] (html/set-attr :data-l8n "content:flash/user-untrusted"))
(vh/remove-element enlive-m [:.clj--flash-message-container]))))
(defn user-list [request]
(let [users (get-in request [:context :users])
non-admin-users (filterv not-an-admin? users)]
(-> (vh/load-template-with-lang "public/user-list.html" request)
vh/remove-work-in-progress
vh/set-admin-links
(add-user-list non-admin-users)
vh/add-anti-forgery
(set-flash-message request)
(vh/add-script "../js/main.js"))))
| null | https://raw.githubusercontent.com/ThoughtWorksInc/stonecutter/37ed22dd276ac652176c4d880e0f1b0c1e27abfe/src/stonecutter/view/user_list.clj | clojure | (ns stonecutter.view.user-list
(:require [net.cgrand.enlive-html :as html]
[stonecutter.view.view-helpers :as vh]
[stonecutter.routes :as r]
[stonecutter.config :as config]))
(def library-m (vh/load-template "public/library.html"))
(def empty-user-list-item (first (html/select library-m [:.clj--user-list__item__empty])))
(def user-with-confirmed-email-list-item
(first (html/select library-m [:.clj-library--user-list__user-with-confirmed-email :.clj--user-item])))
(def unconfirmed-email-icon (first (html/select library-m [:.clj--user-item__email-unconfirmed])))
(def user-displaying-both-confirmed-and-unconfirmed-email
(html/at user-with-confirmed-email-list-item
[:.clj--user-item__email-address] (html/prepend unconfirmed-email-icon)))
(defn user-list-items [users]
(html/at user-displaying-both-confirmed-and-unconfirmed-email
[:.clj--user-item]
(html/clone-for [user users]
[:.clj--user-item__email-confirmed] (when (:confirmed? user) identity)
[:.clj--user-item__email-unconfirmed] (when-not (:confirmed? user) identity)
[:.clj--user-item__toggle] (if (= (:role user) (:trusted config/roles))
(html/set-attr :checked "checked")
(html/remove-attr :checked))
[:.clj--user-item__label] (html/set-attr :for (:login user))
[:.clj--user-item__toggle] (html/set-attr :id (:login user))
[:.clj--user-item__email-input] (html/set-attr :value (:login user))
[:.clj--user-item__email-address__text] (html/content (:login user))
[:.clj--user-item__full-name] (html/content (str (:first-name user) " " (:last-name user))))))
(defn add-user-list [enlive-m users]
(if-not (empty? users)
(html/at enlive-m [:.clj--user-list] (html/content (user-list-items users)))
(html/at enlive-m [:.clj--user-list] (html/content empty-user-list-item))))
(defn not-an-admin? [user]
(not (= (:admin config/roles) (:role user))))
(defn set-flash-message [enlive-m request]
(let [translation-key (get-in request [:flash :translation-key])
updated-account-email (get-in request [:flash :updated-account-email])
enlive-m-with-user-login (html/at enlive-m [:.clj--flash-message-login] (html/content updated-account-email))]
(case translation-key
:user-trusted (html/at enlive-m-with-user-login [:.clj--flash-message-text] (html/set-attr :data-l8n "content:flash/user-trusted"))
:user-untrusted (html/at enlive-m-with-user-login [:.clj--flash-message-text] (html/set-attr :data-l8n "content:flash/user-untrusted"))
(vh/remove-element enlive-m [:.clj--flash-message-container]))))
(defn user-list [request]
(let [users (get-in request [:context :users])
non-admin-users (filterv not-an-admin? users)]
(-> (vh/load-template-with-lang "public/user-list.html" request)
vh/remove-work-in-progress
vh/set-admin-links
(add-user-list non-admin-users)
vh/add-anti-forgery
(set-flash-message request)
(vh/add-script "../js/main.js"))))
|
|
0e10767c12cd76224083a03a21320010a0afd6dc08be263ca38a14d47acbe8ab | jaredly/reason-language-server | runtimedef.ml | let builtin_exceptions = [|
"Out_of_memory";
"Sys_error";
"Failure";
"Invalid_argument";
"End_of_file";
"Division_by_zero";
"Not_found";
"Match_failure";
"Stack_overflow";
"Sys_blocked_io";
"Assert_failure";
"Undefined_recursive_module";
|]
let builtin_primitives = [|
"caml_abs_float";
"caml_acos_float";
"caml_add_debug_info";
"caml_add_float";
"caml_alloc_dummy";
"caml_alloc_dummy_float";
"caml_alloc_dummy_function";
"caml_array_append";
"caml_array_blit";
"caml_array_concat";
"caml_array_get";
"caml_array_get_addr";
"caml_array_get_float";
"caml_array_set";
"caml_array_set_addr";
"caml_array_set_float";
"caml_array_sub";
"caml_array_unsafe_get";
"caml_array_unsafe_get_float";
"caml_array_unsafe_set";
"caml_array_unsafe_set_addr";
"caml_array_unsafe_set_float";
"caml_asin_float";
"caml_atan2_float";
"caml_atan_float";
"caml_ba_blit";
"caml_ba_change_layout";
"caml_ba_create";
"caml_ba_dim";
"caml_ba_dim_1";
"caml_ba_dim_2";
"caml_ba_dim_3";
"caml_ba_fill";
"caml_ba_get_1";
"caml_ba_get_2";
"caml_ba_get_3";
"caml_ba_get_generic";
"caml_ba_kind";
"caml_ba_layout";
"caml_ba_num_dims";
"caml_ba_reshape";
"caml_ba_set_1";
"caml_ba_set_2";
"caml_ba_set_3";
"caml_ba_set_generic";
"caml_ba_slice";
"caml_ba_sub";
"caml_ba_uint8_get16";
"caml_ba_uint8_get32";
"caml_ba_uint8_get64";
"caml_ba_uint8_set16";
"caml_ba_uint8_set32";
"caml_ba_uint8_set64";
"caml_backtrace_status";
"caml_blit_bytes";
"caml_blit_string";
"caml_bswap16";
"caml_bytes_compare";
"caml_bytes_equal";
"caml_bytes_get";
"caml_bytes_get16";
"caml_bytes_get32";
"caml_bytes_get64";
"caml_bytes_greaterequal";
"caml_bytes_greaterthan";
"caml_bytes_lessequal";
"caml_bytes_lessthan";
"caml_bytes_notequal";
"caml_bytes_of_string";
"caml_bytes_set";
"caml_bytes_set16";
"caml_bytes_set32";
"caml_bytes_set64";
"caml_ceil_float";
"caml_channel_descriptor";
"caml_classify_float";
"caml_compare";
"caml_convert_raw_backtrace";
"caml_convert_raw_backtrace_slot";
"caml_copysign_float";
"caml_cos_float";
"caml_cosh_float";
"caml_create_bytes";
"caml_create_string";
"caml_div_float";
"caml_dynlink_add_primitive";
"caml_dynlink_close_lib";
"caml_dynlink_get_current_libs";
"caml_dynlink_lookup_symbol";
"caml_dynlink_open_lib";
"caml_ensure_stack_capacity";
"caml_ephe_blit_data";
"caml_ephe_blit_key";
"caml_ephe_check_data";
"caml_ephe_check_key";
"caml_ephe_create";
"caml_ephe_get_data";
"caml_ephe_get_data_copy";
"caml_ephe_get_key";
"caml_ephe_get_key_copy";
"caml_ephe_set_data";
"caml_ephe_set_key";
"caml_ephe_unset_data";
"caml_ephe_unset_key";
"caml_eq_float";
"caml_equal";
"caml_exp_float";
"caml_expm1_float";
"caml_fill_bytes";
"caml_fill_string";
"caml_final_register";
"caml_final_register_called_without_value";
"caml_final_release";
"caml_float_compare";
"caml_float_of_int";
"caml_float_of_string";
"caml_floatarray_create";
"caml_floatarray_get";
"caml_floatarray_set";
"caml_floatarray_unsafe_get";
"caml_floatarray_unsafe_set";
"caml_floor_float";
"caml_fmod_float";
"caml_format_float";
"caml_format_int";
"caml_fresh_oo_id";
"caml_frexp_float";
"caml_gc_compaction";
"caml_gc_counters";
"caml_gc_full_major";
"caml_gc_get";
"caml_gc_huge_fallback_count";
"caml_gc_major";
"caml_gc_major_slice";
"caml_gc_minor";
"caml_gc_minor_words";
"caml_gc_quick_stat";
"caml_gc_set";
"caml_gc_stat";
"caml_ge_float";
"caml_get_current_callstack";
"caml_get_current_environment";
"caml_get_exception_backtrace";
"caml_get_exception_raw_backtrace";
"caml_get_global_data";
"caml_get_major_bucket";
"caml_get_major_credit";
"caml_get_minor_free";
"caml_get_public_method";
"caml_get_section_table";
"caml_greaterequal";
"caml_greaterthan";
"caml_gt_float";
"caml_hash";
"caml_hash_univ_param";
"caml_hexstring_of_float";
"caml_hypot_float";
"caml_input_value";
"caml_input_value_from_bytes";
"caml_input_value_from_string";
"caml_input_value_to_outside_heap";
"caml_install_signal_handler";
"caml_int32_add";
"caml_int32_and";
"caml_int32_bits_of_float";
"caml_int32_bswap";
"caml_int32_compare";
"caml_int32_div";
"caml_int32_float_of_bits";
"caml_int32_format";
"caml_int32_mod";
"caml_int32_mul";
"caml_int32_neg";
"caml_int32_of_float";
"caml_int32_of_int";
"caml_int32_of_string";
"caml_int32_or";
"caml_int32_shift_left";
"caml_int32_shift_right";
"caml_int32_shift_right_unsigned";
"caml_int32_sub";
"caml_int32_to_float";
"caml_int32_to_int";
"caml_int32_xor";
"caml_int64_add";
"caml_int64_and";
"caml_int64_bits_of_float";
"caml_int64_bswap";
"caml_int64_compare";
"caml_int64_div";
"caml_int64_float_of_bits";
"caml_int64_format";
"caml_int64_mod";
"caml_int64_mul";
"caml_int64_neg";
"caml_int64_of_float";
"caml_int64_of_int";
"caml_int64_of_int32";
"caml_int64_of_nativeint";
"caml_int64_of_string";
"caml_int64_or";
"caml_int64_shift_left";
"caml_int64_shift_right";
"caml_int64_shift_right_unsigned";
"caml_int64_sub";
"caml_int64_to_float";
"caml_int64_to_int";
"caml_int64_to_int32";
"caml_int64_to_nativeint";
"caml_int64_xor";
"caml_int_as_pointer";
"caml_int_compare";
"caml_int_of_float";
"caml_int_of_string";
"caml_invoke_traced_function";
"caml_lazy_follow_forward";
"caml_lazy_make_forward";
"caml_ldexp_float";
"caml_le_float";
"caml_lessequal";
"caml_lessthan";
"caml_lex_engine";
"caml_log10_float";
"caml_log1p_float";
"caml_log_float";
"caml_lt_float";
"caml_make_array";
"caml_make_float_vect";
"caml_make_vect";
"caml_marshal_data_size";
"caml_md5_chan";
"caml_md5_string";
"caml_ml_bytes_length";
"caml_ml_channel_size";
"caml_ml_channel_size_64";
"caml_ml_close_channel";
"caml_ml_enable_runtime_warnings";
"caml_ml_flush";
"caml_ml_flush_partial";
"caml_ml_input";
"caml_ml_input_char";
"caml_ml_input_int";
"caml_ml_input_scan_line";
"caml_ml_open_descriptor_in";
"caml_ml_open_descriptor_out";
"caml_ml_out_channels_list";
"caml_ml_output";
"caml_ml_output_bytes";
"caml_ml_output_char";
"caml_ml_output_int";
"caml_ml_output_partial";
"caml_ml_pos_in";
"caml_ml_pos_in_64";
"caml_ml_pos_out";
"caml_ml_pos_out_64";
"caml_ml_runtime_warnings_enabled";
"caml_ml_seek_in";
"caml_ml_seek_in_64";
"caml_ml_seek_out";
"caml_ml_seek_out_64";
"caml_ml_set_binary_mode";
"caml_ml_set_channel_name";
"caml_ml_string_length";
"caml_modf_float";
"caml_mul_float";
"caml_nativeint_add";
"caml_nativeint_and";
"caml_nativeint_bswap";
"caml_nativeint_compare";
"caml_nativeint_div";
"caml_nativeint_format";
"caml_nativeint_mod";
"caml_nativeint_mul";
"caml_nativeint_neg";
"caml_nativeint_of_float";
"caml_nativeint_of_int";
"caml_nativeint_of_int32";
"caml_nativeint_of_string";
"caml_nativeint_or";
"caml_nativeint_shift_left";
"caml_nativeint_shift_right";
"caml_nativeint_shift_right_unsigned";
"caml_nativeint_sub";
"caml_nativeint_to_float";
"caml_nativeint_to_int";
"caml_nativeint_to_int32";
"caml_nativeint_xor";
"caml_neg_float";
"caml_neq_float";
"caml_new_lex_engine";
"caml_notequal";
"caml_obj_add_offset";
"caml_obj_block";
"caml_obj_dup";
"caml_obj_is_block";
"caml_obj_reachable_words";
"caml_obj_set_tag";
"caml_obj_tag";
"caml_obj_truncate";
"caml_output_value";
"caml_output_value_to_buffer";
"caml_output_value_to_bytes";
"caml_output_value_to_string";
"caml_parse_engine";
"caml_power_float";
"caml_raw_backtrace_length";
"caml_raw_backtrace_next_slot";
"caml_raw_backtrace_slot";
"caml_realloc_global";
"caml_record_backtrace";
"caml_register_channel_for_spacetime";
"caml_register_code_fragment";
"caml_register_named_value";
"caml_reify_bytecode";
"caml_remove_debug_info";
"caml_reset_afl_instrumentation";
"caml_restore_raw_backtrace";
"caml_runtime_parameters";
"caml_runtime_variant";
"caml_set_oo_id";
"caml_set_parser_trace";
"caml_setup_afl";
"caml_sin_float";
"caml_sinh_float";
"caml_spacetime_enabled";
"caml_spacetime_only_works_for_native_code";
"caml_sqrt_float";
"caml_static_alloc";
"caml_static_free";
"caml_static_release_bytecode";
"caml_static_resize";
"caml_string_compare";
"caml_string_equal";
"caml_string_get";
"caml_string_get16";
"caml_string_get32";
"caml_string_get64";
"caml_string_greaterequal";
"caml_string_greaterthan";
"caml_string_lessequal";
"caml_string_lessthan";
"caml_string_notequal";
"caml_string_of_bytes";
"caml_string_set";
"caml_sub_float";
"caml_sys_chdir";
"caml_sys_close";
"caml_sys_const_backend_type";
"caml_sys_const_big_endian";
"caml_sys_const_int_size";
"caml_sys_const_max_wosize";
"caml_sys_const_ostype_cygwin";
"caml_sys_const_ostype_unix";
"caml_sys_const_ostype_win32";
"caml_sys_const_word_size";
"caml_sys_exit";
"caml_sys_file_exists";
"caml_sys_get_argv";
"caml_sys_get_config";
"caml_sys_getcwd";
"caml_sys_getenv";
"caml_sys_is_directory";
"caml_sys_isatty";
"caml_sys_open";
"caml_sys_random_seed";
"caml_sys_read_directory";
"caml_sys_remove";
"caml_sys_rename";
"caml_sys_system_command";
"caml_sys_time";
"caml_sys_time_include_children";
"caml_sys_unsafe_getenv";
"caml_tan_float";
"caml_tanh_float";
"caml_terminfo_rows";
"caml_update_dummy";
"caml_weak_blit";
"caml_weak_check";
"caml_weak_create";
"caml_weak_get";
"caml_weak_get_copy";
"caml_weak_set";
|]
| null | https://raw.githubusercontent.com/jaredly/reason-language-server/ce1b3f8ddb554b6498c2a83ea9c53a6bdf0b6081/ocaml_typing/407/runtimedef.ml | ocaml | let builtin_exceptions = [|
"Out_of_memory";
"Sys_error";
"Failure";
"Invalid_argument";
"End_of_file";
"Division_by_zero";
"Not_found";
"Match_failure";
"Stack_overflow";
"Sys_blocked_io";
"Assert_failure";
"Undefined_recursive_module";
|]
let builtin_primitives = [|
"caml_abs_float";
"caml_acos_float";
"caml_add_debug_info";
"caml_add_float";
"caml_alloc_dummy";
"caml_alloc_dummy_float";
"caml_alloc_dummy_function";
"caml_array_append";
"caml_array_blit";
"caml_array_concat";
"caml_array_get";
"caml_array_get_addr";
"caml_array_get_float";
"caml_array_set";
"caml_array_set_addr";
"caml_array_set_float";
"caml_array_sub";
"caml_array_unsafe_get";
"caml_array_unsafe_get_float";
"caml_array_unsafe_set";
"caml_array_unsafe_set_addr";
"caml_array_unsafe_set_float";
"caml_asin_float";
"caml_atan2_float";
"caml_atan_float";
"caml_ba_blit";
"caml_ba_change_layout";
"caml_ba_create";
"caml_ba_dim";
"caml_ba_dim_1";
"caml_ba_dim_2";
"caml_ba_dim_3";
"caml_ba_fill";
"caml_ba_get_1";
"caml_ba_get_2";
"caml_ba_get_3";
"caml_ba_get_generic";
"caml_ba_kind";
"caml_ba_layout";
"caml_ba_num_dims";
"caml_ba_reshape";
"caml_ba_set_1";
"caml_ba_set_2";
"caml_ba_set_3";
"caml_ba_set_generic";
"caml_ba_slice";
"caml_ba_sub";
"caml_ba_uint8_get16";
"caml_ba_uint8_get32";
"caml_ba_uint8_get64";
"caml_ba_uint8_set16";
"caml_ba_uint8_set32";
"caml_ba_uint8_set64";
"caml_backtrace_status";
"caml_blit_bytes";
"caml_blit_string";
"caml_bswap16";
"caml_bytes_compare";
"caml_bytes_equal";
"caml_bytes_get";
"caml_bytes_get16";
"caml_bytes_get32";
"caml_bytes_get64";
"caml_bytes_greaterequal";
"caml_bytes_greaterthan";
"caml_bytes_lessequal";
"caml_bytes_lessthan";
"caml_bytes_notequal";
"caml_bytes_of_string";
"caml_bytes_set";
"caml_bytes_set16";
"caml_bytes_set32";
"caml_bytes_set64";
"caml_ceil_float";
"caml_channel_descriptor";
"caml_classify_float";
"caml_compare";
"caml_convert_raw_backtrace";
"caml_convert_raw_backtrace_slot";
"caml_copysign_float";
"caml_cos_float";
"caml_cosh_float";
"caml_create_bytes";
"caml_create_string";
"caml_div_float";
"caml_dynlink_add_primitive";
"caml_dynlink_close_lib";
"caml_dynlink_get_current_libs";
"caml_dynlink_lookup_symbol";
"caml_dynlink_open_lib";
"caml_ensure_stack_capacity";
"caml_ephe_blit_data";
"caml_ephe_blit_key";
"caml_ephe_check_data";
"caml_ephe_check_key";
"caml_ephe_create";
"caml_ephe_get_data";
"caml_ephe_get_data_copy";
"caml_ephe_get_key";
"caml_ephe_get_key_copy";
"caml_ephe_set_data";
"caml_ephe_set_key";
"caml_ephe_unset_data";
"caml_ephe_unset_key";
"caml_eq_float";
"caml_equal";
"caml_exp_float";
"caml_expm1_float";
"caml_fill_bytes";
"caml_fill_string";
"caml_final_register";
"caml_final_register_called_without_value";
"caml_final_release";
"caml_float_compare";
"caml_float_of_int";
"caml_float_of_string";
"caml_floatarray_create";
"caml_floatarray_get";
"caml_floatarray_set";
"caml_floatarray_unsafe_get";
"caml_floatarray_unsafe_set";
"caml_floor_float";
"caml_fmod_float";
"caml_format_float";
"caml_format_int";
"caml_fresh_oo_id";
"caml_frexp_float";
"caml_gc_compaction";
"caml_gc_counters";
"caml_gc_full_major";
"caml_gc_get";
"caml_gc_huge_fallback_count";
"caml_gc_major";
"caml_gc_major_slice";
"caml_gc_minor";
"caml_gc_minor_words";
"caml_gc_quick_stat";
"caml_gc_set";
"caml_gc_stat";
"caml_ge_float";
"caml_get_current_callstack";
"caml_get_current_environment";
"caml_get_exception_backtrace";
"caml_get_exception_raw_backtrace";
"caml_get_global_data";
"caml_get_major_bucket";
"caml_get_major_credit";
"caml_get_minor_free";
"caml_get_public_method";
"caml_get_section_table";
"caml_greaterequal";
"caml_greaterthan";
"caml_gt_float";
"caml_hash";
"caml_hash_univ_param";
"caml_hexstring_of_float";
"caml_hypot_float";
"caml_input_value";
"caml_input_value_from_bytes";
"caml_input_value_from_string";
"caml_input_value_to_outside_heap";
"caml_install_signal_handler";
"caml_int32_add";
"caml_int32_and";
"caml_int32_bits_of_float";
"caml_int32_bswap";
"caml_int32_compare";
"caml_int32_div";
"caml_int32_float_of_bits";
"caml_int32_format";
"caml_int32_mod";
"caml_int32_mul";
"caml_int32_neg";
"caml_int32_of_float";
"caml_int32_of_int";
"caml_int32_of_string";
"caml_int32_or";
"caml_int32_shift_left";
"caml_int32_shift_right";
"caml_int32_shift_right_unsigned";
"caml_int32_sub";
"caml_int32_to_float";
"caml_int32_to_int";
"caml_int32_xor";
"caml_int64_add";
"caml_int64_and";
"caml_int64_bits_of_float";
"caml_int64_bswap";
"caml_int64_compare";
"caml_int64_div";
"caml_int64_float_of_bits";
"caml_int64_format";
"caml_int64_mod";
"caml_int64_mul";
"caml_int64_neg";
"caml_int64_of_float";
"caml_int64_of_int";
"caml_int64_of_int32";
"caml_int64_of_nativeint";
"caml_int64_of_string";
"caml_int64_or";
"caml_int64_shift_left";
"caml_int64_shift_right";
"caml_int64_shift_right_unsigned";
"caml_int64_sub";
"caml_int64_to_float";
"caml_int64_to_int";
"caml_int64_to_int32";
"caml_int64_to_nativeint";
"caml_int64_xor";
"caml_int_as_pointer";
"caml_int_compare";
"caml_int_of_float";
"caml_int_of_string";
"caml_invoke_traced_function";
"caml_lazy_follow_forward";
"caml_lazy_make_forward";
"caml_ldexp_float";
"caml_le_float";
"caml_lessequal";
"caml_lessthan";
"caml_lex_engine";
"caml_log10_float";
"caml_log1p_float";
"caml_log_float";
"caml_lt_float";
"caml_make_array";
"caml_make_float_vect";
"caml_make_vect";
"caml_marshal_data_size";
"caml_md5_chan";
"caml_md5_string";
"caml_ml_bytes_length";
"caml_ml_channel_size";
"caml_ml_channel_size_64";
"caml_ml_close_channel";
"caml_ml_enable_runtime_warnings";
"caml_ml_flush";
"caml_ml_flush_partial";
"caml_ml_input";
"caml_ml_input_char";
"caml_ml_input_int";
"caml_ml_input_scan_line";
"caml_ml_open_descriptor_in";
"caml_ml_open_descriptor_out";
"caml_ml_out_channels_list";
"caml_ml_output";
"caml_ml_output_bytes";
"caml_ml_output_char";
"caml_ml_output_int";
"caml_ml_output_partial";
"caml_ml_pos_in";
"caml_ml_pos_in_64";
"caml_ml_pos_out";
"caml_ml_pos_out_64";
"caml_ml_runtime_warnings_enabled";
"caml_ml_seek_in";
"caml_ml_seek_in_64";
"caml_ml_seek_out";
"caml_ml_seek_out_64";
"caml_ml_set_binary_mode";
"caml_ml_set_channel_name";
"caml_ml_string_length";
"caml_modf_float";
"caml_mul_float";
"caml_nativeint_add";
"caml_nativeint_and";
"caml_nativeint_bswap";
"caml_nativeint_compare";
"caml_nativeint_div";
"caml_nativeint_format";
"caml_nativeint_mod";
"caml_nativeint_mul";
"caml_nativeint_neg";
"caml_nativeint_of_float";
"caml_nativeint_of_int";
"caml_nativeint_of_int32";
"caml_nativeint_of_string";
"caml_nativeint_or";
"caml_nativeint_shift_left";
"caml_nativeint_shift_right";
"caml_nativeint_shift_right_unsigned";
"caml_nativeint_sub";
"caml_nativeint_to_float";
"caml_nativeint_to_int";
"caml_nativeint_to_int32";
"caml_nativeint_xor";
"caml_neg_float";
"caml_neq_float";
"caml_new_lex_engine";
"caml_notequal";
"caml_obj_add_offset";
"caml_obj_block";
"caml_obj_dup";
"caml_obj_is_block";
"caml_obj_reachable_words";
"caml_obj_set_tag";
"caml_obj_tag";
"caml_obj_truncate";
"caml_output_value";
"caml_output_value_to_buffer";
"caml_output_value_to_bytes";
"caml_output_value_to_string";
"caml_parse_engine";
"caml_power_float";
"caml_raw_backtrace_length";
"caml_raw_backtrace_next_slot";
"caml_raw_backtrace_slot";
"caml_realloc_global";
"caml_record_backtrace";
"caml_register_channel_for_spacetime";
"caml_register_code_fragment";
"caml_register_named_value";
"caml_reify_bytecode";
"caml_remove_debug_info";
"caml_reset_afl_instrumentation";
"caml_restore_raw_backtrace";
"caml_runtime_parameters";
"caml_runtime_variant";
"caml_set_oo_id";
"caml_set_parser_trace";
"caml_setup_afl";
"caml_sin_float";
"caml_sinh_float";
"caml_spacetime_enabled";
"caml_spacetime_only_works_for_native_code";
"caml_sqrt_float";
"caml_static_alloc";
"caml_static_free";
"caml_static_release_bytecode";
"caml_static_resize";
"caml_string_compare";
"caml_string_equal";
"caml_string_get";
"caml_string_get16";
"caml_string_get32";
"caml_string_get64";
"caml_string_greaterequal";
"caml_string_greaterthan";
"caml_string_lessequal";
"caml_string_lessthan";
"caml_string_notequal";
"caml_string_of_bytes";
"caml_string_set";
"caml_sub_float";
"caml_sys_chdir";
"caml_sys_close";
"caml_sys_const_backend_type";
"caml_sys_const_big_endian";
"caml_sys_const_int_size";
"caml_sys_const_max_wosize";
"caml_sys_const_ostype_cygwin";
"caml_sys_const_ostype_unix";
"caml_sys_const_ostype_win32";
"caml_sys_const_word_size";
"caml_sys_exit";
"caml_sys_file_exists";
"caml_sys_get_argv";
"caml_sys_get_config";
"caml_sys_getcwd";
"caml_sys_getenv";
"caml_sys_is_directory";
"caml_sys_isatty";
"caml_sys_open";
"caml_sys_random_seed";
"caml_sys_read_directory";
"caml_sys_remove";
"caml_sys_rename";
"caml_sys_system_command";
"caml_sys_time";
"caml_sys_time_include_children";
"caml_sys_unsafe_getenv";
"caml_tan_float";
"caml_tanh_float";
"caml_terminfo_rows";
"caml_update_dummy";
"caml_weak_blit";
"caml_weak_check";
"caml_weak_create";
"caml_weak_get";
"caml_weak_get_copy";
"caml_weak_set";
|]
|
|
98064a51e74620a5a7f34993f686b997594ffcf2d6a4f968981d403c2f446e57 | spawnfest/eep49ers | xmerl_sax_stream_SUITE.erl | %%-*-erlang-*-
%%----------------------------------------------------------------------
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2017 . All Rights Reserved .
%%
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
%%
%% -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.
%%
%% %CopyrightEnd%
%%----------------------------------------------------------------------
%% File : xmerl_sax_stream_SUITE.erl
%%----------------------------------------------------------------------
-module(xmerl_sax_stream_SUITE).
-compile(export_all).
%%----------------------------------------------------------------------
%% Include files
%%----------------------------------------------------------------------
-include_lib("common_test/include/ct.hrl").
-include_lib("kernel/include/file.hrl").
%%======================================================================
%% External functions
%%======================================================================
%%----------------------------------------------------------------------
Initializations
%%----------------------------------------------------------------------
all() ->
[
one_document,
two_documents,
one_document_and_junk,
end_of_stream
].
%%----------------------------------------------------------------------
Initializations
%%----------------------------------------------------------------------
init_per_suite(Config) ->
Config.
end_per_suite(_Config) ->
ok.
init_per_testcase(_TestCase, Config) ->
Config.
end_per_testcase(_Func, _Config) ->
ok.
%%----------------------------------------------------------------------
%% Tests
%%----------------------------------------------------------------------
%%----------------------------------------------------------------------
Send One doc over stream
one_document(Config) ->
Port = 11111,
{ok, ListenSocket} = listen(Port),
Self = self(),
spawn(
fun() ->
case catch gen_tcp:accept(ListenSocket) of
{ok, S} ->
Result = xmerl_sax_parser:stream(<<>>,
[{continuation_state, S},
{continuation_fun,
fun(Sd) ->
io:format("Continuation called!!", []),
case gen_tcp:recv(Sd, 0) of
{ok, Packet} ->
io:format("Packet: ~p\n", [Packet]),
{Packet, Sd};
{error, Reason} ->
throw({error, Reason})
end
end}]),
Self ! {xmerl_sax, Result},
close(S);
Error ->
Self ! {xmerl_sax, {error, {accept, Error}}}
end
end),
{ok, SendSocket} = connect(localhost, Port),
{ok, Binary} = file:read_file(filename:join([datadir(Config), "xmerl_sax_stream_one.xml"])),
send_chunks(SendSocket, Binary),
receive
{xmerl_sax, {ok, undefined, Rest}} ->
<<"\n">> = Rest,
io:format("Ok Rest: ~p\n", [Rest])
after 5000 ->
ct:fail("Timeout")
end,
ok.
%%----------------------------------------------------------------------
Send Two doc over stream
two_documents(Config) ->
Port = 11111,
{ok, ListenSocket} = listen(Port),
Self = self(),
spawn(
fun() ->
case catch gen_tcp:accept(ListenSocket) of
{ok, S} ->
Result = xmerl_sax_parser:stream(<<>>,
[{continuation_state, S},
{continuation_fun,
fun(Sd) ->
io:format("Continuation called!!", []),
case gen_tcp:recv(Sd, 0) of
{ok, Packet} ->
io:format("Packet: ~p\n", [Packet]),
{Packet, Sd};
{error, Reason} ->
throw({error, Reason})
end
end}]),
Self ! {xmerl_sax, Result},
close(S);
Error ->
Self ! {xmerl_sax, {error, {accept, Error}}}
end
end),
{ok, SendSocket} = connect(localhost, Port),
{ok, Binary} = file:read_file(filename:join([datadir(Config), "xmerl_sax_stream_two.xml"])),
send_chunks(SendSocket, Binary),
receive
{xmerl_sax, {ok, undefined, Rest}} ->
<<"\n<?x", _R/binary>> = Rest,
io:format("Ok Rest: ~p\n", [Rest])
after 5000 ->
ct:fail("Timeout")
end,
ok.
%%----------------------------------------------------------------------
Send one doc and then junk on stream
one_document_and_junk(Config) ->
Port = 11111,
{ok, ListenSocket} = listen(Port),
Self = self(),
spawn(
fun() ->
case catch gen_tcp:accept(ListenSocket) of
{ok, S} ->
Result = xmerl_sax_parser:stream(<<>>,
[{continuation_state, S},
{continuation_fun,
fun(Sd) ->
io:format("Continuation called!!", []),
case gen_tcp:recv(Sd, 0) of
{ok, Packet} ->
io:format("Packet: ~p\n", [Packet]),
{Packet, Sd};
{error, Reason} ->
throw({error, Reason})
end
end}]),
Self ! {xmerl_sax, Result},
close(S);
Error ->
Self ! {xmerl_sax, {error, {accept, Error}}}
end
end),
{ok, SendSocket} = connect(localhost, Port),
{ok, Binary} = file:read_file(filename:join([datadir(Config), "xmerl_sax_stream_one_junk.xml"])),
send_chunks(SendSocket, Binary),
receive
{xmerl_sax, {ok, undefined, Rest}} ->
<<"\nth", _R/binary>> = Rest,
io:format("Ok Rest: ~p\n", [Rest])
after 10000 ->
ct:fail("Timeout")
end,
ok.
%%----------------------------------------------------------------------
%% Test of continuation when end of stream
end_of_stream(_Config) ->
Stream = <<"<?xml version=\"1.0\" encoding=\"utf-8\"?><a>hej</a>">>,
{ok, undefined, <<>>} = xmerl_sax_parser:stream(Stream, []),
ok.
%%----------------------------------------------------------------------
%% Utility functions
%%----------------------------------------------------------------------
listen(Port) ->
case catch gen_tcp:listen(Port, [{active, false},
binary,
{keepalive, true},
{reuseaddr,true}]) of
{ok, ListenSocket} ->
{ok, ListenSocket};
{error, Reason} ->
{error, {listen, Reason}}
end.
close(Socket) ->
(catch gen_tcp:close(Socket)).
connect(Host, Port) ->
Timeout = 5000,
% Options1 = check_options(Options),
Options = [binary],
case catch gen_tcp:connect(Host, Port, Options, Timeout) of
{ok, Socket} ->
{ok, Socket};
{error, Reason} ->
{error, Reason}
end.
send_chunks(Socket, Binary) ->
BSize = erlang:size(Binary),
if
BSize > 25 ->
<<Head:25/binary, Tail/binary>> = Binary,
case gen_tcp:send(Socket, Head) of
ok ->
timer:sleep(1000),
send_chunks(Socket, Tail);
{error,closed} ->
ok
end;
true ->
gen_tcp:send(Socket, Binary)
end.
datadir(Config) ->
proplists:get_value(data_dir, Config).
| null | https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/xmerl/test/xmerl_sax_stream_SUITE.erl | erlang | -*-erlang-*-
----------------------------------------------------------------------
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
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.
%CopyrightEnd%
----------------------------------------------------------------------
File : xmerl_sax_stream_SUITE.erl
----------------------------------------------------------------------
----------------------------------------------------------------------
Include files
----------------------------------------------------------------------
======================================================================
External functions
======================================================================
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Tests
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Test of continuation when end of stream
----------------------------------------------------------------------
Utility functions
----------------------------------------------------------------------
Options1 = check_options(Options), | Copyright Ericsson AB 2017 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(xmerl_sax_stream_SUITE).
-compile(export_all).
-include_lib("common_test/include/ct.hrl").
-include_lib("kernel/include/file.hrl").
Initializations
all() ->
[
one_document,
two_documents,
one_document_and_junk,
end_of_stream
].
Initializations
init_per_suite(Config) ->
Config.
end_per_suite(_Config) ->
ok.
init_per_testcase(_TestCase, Config) ->
Config.
end_per_testcase(_Func, _Config) ->
ok.
Send One doc over stream
one_document(Config) ->
Port = 11111,
{ok, ListenSocket} = listen(Port),
Self = self(),
spawn(
fun() ->
case catch gen_tcp:accept(ListenSocket) of
{ok, S} ->
Result = xmerl_sax_parser:stream(<<>>,
[{continuation_state, S},
{continuation_fun,
fun(Sd) ->
io:format("Continuation called!!", []),
case gen_tcp:recv(Sd, 0) of
{ok, Packet} ->
io:format("Packet: ~p\n", [Packet]),
{Packet, Sd};
{error, Reason} ->
throw({error, Reason})
end
end}]),
Self ! {xmerl_sax, Result},
close(S);
Error ->
Self ! {xmerl_sax, {error, {accept, Error}}}
end
end),
{ok, SendSocket} = connect(localhost, Port),
{ok, Binary} = file:read_file(filename:join([datadir(Config), "xmerl_sax_stream_one.xml"])),
send_chunks(SendSocket, Binary),
receive
{xmerl_sax, {ok, undefined, Rest}} ->
<<"\n">> = Rest,
io:format("Ok Rest: ~p\n", [Rest])
after 5000 ->
ct:fail("Timeout")
end,
ok.
Send Two doc over stream
two_documents(Config) ->
Port = 11111,
{ok, ListenSocket} = listen(Port),
Self = self(),
spawn(
fun() ->
case catch gen_tcp:accept(ListenSocket) of
{ok, S} ->
Result = xmerl_sax_parser:stream(<<>>,
[{continuation_state, S},
{continuation_fun,
fun(Sd) ->
io:format("Continuation called!!", []),
case gen_tcp:recv(Sd, 0) of
{ok, Packet} ->
io:format("Packet: ~p\n", [Packet]),
{Packet, Sd};
{error, Reason} ->
throw({error, Reason})
end
end}]),
Self ! {xmerl_sax, Result},
close(S);
Error ->
Self ! {xmerl_sax, {error, {accept, Error}}}
end
end),
{ok, SendSocket} = connect(localhost, Port),
{ok, Binary} = file:read_file(filename:join([datadir(Config), "xmerl_sax_stream_two.xml"])),
send_chunks(SendSocket, Binary),
receive
{xmerl_sax, {ok, undefined, Rest}} ->
<<"\n<?x", _R/binary>> = Rest,
io:format("Ok Rest: ~p\n", [Rest])
after 5000 ->
ct:fail("Timeout")
end,
ok.
Send one doc and then junk on stream
one_document_and_junk(Config) ->
Port = 11111,
{ok, ListenSocket} = listen(Port),
Self = self(),
spawn(
fun() ->
case catch gen_tcp:accept(ListenSocket) of
{ok, S} ->
Result = xmerl_sax_parser:stream(<<>>,
[{continuation_state, S},
{continuation_fun,
fun(Sd) ->
io:format("Continuation called!!", []),
case gen_tcp:recv(Sd, 0) of
{ok, Packet} ->
io:format("Packet: ~p\n", [Packet]),
{Packet, Sd};
{error, Reason} ->
throw({error, Reason})
end
end}]),
Self ! {xmerl_sax, Result},
close(S);
Error ->
Self ! {xmerl_sax, {error, {accept, Error}}}
end
end),
{ok, SendSocket} = connect(localhost, Port),
{ok, Binary} = file:read_file(filename:join([datadir(Config), "xmerl_sax_stream_one_junk.xml"])),
send_chunks(SendSocket, Binary),
receive
{xmerl_sax, {ok, undefined, Rest}} ->
<<"\nth", _R/binary>> = Rest,
io:format("Ok Rest: ~p\n", [Rest])
after 10000 ->
ct:fail("Timeout")
end,
ok.
end_of_stream(_Config) ->
Stream = <<"<?xml version=\"1.0\" encoding=\"utf-8\"?><a>hej</a>">>,
{ok, undefined, <<>>} = xmerl_sax_parser:stream(Stream, []),
ok.
listen(Port) ->
case catch gen_tcp:listen(Port, [{active, false},
binary,
{keepalive, true},
{reuseaddr,true}]) of
{ok, ListenSocket} ->
{ok, ListenSocket};
{error, Reason} ->
{error, {listen, Reason}}
end.
close(Socket) ->
(catch gen_tcp:close(Socket)).
connect(Host, Port) ->
Timeout = 5000,
Options = [binary],
case catch gen_tcp:connect(Host, Port, Options, Timeout) of
{ok, Socket} ->
{ok, Socket};
{error, Reason} ->
{error, Reason}
end.
send_chunks(Socket, Binary) ->
BSize = erlang:size(Binary),
if
BSize > 25 ->
<<Head:25/binary, Tail/binary>> = Binary,
case gen_tcp:send(Socket, Head) of
ok ->
timer:sleep(1000),
send_chunks(Socket, Tail);
{error,closed} ->
ok
end;
true ->
gen_tcp:send(Socket, Binary)
end.
datadir(Config) ->
proplists:get_value(data_dir, Config).
|
3107186d94945ec8188d2bf75e2e0ff3a79d36a235354ccfa9bf58308142eba0 | EasyCrypt/easycrypt | ecAlgTactic.mli | (* -------------------------------------------------------------------- *)
open EcSymbols
open EcTypes
open EcDecl
open EcFol
open EcAlgebra
open EcCoreGoal
(* -------------------------------------------------------------------- *)
val is_module_loaded : EcEnv.env -> bool
(* -------------------------------------------------------------------- *)
val ring_symbols : EcEnv.env -> EcDecl.rkind -> ty -> (symbol * (bool * ty)) list
val field_symbols : EcEnv.env -> ty -> (symbol * (bool * ty)) list
val ring_axioms : EcEnv.env -> ring -> (symbol * form) list
val field_axioms : EcEnv.env -> field -> (symbol * form) list
(* -------------------------------------------------------------------- *)
val t_ring : ring -> eq list -> form * form -> FApi.backward
val t_ring_simplify : ring -> eq list -> form * form -> FApi.backward
val t_ring_congr :
cring -> RState.rstate -> int list -> form list -> FApi.backward
(* -------------------------------------------------------------------- *)
val t_field : field -> eq list -> form * form -> FApi.backward
val t_field_simplify : field -> eq list -> form * form -> FApi.backward
val t_field_congr :
cfield -> RState.rstate -> int list -> form list -> FApi.backward
| null | https://raw.githubusercontent.com/EasyCrypt/easycrypt/f87695472e70c313ef2966e20979b1afcc2e543e/src/ecAlgTactic.mli | ocaml | --------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
-------------------------------------------------------------------- | open EcSymbols
open EcTypes
open EcDecl
open EcFol
open EcAlgebra
open EcCoreGoal
val is_module_loaded : EcEnv.env -> bool
val ring_symbols : EcEnv.env -> EcDecl.rkind -> ty -> (symbol * (bool * ty)) list
val field_symbols : EcEnv.env -> ty -> (symbol * (bool * ty)) list
val ring_axioms : EcEnv.env -> ring -> (symbol * form) list
val field_axioms : EcEnv.env -> field -> (symbol * form) list
val t_ring : ring -> eq list -> form * form -> FApi.backward
val t_ring_simplify : ring -> eq list -> form * form -> FApi.backward
val t_ring_congr :
cring -> RState.rstate -> int list -> form list -> FApi.backward
val t_field : field -> eq list -> form * form -> FApi.backward
val t_field_simplify : field -> eq list -> form * form -> FApi.backward
val t_field_congr :
cfield -> RState.rstate -> int list -> form list -> FApi.backward
|
e5d775dac0a83dbb7fed6cd7fed72f4104bdf934e4d90c1c6be486d8c6f97965 | derui/okeyfum | environment_test.ml | open Okeyfum
let tests =
[
( "OKeyfum environment can change state of lock",
`Quick,
fun () ->
let module E = Okeyfum_environment in
let e = E.make Okeyfum_config.Config.empty in
let e = E.lock_state_lock ~env:e ~name:"foo" in
Alcotest.(check @@ list string) "state" [ "foo" ] (E.locked_keys e);
let e = E.lock_state_unlock ~env:e ~name:"foo" in
Alcotest.(check @@ list string) "state" [] (E.locked_keys e) );
]
| null | https://raw.githubusercontent.com/derui/okeyfum/bc47c0bea35c00d720dcde0200256a3f2e1312bd/test/environment_test.ml | ocaml | open Okeyfum
let tests =
[
( "OKeyfum environment can change state of lock",
`Quick,
fun () ->
let module E = Okeyfum_environment in
let e = E.make Okeyfum_config.Config.empty in
let e = E.lock_state_lock ~env:e ~name:"foo" in
Alcotest.(check @@ list string) "state" [ "foo" ] (E.locked_keys e);
let e = E.lock_state_unlock ~env:e ~name:"foo" in
Alcotest.(check @@ list string) "state" [] (E.locked_keys e) );
]
|
|
97ccd19f508d321599d26e854cee75aac829d5563f9967ad22b113e5856d4aeb | tomjridge/imp_fs | v2_main.ml | * Run the v2 example , using a ( somewhat hairy ) combination of
and Lwt
and Lwt *)
open Tjr_monad.With_lwt
open Shared_ctxt
let argv = Sys.argv |> Array.to_list |> List.tl
FIXME move to config
let fn = "./tmp/v2.store"
(* debug line reached *)
let line s = Printf.printf "Reached %s\n%!" s
(** Create the filesystem *)
module Create() = struct
let m =
(* Block device *)
blk_devs#lwt_open_file ~fn ~create:true ~trunc:true >>= fun bd ->
(* Test_blk_dev.make () |> fun bd -> *)
let blk_dev_ops = bd#blk_dev_ops in
let barrier = fun () -> return () in
let sync = fun () -> return () in
let with_ = V2_fs_impl.example#with_ ~blk_dev_ops ~barrier ~sync in
with_#create () >>= fun _ops ->
bd#close ()
let _ = Lwt_main.run (to_lwt m)
end
(** Restore, but don't mount *)
module Restore() = struct
let _ = Printf.printf "%s: restoring\n%!" __FILE__
let _ =
Lwt_main.run (to_lwt (
(* Block device *)
blk_devs#lwt_open_file ~fn ~create:false ~trunc:false >>= fun bd ->
(* Test_blk_dev.restore () |> fun bd -> *)
let blk_dev_ops = bd#blk_dev_ops in
let barrier = fun () -> return () in
let sync = fun () -> return () in
let with_ = V2_fs_impl.example#with_ ~blk_dev_ops ~barrier ~sync in
with_#restore () >>= fun ops ->
return ops))
end
* Mount the filesystem via FUSE
module Run() = struct
* Set lwt running , but NOT in the main thread ( we need that for
)
FUSE) *)
let () =
(* an lwt thread that just keeps going... *)
let rec t () = Lwt.Infix.(
Lwt_unix.sleep 1.0 >>= fun () ->
Printf.printf "%s: lwt thread wakes\n%!" __FILE__;
t ())
in
(* run lwt in another thread *)
let _t =
Thread.create
(fun () ->
Printf.printf "%s: Lwt main thread starts\n%!" __FILE__;
Lwt_main.run (t()))
()
in
()
(** NOTE main thread deals with fuse *)
(** Initialize filesystem operations *)
let ops : (_,_,_) Minifs_intf.ops =
Printf.printf "%s: initializing ops\n%!" __FILE__;
Lwt_preemptive.run_in_main (fun () -> to_lwt (
(* Block device *)
blk_devs#lwt_open_file ~fn ~create:false ~trunc:false >>= fun bd ->
let blk_dev_ops = bd#blk_dev_ops in
let barrier = fun () -> return () in
let sync = fun () -> return () in
let with_ = V2_fs_impl.example#with_ ~blk_dev_ops ~barrier ~sync in
with_#restore () >>= fun ops ->
return ops))
(** Run the FUSE main loop, with Lwt running in a separate
(non-Lwt) thread *)
let () =
Printf.printf "%s: running FUSE main loop\n%!" __FILE__;
let fuse_ops =
Fuse_.mk_fuse_ops
~monad_ops ~ops
~co_eta:Tjr_minifs.Lwt_util.co_eta
in
Fuse.main Sys.argv fuse_ops;
()
end (* Run *)
let _ =
match argv with
| ["create"] ->
let module X = Create() in
()
| ["restore"] ->
let module X = Restore() in
()
| _ ->
(* default: run the filesystem *)
let module X = Run() in
()
| null | https://raw.githubusercontent.com/tomjridge/imp_fs/ba86e8e9204c59b18f041bf21332a2a4846ae20b/bin/v2_main.ml | ocaml | debug line reached
* Create the filesystem
Block device
Test_blk_dev.make () |> fun bd ->
* Restore, but don't mount
Block device
Test_blk_dev.restore () |> fun bd ->
an lwt thread that just keeps going...
run lwt in another thread
* NOTE main thread deals with fuse
* Initialize filesystem operations
Block device
* Run the FUSE main loop, with Lwt running in a separate
(non-Lwt) thread
Run
default: run the filesystem | * Run the v2 example , using a ( somewhat hairy ) combination of
and Lwt
and Lwt *)
open Tjr_monad.With_lwt
open Shared_ctxt
let argv = Sys.argv |> Array.to_list |> List.tl
FIXME move to config
let fn = "./tmp/v2.store"
let line s = Printf.printf "Reached %s\n%!" s
module Create() = struct
let m =
blk_devs#lwt_open_file ~fn ~create:true ~trunc:true >>= fun bd ->
let blk_dev_ops = bd#blk_dev_ops in
let barrier = fun () -> return () in
let sync = fun () -> return () in
let with_ = V2_fs_impl.example#with_ ~blk_dev_ops ~barrier ~sync in
with_#create () >>= fun _ops ->
bd#close ()
let _ = Lwt_main.run (to_lwt m)
end
module Restore() = struct
let _ = Printf.printf "%s: restoring\n%!" __FILE__
let _ =
Lwt_main.run (to_lwt (
blk_devs#lwt_open_file ~fn ~create:false ~trunc:false >>= fun bd ->
let blk_dev_ops = bd#blk_dev_ops in
let barrier = fun () -> return () in
let sync = fun () -> return () in
let with_ = V2_fs_impl.example#with_ ~blk_dev_ops ~barrier ~sync in
with_#restore () >>= fun ops ->
return ops))
end
* Mount the filesystem via FUSE
module Run() = struct
* Set lwt running , but NOT in the main thread ( we need that for
)
FUSE) *)
let () =
let rec t () = Lwt.Infix.(
Lwt_unix.sleep 1.0 >>= fun () ->
Printf.printf "%s: lwt thread wakes\n%!" __FILE__;
t ())
in
let _t =
Thread.create
(fun () ->
Printf.printf "%s: Lwt main thread starts\n%!" __FILE__;
Lwt_main.run (t()))
()
in
()
let ops : (_,_,_) Minifs_intf.ops =
Printf.printf "%s: initializing ops\n%!" __FILE__;
Lwt_preemptive.run_in_main (fun () -> to_lwt (
blk_devs#lwt_open_file ~fn ~create:false ~trunc:false >>= fun bd ->
let blk_dev_ops = bd#blk_dev_ops in
let barrier = fun () -> return () in
let sync = fun () -> return () in
let with_ = V2_fs_impl.example#with_ ~blk_dev_ops ~barrier ~sync in
with_#restore () >>= fun ops ->
return ops))
let () =
Printf.printf "%s: running FUSE main loop\n%!" __FILE__;
let fuse_ops =
Fuse_.mk_fuse_ops
~monad_ops ~ops
~co_eta:Tjr_minifs.Lwt_util.co_eta
in
Fuse.main Sys.argv fuse_ops;
()
let _ =
match argv with
| ["create"] ->
let module X = Create() in
()
| ["restore"] ->
let module X = Restore() in
()
| _ ->
let module X = Run() in
()
|
5460b1b660d73a5cb187de2a299eac33110e3a6290a8c8df6d43f56479faf0f4 | loguntsov/reliable_udp | gen_rudp.erl | -module(gen_rudp).
-author("Sergey Loguntsov <>").
%% API
-export([
start_listener/2, start_listener/1,
stop_listener/1,
connect/4, connect/5,
close/1,
accept/2, accept/1,
is_alive/1, is_connected/1,
controlling_process/2,
async_send_binary/2, sync_send_binary/3,
send_udp/2
]).
-include("listener.hrl").
-include("socket.hrl").
-include("packet_type.hrl").
-include("priorities.hrl").
% -define(WORKERS, rudp_app:env(workers_for_each_port)).
-define(WORKERS, 1).
-define(TIMEOUT, 5000).
-spec start_listener( Port :: pos_integer(), Opts :: proplists:proplist() ) -> { ok, Lestener :: rudp_listener:listener() }.
start_listener(Port, Opts) ->
{ ok, Pid } = rudp_listener:start_link(?WORKERS, Port, Opts),
{ ok, Listener } = rudp_listener_registrar:lookup(Pid),
{ ok, Listener }.
start_listener(Port) ->
start_listener(Port, []).
-spec stop_listener( pid() | rudp_listener:listener() | pos_integer()) -> ok | undefined.
stop_listener(Pid) when is_pid(Pid) ->
rudp_listener:stop(Pid);
stop_listener(#listener{ pid = Pid }) ->
stop_listener(Pid);
stop_listener(Port) when is_integer(Port) ->
case rudp_listener_registrar:lookup(Port) of
{ ok, Listener } ->
stop_listener(Listener);
undefined -> undefined
end.
-spec connect( pid(), inet:ip_address(), pos_integer(), [], pos_integer() ) -> { ok, rudp_socket:socket() } | { error, Reason :: term() }.
connect(Listener, Address, Port, Options, Timeout) ->
{ ok, Protocol } = rudp_protocol:start_link(Listener),
case rudp_protocol:connect(Protocol, Address, Port, Options, Timeout) of
ok ->
{ ok, Socket } = rudp_protocol:get_socket(Protocol),
{ ok, Socket };
Any ->
rudp_protocol:destroy(Protocol),
Any
end.
connect(Listener, Address, Port, Options) ->
connect(Listener, Address, Port, Options, rudp_app:env(connection_timeout)).
-spec close(rudp_socket:socket()) -> ok.
close(Socket) ->
rudp_protocol:destroy(Socket#rudp_socket.protocol).
-spec accept(Listener :: rudp_listener:listener(), Timeout :: pos_integer() | infinity) -> { ok, rudp_socket:socket() } | { error, Reason :: atom() }.
accept(Listener, Timeout) ->
AcceptorPid = Listener#listener.acceptor,
case rudp_listener_acceptor:accept(AcceptorPid, Timeout) of
{ error, _ } = Error -> Error;
{ ok, IP, ParsedPacket = #connect_packet{} } ->
{ ok, ProtocolPid } = rudp_protocol:start_link(Listener),
case rudp_protocol:accept(ProtocolPid, IP, ParsedPacket, rudp_app:env(connection_timeout)) of
ok ->
{ ok, Socket } = rudp_protocol:get_socket(ProtocolPid),
{ ok, Socket };
Any ->
rudp_protocol:destroy(ProtocolPid),
Any
end
end.
accept(Listener) ->
accept(Listener, infinity).
-spec is_alive( rudp_socket:socket() ) -> boolean().
is_alive(Socket) ->
ProtocolPid = Socket#rudp_socket.protocol,
erlang:is_process_alive(ProtocolPid).
-spec is_connected( rudp_socket:socket() ) -> boolean().
is_connected(Socket) ->
ProtocolPid = Socket#rudp_socket.protocol,
case erlang:is_process_alive(ProtocolPid) of
false -> false;
true ->
state_connected =:= rudp_protocol:get_state_atom(ProtocolPid)
end.
-spec controlling_process(Socket :: rudp_socket:socket(), Pid :: pid) -> ok | { error, Reason :: atom() }.
controlling_process(Socket, Pid) ->
rudp_protocol:controlling_process(Socket#rudp_socket.protocol, Pid).
async_send_binary(Socket, Binary) ->
rudp_socket:sender(Socket, fun(Pid) ->
rudp_sender:async_send_binary(Pid, ?PRIORITY_LOW, binary, Binary)
end).
sync_send_binary(Socket, Binary, Timeout) ->
rudp_socket:sender(Socket, fun(Pid) ->
rudp_sender:sync_send_binary(Pid, ?PRIORITY_LOW, binary, Binary, Timeout)
end).
send_udp(_Socket, Binary) when size(Binary) > 1024 -> { error, big_packet };
send_udp(Socket, Binary) ->
rudp_socket:sender(Socket, fun(Pid) ->
rudp_sender:async_send_binary(Pid, ?PRIORITY_MIDDLE, udp, Binary)
end).
| null | https://raw.githubusercontent.com/loguntsov/reliable_udp/6544c08a551397182f33ca89ce2ff1db470a0daa/src/gen_rudp.erl | erlang | API
-define(WORKERS, rudp_app:env(workers_for_each_port)). | -module(gen_rudp).
-author("Sergey Loguntsov <>").
-export([
start_listener/2, start_listener/1,
stop_listener/1,
connect/4, connect/5,
close/1,
accept/2, accept/1,
is_alive/1, is_connected/1,
controlling_process/2,
async_send_binary/2, sync_send_binary/3,
send_udp/2
]).
-include("listener.hrl").
-include("socket.hrl").
-include("packet_type.hrl").
-include("priorities.hrl").
-define(WORKERS, 1).
-define(TIMEOUT, 5000).
-spec start_listener( Port :: pos_integer(), Opts :: proplists:proplist() ) -> { ok, Lestener :: rudp_listener:listener() }.
start_listener(Port, Opts) ->
{ ok, Pid } = rudp_listener:start_link(?WORKERS, Port, Opts),
{ ok, Listener } = rudp_listener_registrar:lookup(Pid),
{ ok, Listener }.
start_listener(Port) ->
start_listener(Port, []).
-spec stop_listener( pid() | rudp_listener:listener() | pos_integer()) -> ok | undefined.
stop_listener(Pid) when is_pid(Pid) ->
rudp_listener:stop(Pid);
stop_listener(#listener{ pid = Pid }) ->
stop_listener(Pid);
stop_listener(Port) when is_integer(Port) ->
case rudp_listener_registrar:lookup(Port) of
{ ok, Listener } ->
stop_listener(Listener);
undefined -> undefined
end.
-spec connect( pid(), inet:ip_address(), pos_integer(), [], pos_integer() ) -> { ok, rudp_socket:socket() } | { error, Reason :: term() }.
connect(Listener, Address, Port, Options, Timeout) ->
{ ok, Protocol } = rudp_protocol:start_link(Listener),
case rudp_protocol:connect(Protocol, Address, Port, Options, Timeout) of
ok ->
{ ok, Socket } = rudp_protocol:get_socket(Protocol),
{ ok, Socket };
Any ->
rudp_protocol:destroy(Protocol),
Any
end.
connect(Listener, Address, Port, Options) ->
connect(Listener, Address, Port, Options, rudp_app:env(connection_timeout)).
-spec close(rudp_socket:socket()) -> ok.
close(Socket) ->
rudp_protocol:destroy(Socket#rudp_socket.protocol).
-spec accept(Listener :: rudp_listener:listener(), Timeout :: pos_integer() | infinity) -> { ok, rudp_socket:socket() } | { error, Reason :: atom() }.
accept(Listener, Timeout) ->
AcceptorPid = Listener#listener.acceptor,
case rudp_listener_acceptor:accept(AcceptorPid, Timeout) of
{ error, _ } = Error -> Error;
{ ok, IP, ParsedPacket = #connect_packet{} } ->
{ ok, ProtocolPid } = rudp_protocol:start_link(Listener),
case rudp_protocol:accept(ProtocolPid, IP, ParsedPacket, rudp_app:env(connection_timeout)) of
ok ->
{ ok, Socket } = rudp_protocol:get_socket(ProtocolPid),
{ ok, Socket };
Any ->
rudp_protocol:destroy(ProtocolPid),
Any
end
end.
accept(Listener) ->
accept(Listener, infinity).
-spec is_alive( rudp_socket:socket() ) -> boolean().
is_alive(Socket) ->
ProtocolPid = Socket#rudp_socket.protocol,
erlang:is_process_alive(ProtocolPid).
-spec is_connected( rudp_socket:socket() ) -> boolean().
is_connected(Socket) ->
ProtocolPid = Socket#rudp_socket.protocol,
case erlang:is_process_alive(ProtocolPid) of
false -> false;
true ->
state_connected =:= rudp_protocol:get_state_atom(ProtocolPid)
end.
-spec controlling_process(Socket :: rudp_socket:socket(), Pid :: pid) -> ok | { error, Reason :: atom() }.
controlling_process(Socket, Pid) ->
rudp_protocol:controlling_process(Socket#rudp_socket.protocol, Pid).
async_send_binary(Socket, Binary) ->
rudp_socket:sender(Socket, fun(Pid) ->
rudp_sender:async_send_binary(Pid, ?PRIORITY_LOW, binary, Binary)
end).
sync_send_binary(Socket, Binary, Timeout) ->
rudp_socket:sender(Socket, fun(Pid) ->
rudp_sender:sync_send_binary(Pid, ?PRIORITY_LOW, binary, Binary, Timeout)
end).
send_udp(_Socket, Binary) when size(Binary) > 1024 -> { error, big_packet };
send_udp(Socket, Binary) ->
rudp_socket:sender(Socket, fun(Pid) ->
rudp_sender:async_send_binary(Pid, ?PRIORITY_MIDDLE, udp, Binary)
end).
|
6b6163006f763b8ed246cf546a3f47dbe806d4189238ad748249df8d2a00407a | biocom-uib/vpf-tools | VirusClass.hs | # options_ghc -Wno - partial - type - signatures #
# language ApplicativeDo #
# language BlockArguments #
# language DeriveGeneric #
{-# language DerivingVia #-}
{-# language PartialTypeSignatures #-}
# language OverloadedLabels #
# language StaticPointers #
{-# language Strict #-}
module VPF.Model.VirusClass where
import GHC.Generics (Generic)
import Control.Carrier.Error.Excepts (ExceptsT, runExceptsT, Errors, throwErrors)
import Control.Distributed.SClosure
import Control.Effect.Reader
import Control.Effect.Distributed
import Control.Effect.Sum.Extra (HasAny)
import Control.Effect.Throw
import qualified Control.Foldl as Fold
import qualified Control.Lens as L
import Control.Monad
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Trans.Control (MonadBaseControl)
import Control.Monad.Trans.Reader (runReaderT)
import qualified Data.Aeson as Aeson
import Data.Bifunctor (first)
import qualified Data.ByteString.Char8 as BC
import Data.List (genericLength, isPrefixOf, isSuffixOf)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
import Data.Monoid (Ap(..))
import Data.Proxy (Proxy(..))
import Data.Semigroup (stimes)
import Data.Store (Store)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Vector (Vector)
import qualified Data.Vector as Vec
import qualified Data.Vinyl as V
import Pipes (Producer, Pipe, (>->))
import qualified Pipes as P
import qualified Pipes.Lift as P
import qualified Pipes.Prelude as P
import Pipes.Safe (SafeT, runSafeT)
import qualified Pipes.Safe as PS
import Pipes.Concurrent.Async ((>||>), (>-|>))
import qualified Pipes.Concurrent.Async as PA
import qualified Pipes.Concurrent.Synchronize as PA
import System.Directory as D
import System.FilePath ((</>), takeFileName)
import System.IO as IO
import VPF.Ext.Prodigal (Prodigal, prodigal)
import VPF.Ext.HMMER.Search (HMMSearch, ProtSearchHitCols, hmmsearch)
import qualified VPF.Ext.HMMER.Search.Cols as HMM
import qualified VPF.Ext.HMMER.TableFormat as Tbl
import VPF.Formats
import VPF.Frames.Dplyr.Ops
import VPF.Frames.Types
import qualified VPF.Frames.Dplyr as F
import qualified VPF.Frames.DSV as DSV
import qualified VPF.Frames.InCore as F
import qualified VPF.Model.Cols as M
import qualified VPF.Model.Class as Cls
import qualified VPF.Model.Class.Cols as Cls
import qualified VPF.Util.Hash as Hash
import qualified VPF.Util.Fasta as FA
import qualified VPF.Util.FS as FS
import qualified VPF.Util.Progress as Progress
newtype GenomeChunkKey = GenomeChunkKey { getGenomeChunkHash :: String }
deriving Store via String
deriving Aeson.FromJSON via String
deriving Aeson.ToJSON via String
newtype WorkDir = WorkDir (Path Directory)
deriving Store via (Path Directory)
type AggregatedHitsCols = '[M.VirusName, M.ModelName, M.ProteinHitScore]
data ModelConfig = ModelConfig
{ modelEValueThreshold :: Double
, modelVirusNameExtractor :: Text -> Text
}
type PredictedCols = '[M.VirusName, Cls.ClassName, M.MembershipRatio, M.VirusHitScore, M.ConfidenceScore]
createGenomesSubdir :: (MonadIO m, Has (Reader WorkDir) sig m) => m (Path Directory)
createGenomesSubdir = do
WorkDir wd <- ask
let fp = untag wd </> "genomes"
liftIO $ D.createDirectoryIfMissing True fp
return (Tagged fp)
createProteinsSubdir :: (MonadIO m, Has (Reader WorkDir) sig m) => m (Path Directory)
createProteinsSubdir = do
WorkDir wd <- ask
let fp = untag wd </> "proteins"
liftIO $ D.createDirectoryIfMissing True fp
return (Tagged fp)
createHitsSubdir :: (MonadIO m, Has (Reader WorkDir) sig m) => m (Path Directory)
createHitsSubdir = do
WorkDir wd <- ask
let fp = untag wd </> "search"
liftIO $ D.createDirectoryIfMissing True fp
return (Tagged fp)
createProcessedHitsSubdir :: (MonadIO m, Has (Reader WorkDir) sig m) => m (Path Directory)
createProcessedHitsSubdir = do
WorkDir wd <- ask
let fp = untag wd </> "processed"
liftIO $ D.createDirectoryIfMissing True fp
return (Tagged fp)
getGenomeChunkKey :: Path (FASTA Nucleotide) -> IO GenomeChunkKey
getGenomeChunkKey f =
fmap (GenomeChunkKey . BC.unpack . Hash.digestToHex)
(Hash.hashFileSHA512t_256 (untag f))
parseGenomesFileName :: Path (FASTA Nucleotide) -> Either (Path (FASTA Nucleotide)) GenomeChunkKey
parseGenomesFileName (Tagged fp) =
if isPrefixOf prefix fileName && isSuffixOf suffix fileName then
let
withoutPrefix = drop (length prefix) fileName
withoutSuffix = take (length withoutPrefix - length suffix) withoutPrefix
in
Right (GenomeChunkKey withoutSuffix)
else
Left (Tagged fileName)
where
fileName = takeFileName fp
prefix = "split-hits-"
suffix = ".fna"
writeGenomesFile ::
( MonadIO m
, Has (Reader WorkDir) sig m
)
=> Producer (FA.FastaEntry Nucleotide) (SafeT IO) ()
-> m (GenomeChunkKey, Path (FASTA Nucleotide))
writeGenomesFile genomes = do
genomesDir <- createGenomesSubdir
tmpGenomesFile <- FS.emptyTmpFile genomesDir "split-genomes.fna"
liftIO $ runSafeT $ P.runEffect $ genomes >-> FA.fastaFileWriter tmpGenomesFile
key <- liftIO $ getGenomeChunkKey tmpGenomesFile
let genomesFile = genomesFileFor genomesDir key
liftIO $ D.renameFile (untag tmpGenomesFile) (untag genomesFile)
return (key, genomesFile)
genomesFileFor :: Path Directory -> GenomeChunkKey -> Path (FASTA Nucleotide)
genomesFileFor dir (GenomeChunkKey hash) =
Tagged (untag dir </> name)
where
name = "split-genomes-" ++ hash ++ ".fna"
proteinFileFor :: Path Directory -> GenomeChunkKey -> Path (FASTA Aminoacid)
proteinFileFor dir (GenomeChunkKey hash) =
Tagged (untag dir </> name)
where
name = "split-proteins-" ++ hash ++ ".faa"
hitsFileFor :: Path Directory -> GenomeChunkKey -> Path (HMMERTable ProtSearchHitCols)
hitsFileFor dir (GenomeChunkKey hash) =
Tagged (untag dir </> name)
where
name = "split-hits-" ++ hash ++ ".hmmout"
processedHitsFileFor :: Path Directory -> GenomeChunkKey -> Path (DSV "\t" AggregatedHitsCols)
processedHitsFileFor dir (GenomeChunkKey hash) =
Tagged (untag dir </> name)
where
name = "processed-hits-" ++ hash ++ ".tsv"
searchGenomeHits ::
( MonadBaseControl IO m
, MonadIO m
, Has HMMSearch sig m
, Has Prodigal sig m
, Has (Reader WorkDir) sig m
)
=> GenomeChunkKey
-> Path (FASTA Nucleotide)
-> Path HMMERModel
-> m (Path (FASTA Aminoacid), Path (HMMERTable ProtSearchHitCols))
searchGenomeHits key genomesFile vpfsFile = do
protsDir <- createProteinsSubdir
let protsFile = proteinFileFor protsDir key
FS.whenNotExists protsFile $ FS.atomicCreateFile protsFile $ \tmpProtsFile ->
prodigal genomesFile tmpProtsFile Nothing
hitsDir <- createHitsSubdir
let hitsFile = hitsFileFor hitsDir key
FS.whenNotExists hitsFile $ FS.atomicCreateFile hitsFile $ \tmpHitsFile -> do
protsFileIsEmpty <- liftIO $ isEmptyFAA protsFile
if protsFileIsEmpty then
liftIO $ createEmptyHitsFile tmpHitsFile
else
hmmsearch vpfsFile protsFile tmpHitsFile
return (protsFile, hitsFile)
where
isEmptyFAA :: Path (FASTA Aminoacid) -> IO Bool
isEmptyFAA fp = runSafeT $ do
firstItem <- P.next (FA.fastaFileReader fp)
case firstItem of
Left (Left _e) -> return False
Left (Right ()) -> return True
Right (_, _) -> return False
createEmptyHitsFile :: Path (HMMERTable ProtSearchHitCols) -> IO ()
createEmptyHitsFile fp = IO.withFile (untag fp) IO.WriteMode $ \_ -> return ()
aggregateHits :: forall sig m.
( Has (Reader ModelConfig) sig m
, Has (Throw DSV.ParseError) sig m
, Has (Throw FA.ParseError) sig m
, MonadIO m
)
=> Path (FASTA Aminoacid)
-> Path (HMMERTable ProtSearchHitCols)
-> m (FrameRec AggregatedHitsCols)
aggregateHits aminoacidsFile hitsFile = do
proteinSizes <- loadProteinSizes
let hitRows = Tbl.produceRows hitsFile
thr <- asks modelEValueThreshold
getVirusName <- asks modelVirusNameExtractor
hitsFrame <- DSV.inCoreAoSExc $
hitRows
>-> P.filter (\row -> row^.HMM.sequenceEValue <= thr)
>-> P.map V.rcast
return $ hitsFrame
& F.mutate1 @"virus_name" (getVirusName . L.view HMM.targetName)
& aggregate proteinSizes
where
fastaEntryToRow :: FA.FastaEntry Aminoacid -> Record '[M.ProteinName, M.KBaseSize]
fastaEntryToRow entry =
V.fieldRec
( #protein_name =: FA.removeNameComments (FA.entryName entry)
, #k_base_size =: fromIntegral (FA.entrySeqNumBases entry) / 1000
)
loadProteinSizes :: m (GroupedFrameRec (Field M.ProteinName) '[M.KBaseSize])
loadProteinSizes = do
(colVecs, errs) <- liftIO $ runSafeT $
Fold.impurely P.foldM' (F.colVecsFoldM 128) $
FA.fastaFileReader aminoacidsFile
>-> P.map fastaEntryToRow
either throwError return errs
return $ F.setIndex @"protein_name" (F.fromColVecs colVecs)
aggregate :: GroupedFrameRec (Field M.ProteinName) '[M.KBaseSize]
-> FrameRec '[M.VirusName, HMM.TargetName, HMM.QueryName, HMM.SequenceScore]
-> FrameRec '[M.VirusName, M.ModelName, M.ProteinHitScore]
aggregate proteinSizes =
F.reindexed @"virus_name" . F.groups %~ do
F.cat
|. F.reindexed @"target_name" %~ do
F.cat
|. F.renameIndexTo @"protein_name"
|. F.groups %~ F.top @(F.Desc "sequence_score") 1
|. F.innerJoin proteinSizes
|. F.summarizing @"query_name" %~ do
let normalizedScore = F.give $ F.val @"sequence_score" / F.val @"k_base_size"
aggNormScore <- L.sumOf (F.foldedRows . L.to normalizedScore)
return (F.singleField @"protein_hit_score" aggNormScore)
|. F.rename @"query_name" @"model_name"
|. F.copySoA
processHits ::
( MonadIO m
, Has (Reader ModelConfig) sig m
, Has (Reader WorkDir) sig m
, Has (Throw DSV.ParseError) sig m
, Has (Throw FA.ParseError) sig m
)
=> GenomeChunkKey
-> Path (FASTA Aminoacid)
-> Path (HMMERTable ProtSearchHitCols)
-> m (Path (DSV "\t" AggregatedHitsCols))
processHits key protsFile hitsFile = do
aggregatedHits <- aggregateHits protsFile hitsFile
processedHitsDir <- createProcessedHitsSubdir
let processedHitsFile = processedHitsFileFor processedHitsDir key
writerOpts = DSV.defWriterOptions '\t'
liftIO $ runSafeT $ FS.atomicCreateFile processedHitsFile $ \tmpFile ->
DSV.writeDSV writerOpts (FS.fileWriter (untag tmpFile)) aggregatedHits
return processedHitsFile
predictMembership ::
Cls.ClassificationParams
-> GroupedFrameRec (Field M.VirusName) '[M.ModelName, M.ProteinHitScore]
-> GroupedFrameRec (Field M.VirusName)
'[Cls.ClassName, M.MembershipRatio, M.VirusHitScore, M.ConfidenceScore]
predictMembership classParams = F.groups %~ do
F.cat
|. L.iso (F.setIndex @"model_name") F.dropIndex %~
F.innerJoin (Cls.modelClasses classParams)
|. F.summarizing @"class_name" %~ do
let products = F.give $
F.val @"protein_hit_score"
* F.val @"class_percent"/100
* catWeight (F.val @"class_cat")
classScore <- L.sumOf (F.foldedRows . L.to products)
return (F.singleField @"class_score" classScore)
|. F.arrange @(F.Desc "class_score")
|. F.copySoA
|. id %~ do
totalScore <- L.sumOf (F.foldedRows . F.field @"class_score")
let confidence = percentileRank (Cls.scoreSamples classParams) (Tagged totalScore)
F.cat
|. F.mutate1 @"virus_hit_score" (const totalScore)
|. F.mutate1 @"confidence_score" (const confidence)
|. F.mutate1 @"membership_ratio" (F.give $ F.val @"class_score" / totalScore)
|. F.select_
where
percentileRank :: Ord a => Vector a -> a -> Double
percentileRank v a =
case Vec.span (< a) v of
(less, v') ->
case Vec.span (== a) v' of
(equal, _) ->
let c = fromIntegral $ Vec.length less
f = fromIntegral $ Vec.length equal
n = fromIntegral $ Vec.length v
in (c + 0.5*f) / n
catWeight :: Int -> Double
catWeight cat = (5 - fromIntegral cat) / 4
-- asynchronous versions
data SearchHitsConcurrencyOpts = SearchHitsConcurrencyOpts
{ fastaChunkSize :: Int
, numSearchingWorkers :: Int
}
deriving Generic
instance Store SearchHitsConcurrencyOpts
asyncSearchHits :: forall sig m.
( MonadBaseControl IO m
, MonadIO m
, Has HMMSearch sig m
, Has Prodigal sig m
, Has (Reader WorkDir) sig m
)
=> SearchHitsConcurrencyOpts
-> Path HMMERModel
-> [(GenomeChunkKey, Path (FASTA Nucleotide))]
-> m [(GenomeChunkKey, Path (FASTA Aminoacid), Path (HMMERTable ProtSearchHitCols))]
asyncSearchHits concOpts vpfsFile genomesFiles = do
let nworkers = numSearchingWorkers concOpts
genomesFilesProducer <- liftIO $ PA.stealingEach genomesFiles
PA.feedAsyncConsumer genomesFilesProducer $
P.mapM (\(key, genomesFile) -> do
(protsFile, hitsFile) <- searchGenomeHits key genomesFile vpfsFile
return (key, protsFile, hitsFile))
>-|>
stimes nworkers PA.toListM
distribSearchHits :: forall sigm m sign n w.
( MonadBaseControl IO m
, MonadIO m
, Has (Reader WorkDir) sigm m
, Has (Throw FA.ParseError) sigm m
, HasAny Distributed (Distributed n w) sigm m
, Typeable sign
, Typeable n
)
=> SDict
( MonadBaseControl IO n
, MonadIO n
, Has HMMSearch sign n
, Has Prodigal sign n
, Has (Reader WorkDir) sign n
)
-> SearchHitsConcurrencyOpts
-> Path HMMERModel
-> Path (FASTA Nucleotide)
-> m [(GenomeChunkKey, Path (FASTA Aminoacid), Path (HMMERTable ProtSearchHitCols))]
distribSearchHits sdict concOpts vpfsFile genomesFile = do
nslaves <- getNumWorkers_
wd <- ask @WorkDir
let genomesChunkWriter :: Pipe [FA.FastaEntry Nucleotide] (Integer, (GenomeChunkKey, Path _)) (SafeT IO) r
genomesChunkWriter = P.mapM $ \chunk -> do
kp <- liftIO $ runReaderT (writeGenomesFile (P.each chunk)) wd
return (genericLength chunk, kp)
chunkGenomeCount :: Pipe [(Integer, a)] (Integer, [a]) (SafeT IO) r
chunkGenomeCount = P.map (first sum . unzip)
genomesFilesProducer :: PA.AsyncProducer (Integer, [(_, _)]) (SafeT IO) () m () <- liftIO $
FA.fastaFileReader genomesFile
& PA.bufferedChunks (fromIntegral $ fastaChunkSize concOpts)
& (>-> genomesChunkWriter)
& PA.bufferedChunks (fromIntegral $ numSearchingWorkers concOpts)
& (>-> chunkGenomeCount)
& PA.stealingAsyncProducer (nslaves+1)
& fmap \ap -> ap
& PA.defaultOutput (Right ())
& PA.hoist (liftIO . runSafeT)
& PA.mapResultM (either throwError return)
let asyncSearchHits' kps =
static (\Dict -> asyncSearchHits @sign @n)
<:*> sdict
<:*> spureWith (static Dict) concOpts
<:*> spureWith (static Dict) vpfsFile
<:*> spureWith (static Dict) kps
progress <- liftIO $ Progress.init 0 (\nseqs -> "processed " ++ show nseqs ++ " sequences")
let updateProgress n = liftIO $ Progress.update progress (+ n)
rs <- withWorkers_ $ \w -> do
((), r) <- PA.runAsyncEffect (nslaves+1) $
genomesFilesProducer
>||>
P.mapM (\(n, kps) -> runInWorker_ w (static Dict) (asyncSearchHits' kps) <* updateProgress n)
>-|>
P.concat
>-|>
PA.toListM
return r
liftIO $ Progress.finish progress Nothing
return rs
newtype ProcessHitsConcurrencyOpts = ProcessHitsConcurrencyOpts
{ numProcessingHitsWorkers :: Int
}
asyncProcessHits :: forall sig m.
( MonadIO m
, MonadBaseControl IO m
, Has (Reader ModelConfig) sig m
, Has (Reader WorkDir) sig m
, Has (Throw DSV.ParseError) sig m
, Has (Throw FA.ParseError) sig m
)
=> ProcessHitsConcurrencyOpts
-> [(GenomeChunkKey, Path (FASTA Aminoacid), Path (HMMERTable ProtSearchHitCols))]
-> m [(GenomeChunkKey, Path (DSV "\t" AggregatedHitsCols))]
asyncProcessHits concOpts hitsFiles = do
let nworkers = numProcessingHitsWorkers concOpts
hitsFilesProducer <- liftIO $ PA.stealingEach hitsFiles
PA.feedAsyncConsumer hitsFilesProducer $
P.mapM (\(key, protsFile, hitsFile) -> (,) key <$> processHits key protsFile hitsFile)
>-|>
stimes nworkers PA.toListM
newtype PredictMembershipConcurrencyOpts = PredictMembershipConcurrencyOpts
{ numPredictingWorkers :: Int
}
asyncPredictMemberships :: forall sig m.
( MonadBaseControl IO m
, MonadIO m
, Has (Throw DSV.ParseError) sig m
)
=> PredictMembershipConcurrencyOpts
-> Map (Field Cls.ClassKey) Cls.ClassificationFiles
-> [Path (DSV "\t" AggregatedHitsCols)]
-> Path Directory
-> m [Path (DSV "\t" PredictedCols)]
asyncPredictMemberships concOpts classFiles aggHitsFiles outputDir = do
let nworkers = fromIntegral $ numPredictingWorkers concOpts
liftIO $ D.createDirectoryIfMissing True (untag outputDir)
liftIO $ IO.hPutStrLn IO.stderr $ "loading VPF classifications"
classes <- mapM (L._2 %%~ Cls.loadClassificationParams) (Map.toAscList classFiles)
(Ap errors, paths) <- liftIO $ runSafeT $ do
let sep = T.singleton '\t'
parserOpts = DSV.defParserOptions '\t'
classesWithHandles <-
forM classes \(classKey, classParams) -> do
let path = untag outputDir </> T.unpack (untag classKey) ++ ".tsv"
h <- PS.mask_ $ do
hdl <- liftIO $ IO.openFile path IO.WriteMode
PS.register (IO.hClose hdl)
return hdl
liftIO $ T.hPutStrLn h (DSV.headerToDSV @PredictedCols Proxy sep)
return (Tagged path, (classParams, h))
let (paths, classHandles) = unzip classesWithHandles
liftIO $ IO.hPutStrLn IO.stderr $ "found " ++ show (length aggHitsFiles) ++ " aggregated hit files"
Progress.tracking 0 (\nchunks -> "predicted " ++ show nchunks ++ " units") $ \progress -> do
hitChunks <- liftIO $ PA.stealingEach aggHitsFiles
let toBeWritten :: PA.AsyncProducer' (IO.Handle, Vec.Vector Text) IO (Ap (Either _) ())
toBeWritten = PA.duplicatingAsyncProducer $
(pure () <$ hitChunks)
>->
runApExceptsP (P.mapM (DSV.readFrame parserOpts))
>->
scheduleForWriting classHandles sep
liftIO $ PA.runAsyncEffect nworkers $
stimes nworkers (PA.defaultOutput (pure ()) toBeWritten)
>||>
-- we don't want concurrent writes
(paths <$ writeOutput progress)
case errors of
Left errs -> throwErrors @'[DSV.ParseError] errs
Right () -> return paths
where
runApExceptsP ::
Monad n
=> P.Proxy a' a b' b (ExceptsT es n) r
-> P.Proxy a' a b' b n (Ap (Either (Errors es)) r)
runApExceptsP = fmap Ap . runExceptsT . P.distribute
scheduleForWriting ::
[(Cls.ClassificationParams, IO.Handle)]
-> Text
-> Pipe (FrameRec AggregatedHitsCols) (IO.Handle, Vec.Vector Text) IO r
scheduleForWriting classHandles sep =
P.for P.cat \aggHits -> do
let indexed = F.setIndex @"virus_name" aggHits
forM_ classHandles \(classParams, h) -> do
let predictedDSV = predictMembership classParams indexed
& F.resetIndex
& F.rows %~ DSV.rowToDSV sep
& F.toRowsVec
P.yield $! (h, predictedDSV)
writeOutput :: Progress.State Int -> PA.AsyncConsumer' (IO.Handle, Vec.Vector Text) IO ()
writeOutput progress =
PA.duplicatingAsyncConsumer $
P.mapM_ \(h, rows) -> do
mapM_ (T.hPutStrLn h) rows
Progress.update progress (+1)
-- stopping/resuming from checkpoints
data Checkpoint
= ContinueSearchingHits
| ContinueFromHitsFiles [GenomeChunkKey]
| ContinueFromProcessedHits [GenomeChunkKey]
deriving Generic
instance Aeson.FromJSON Checkpoint
instance Aeson.ToJSON Checkpoint
newtype CheckpointLoadError = CheckpointJSONLoadError String
deriving Store via CheckpointLoadError
data ClassificationStep
= SearchHitsStep {
runSearchHitsStep :: forall sigm m sign n w.
( MonadBaseControl IO m
, MonadIO m
, Has (Reader WorkDir) sigm m
, Has (Throw FA.ParseError) sigm m
, HasAny Distributed (Distributed n w) sigm m
, Typeable sign
, Typeable n
)
=> SDict
( MonadBaseControl IO n
, MonadIO n
, Has HMMSearch sign n
, Has Prodigal sign n
, Has (Reader WorkDir) sign n
)
-> SearchHitsConcurrencyOpts
-> Path HMMERModel
-> Path (FASTA Nucleotide)
-> m Checkpoint
}
| ProcessHitsStep {
runProcessHitsStep :: forall sig m.
( MonadBaseControl IO m
, MonadIO m
, Has (Reader ModelConfig) sig m
, Has (Reader WorkDir) sig m
, Has (Throw DSV.ParseError) sig m
, Has (Throw FA.ParseError) sig m
)
=> ProcessHitsConcurrencyOpts
-> m Checkpoint
}
| PredictMembershipStep {
runPredictMembershipStep :: forall sig m.
( MonadBaseControl IO m
, MonadIO m
, Has (Reader WorkDir) sig m
, Has (Throw DSV.ParseError) sig m
)
=> PredictMembershipConcurrencyOpts
-> Map (Field Cls.ClassKey) Cls.ClassificationFiles
-> Path Directory
-> m [Path (DSV "\t" PredictedCols)]
}
tryLoadCheckpoint ::
( MonadIO m
, Has (Throw CheckpointLoadError) sig m
)
=> Path (JSON Checkpoint)
-> m (Maybe Checkpoint)
tryLoadCheckpoint checkpointFile = do
exists <- liftIO $ D.doesFileExist (untag checkpointFile)
if exists then do
r <- liftIO $ Aeson.eitherDecodeFileStrict' (untag checkpointFile)
case r of
Left e -> throwError (CheckpointJSONLoadError e)
Right checkpoint -> return (Just checkpoint)
else
return Nothing
saveCheckpoint :: Path (JSON Checkpoint) -> Checkpoint -> IO ()
saveCheckpoint checkpointFile checkpoint =
FS.atomicCreateFile checkpointFile $ \tmp ->
Aeson.encodeFile (untag tmp) checkpoint
checkpointStep :: Checkpoint -> ClassificationStep
checkpointStep checkpoint =
case checkpoint of
ContinueSearchingHits ->
SearchHitsStep $ \sdict concOpts vpfsFile genomesFile -> do
r <- distribSearchHits sdict concOpts vpfsFile genomesFile
return $ ContinueFromHitsFiles (map (L.view L._1) r)
ContinueFromHitsFiles keys ->
ProcessHitsStep $ \concOpts -> do
protsSubdir <- createProteinsSubdir
hitsSubdir <- createHitsSubdir
let hitsFiles =
[ (key, proteinFileFor protsSubdir key, hitsFileFor hitsSubdir key)
| key <- keys
]
r <- asyncProcessHits concOpts hitsFiles
return (ContinueFromProcessedHits (map fst r))
ContinueFromProcessedHits keys ->
PredictMembershipStep $ \concOpts classFiles outputDir -> do
aggHitsSubdir <- createProcessedHitsSubdir
let aggHitsFiles = map (processedHitsFileFor aggHitsSubdir) keys
asyncPredictMemberships concOpts classFiles aggHitsFiles outputDir
-- run the whole process
checkpointFileFor :: WorkDir -> GenomeChunkKey -> Path (JSON Checkpoint)
checkpointFileFor (WorkDir dir) (GenomeChunkKey hash) =
Tagged (untag dir </> name)
where
name = "checkpoint-" ++ hash ++ ".json"
runClassification :: forall sig m a.
( MonadIO m
, Has (Reader WorkDir) sig m
, Has (Throw CheckpointLoadError) sig m
)
=> Path (FASTA Nucleotide)
-> ((Checkpoint -> m a) -> ClassificationStep -> m a)
-> m a
runClassification fullGenomesFile runSteps = do
key <- liftIO $ getGenomeChunkKey fullGenomesFile
wd <- ask
let checkpointFile = checkpointFileFor wd key
maybeCheckpoint <- tryLoadCheckpoint checkpointFile
let checkpoint = fromMaybe ContinueSearchingHits maybeCheckpoint
runSteps (resume checkpointFile) (checkpointStep checkpoint)
where
resume :: Path (JSON Checkpoint) -> Checkpoint -> m a
resume checkpointFile checkpoint = do
liftIO $ saveCheckpoint checkpointFile checkpoint
runSteps (resume checkpointFile) (checkpointStep checkpoint)
| null | https://raw.githubusercontent.com/biocom-uib/vpf-tools/11abf5645f0b155e20d13a398fb74f2e75f4b4a9/src/VPF/Model/VirusClass.hs | haskell | # language DerivingVia #
# language PartialTypeSignatures #
# language Strict #
asynchronous versions
we don't want concurrent writes
stopping/resuming from checkpoints
run the whole process | # options_ghc -Wno - partial - type - signatures #
# language ApplicativeDo #
# language BlockArguments #
# language DeriveGeneric #
# language OverloadedLabels #
# language StaticPointers #
module VPF.Model.VirusClass where
import GHC.Generics (Generic)
import Control.Carrier.Error.Excepts (ExceptsT, runExceptsT, Errors, throwErrors)
import Control.Distributed.SClosure
import Control.Effect.Reader
import Control.Effect.Distributed
import Control.Effect.Sum.Extra (HasAny)
import Control.Effect.Throw
import qualified Control.Foldl as Fold
import qualified Control.Lens as L
import Control.Monad
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Trans.Control (MonadBaseControl)
import Control.Monad.Trans.Reader (runReaderT)
import qualified Data.Aeson as Aeson
import Data.Bifunctor (first)
import qualified Data.ByteString.Char8 as BC
import Data.List (genericLength, isPrefixOf, isSuffixOf)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
import Data.Monoid (Ap(..))
import Data.Proxy (Proxy(..))
import Data.Semigroup (stimes)
import Data.Store (Store)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Vector (Vector)
import qualified Data.Vector as Vec
import qualified Data.Vinyl as V
import Pipes (Producer, Pipe, (>->))
import qualified Pipes as P
import qualified Pipes.Lift as P
import qualified Pipes.Prelude as P
import Pipes.Safe (SafeT, runSafeT)
import qualified Pipes.Safe as PS
import Pipes.Concurrent.Async ((>||>), (>-|>))
import qualified Pipes.Concurrent.Async as PA
import qualified Pipes.Concurrent.Synchronize as PA
import System.Directory as D
import System.FilePath ((</>), takeFileName)
import System.IO as IO
import VPF.Ext.Prodigal (Prodigal, prodigal)
import VPF.Ext.HMMER.Search (HMMSearch, ProtSearchHitCols, hmmsearch)
import qualified VPF.Ext.HMMER.Search.Cols as HMM
import qualified VPF.Ext.HMMER.TableFormat as Tbl
import VPF.Formats
import VPF.Frames.Dplyr.Ops
import VPF.Frames.Types
import qualified VPF.Frames.Dplyr as F
import qualified VPF.Frames.DSV as DSV
import qualified VPF.Frames.InCore as F
import qualified VPF.Model.Cols as M
import qualified VPF.Model.Class as Cls
import qualified VPF.Model.Class.Cols as Cls
import qualified VPF.Util.Hash as Hash
import qualified VPF.Util.Fasta as FA
import qualified VPF.Util.FS as FS
import qualified VPF.Util.Progress as Progress
newtype GenomeChunkKey = GenomeChunkKey { getGenomeChunkHash :: String }
deriving Store via String
deriving Aeson.FromJSON via String
deriving Aeson.ToJSON via String
newtype WorkDir = WorkDir (Path Directory)
deriving Store via (Path Directory)
type AggregatedHitsCols = '[M.VirusName, M.ModelName, M.ProteinHitScore]
data ModelConfig = ModelConfig
{ modelEValueThreshold :: Double
, modelVirusNameExtractor :: Text -> Text
}
type PredictedCols = '[M.VirusName, Cls.ClassName, M.MembershipRatio, M.VirusHitScore, M.ConfidenceScore]
createGenomesSubdir :: (MonadIO m, Has (Reader WorkDir) sig m) => m (Path Directory)
createGenomesSubdir = do
WorkDir wd <- ask
let fp = untag wd </> "genomes"
liftIO $ D.createDirectoryIfMissing True fp
return (Tagged fp)
createProteinsSubdir :: (MonadIO m, Has (Reader WorkDir) sig m) => m (Path Directory)
createProteinsSubdir = do
WorkDir wd <- ask
let fp = untag wd </> "proteins"
liftIO $ D.createDirectoryIfMissing True fp
return (Tagged fp)
createHitsSubdir :: (MonadIO m, Has (Reader WorkDir) sig m) => m (Path Directory)
createHitsSubdir = do
WorkDir wd <- ask
let fp = untag wd </> "search"
liftIO $ D.createDirectoryIfMissing True fp
return (Tagged fp)
createProcessedHitsSubdir :: (MonadIO m, Has (Reader WorkDir) sig m) => m (Path Directory)
createProcessedHitsSubdir = do
WorkDir wd <- ask
let fp = untag wd </> "processed"
liftIO $ D.createDirectoryIfMissing True fp
return (Tagged fp)
getGenomeChunkKey :: Path (FASTA Nucleotide) -> IO GenomeChunkKey
getGenomeChunkKey f =
fmap (GenomeChunkKey . BC.unpack . Hash.digestToHex)
(Hash.hashFileSHA512t_256 (untag f))
parseGenomesFileName :: Path (FASTA Nucleotide) -> Either (Path (FASTA Nucleotide)) GenomeChunkKey
parseGenomesFileName (Tagged fp) =
if isPrefixOf prefix fileName && isSuffixOf suffix fileName then
let
withoutPrefix = drop (length prefix) fileName
withoutSuffix = take (length withoutPrefix - length suffix) withoutPrefix
in
Right (GenomeChunkKey withoutSuffix)
else
Left (Tagged fileName)
where
fileName = takeFileName fp
prefix = "split-hits-"
suffix = ".fna"
writeGenomesFile ::
( MonadIO m
, Has (Reader WorkDir) sig m
)
=> Producer (FA.FastaEntry Nucleotide) (SafeT IO) ()
-> m (GenomeChunkKey, Path (FASTA Nucleotide))
writeGenomesFile genomes = do
genomesDir <- createGenomesSubdir
tmpGenomesFile <- FS.emptyTmpFile genomesDir "split-genomes.fna"
liftIO $ runSafeT $ P.runEffect $ genomes >-> FA.fastaFileWriter tmpGenomesFile
key <- liftIO $ getGenomeChunkKey tmpGenomesFile
let genomesFile = genomesFileFor genomesDir key
liftIO $ D.renameFile (untag tmpGenomesFile) (untag genomesFile)
return (key, genomesFile)
genomesFileFor :: Path Directory -> GenomeChunkKey -> Path (FASTA Nucleotide)
genomesFileFor dir (GenomeChunkKey hash) =
Tagged (untag dir </> name)
where
name = "split-genomes-" ++ hash ++ ".fna"
proteinFileFor :: Path Directory -> GenomeChunkKey -> Path (FASTA Aminoacid)
proteinFileFor dir (GenomeChunkKey hash) =
Tagged (untag dir </> name)
where
name = "split-proteins-" ++ hash ++ ".faa"
hitsFileFor :: Path Directory -> GenomeChunkKey -> Path (HMMERTable ProtSearchHitCols)
hitsFileFor dir (GenomeChunkKey hash) =
Tagged (untag dir </> name)
where
name = "split-hits-" ++ hash ++ ".hmmout"
processedHitsFileFor :: Path Directory -> GenomeChunkKey -> Path (DSV "\t" AggregatedHitsCols)
processedHitsFileFor dir (GenomeChunkKey hash) =
Tagged (untag dir </> name)
where
name = "processed-hits-" ++ hash ++ ".tsv"
searchGenomeHits ::
( MonadBaseControl IO m
, MonadIO m
, Has HMMSearch sig m
, Has Prodigal sig m
, Has (Reader WorkDir) sig m
)
=> GenomeChunkKey
-> Path (FASTA Nucleotide)
-> Path HMMERModel
-> m (Path (FASTA Aminoacid), Path (HMMERTable ProtSearchHitCols))
searchGenomeHits key genomesFile vpfsFile = do
protsDir <- createProteinsSubdir
let protsFile = proteinFileFor protsDir key
FS.whenNotExists protsFile $ FS.atomicCreateFile protsFile $ \tmpProtsFile ->
prodigal genomesFile tmpProtsFile Nothing
hitsDir <- createHitsSubdir
let hitsFile = hitsFileFor hitsDir key
FS.whenNotExists hitsFile $ FS.atomicCreateFile hitsFile $ \tmpHitsFile -> do
protsFileIsEmpty <- liftIO $ isEmptyFAA protsFile
if protsFileIsEmpty then
liftIO $ createEmptyHitsFile tmpHitsFile
else
hmmsearch vpfsFile protsFile tmpHitsFile
return (protsFile, hitsFile)
where
isEmptyFAA :: Path (FASTA Aminoacid) -> IO Bool
isEmptyFAA fp = runSafeT $ do
firstItem <- P.next (FA.fastaFileReader fp)
case firstItem of
Left (Left _e) -> return False
Left (Right ()) -> return True
Right (_, _) -> return False
createEmptyHitsFile :: Path (HMMERTable ProtSearchHitCols) -> IO ()
createEmptyHitsFile fp = IO.withFile (untag fp) IO.WriteMode $ \_ -> return ()
aggregateHits :: forall sig m.
( Has (Reader ModelConfig) sig m
, Has (Throw DSV.ParseError) sig m
, Has (Throw FA.ParseError) sig m
, MonadIO m
)
=> Path (FASTA Aminoacid)
-> Path (HMMERTable ProtSearchHitCols)
-> m (FrameRec AggregatedHitsCols)
aggregateHits aminoacidsFile hitsFile = do
proteinSizes <- loadProteinSizes
let hitRows = Tbl.produceRows hitsFile
thr <- asks modelEValueThreshold
getVirusName <- asks modelVirusNameExtractor
hitsFrame <- DSV.inCoreAoSExc $
hitRows
>-> P.filter (\row -> row^.HMM.sequenceEValue <= thr)
>-> P.map V.rcast
return $ hitsFrame
& F.mutate1 @"virus_name" (getVirusName . L.view HMM.targetName)
& aggregate proteinSizes
where
fastaEntryToRow :: FA.FastaEntry Aminoacid -> Record '[M.ProteinName, M.KBaseSize]
fastaEntryToRow entry =
V.fieldRec
( #protein_name =: FA.removeNameComments (FA.entryName entry)
, #k_base_size =: fromIntegral (FA.entrySeqNumBases entry) / 1000
)
loadProteinSizes :: m (GroupedFrameRec (Field M.ProteinName) '[M.KBaseSize])
loadProteinSizes = do
(colVecs, errs) <- liftIO $ runSafeT $
Fold.impurely P.foldM' (F.colVecsFoldM 128) $
FA.fastaFileReader aminoacidsFile
>-> P.map fastaEntryToRow
either throwError return errs
return $ F.setIndex @"protein_name" (F.fromColVecs colVecs)
aggregate :: GroupedFrameRec (Field M.ProteinName) '[M.KBaseSize]
-> FrameRec '[M.VirusName, HMM.TargetName, HMM.QueryName, HMM.SequenceScore]
-> FrameRec '[M.VirusName, M.ModelName, M.ProteinHitScore]
aggregate proteinSizes =
F.reindexed @"virus_name" . F.groups %~ do
F.cat
|. F.reindexed @"target_name" %~ do
F.cat
|. F.renameIndexTo @"protein_name"
|. F.groups %~ F.top @(F.Desc "sequence_score") 1
|. F.innerJoin proteinSizes
|. F.summarizing @"query_name" %~ do
let normalizedScore = F.give $ F.val @"sequence_score" / F.val @"k_base_size"
aggNormScore <- L.sumOf (F.foldedRows . L.to normalizedScore)
return (F.singleField @"protein_hit_score" aggNormScore)
|. F.rename @"query_name" @"model_name"
|. F.copySoA
processHits ::
( MonadIO m
, Has (Reader ModelConfig) sig m
, Has (Reader WorkDir) sig m
, Has (Throw DSV.ParseError) sig m
, Has (Throw FA.ParseError) sig m
)
=> GenomeChunkKey
-> Path (FASTA Aminoacid)
-> Path (HMMERTable ProtSearchHitCols)
-> m (Path (DSV "\t" AggregatedHitsCols))
processHits key protsFile hitsFile = do
aggregatedHits <- aggregateHits protsFile hitsFile
processedHitsDir <- createProcessedHitsSubdir
let processedHitsFile = processedHitsFileFor processedHitsDir key
writerOpts = DSV.defWriterOptions '\t'
liftIO $ runSafeT $ FS.atomicCreateFile processedHitsFile $ \tmpFile ->
DSV.writeDSV writerOpts (FS.fileWriter (untag tmpFile)) aggregatedHits
return processedHitsFile
predictMembership ::
Cls.ClassificationParams
-> GroupedFrameRec (Field M.VirusName) '[M.ModelName, M.ProteinHitScore]
-> GroupedFrameRec (Field M.VirusName)
'[Cls.ClassName, M.MembershipRatio, M.VirusHitScore, M.ConfidenceScore]
predictMembership classParams = F.groups %~ do
F.cat
|. L.iso (F.setIndex @"model_name") F.dropIndex %~
F.innerJoin (Cls.modelClasses classParams)
|. F.summarizing @"class_name" %~ do
let products = F.give $
F.val @"protein_hit_score"
* F.val @"class_percent"/100
* catWeight (F.val @"class_cat")
classScore <- L.sumOf (F.foldedRows . L.to products)
return (F.singleField @"class_score" classScore)
|. F.arrange @(F.Desc "class_score")
|. F.copySoA
|. id %~ do
totalScore <- L.sumOf (F.foldedRows . F.field @"class_score")
let confidence = percentileRank (Cls.scoreSamples classParams) (Tagged totalScore)
F.cat
|. F.mutate1 @"virus_hit_score" (const totalScore)
|. F.mutate1 @"confidence_score" (const confidence)
|. F.mutate1 @"membership_ratio" (F.give $ F.val @"class_score" / totalScore)
|. F.select_
where
percentileRank :: Ord a => Vector a -> a -> Double
percentileRank v a =
case Vec.span (< a) v of
(less, v') ->
case Vec.span (== a) v' of
(equal, _) ->
let c = fromIntegral $ Vec.length less
f = fromIntegral $ Vec.length equal
n = fromIntegral $ Vec.length v
in (c + 0.5*f) / n
catWeight :: Int -> Double
catWeight cat = (5 - fromIntegral cat) / 4
data SearchHitsConcurrencyOpts = SearchHitsConcurrencyOpts
{ fastaChunkSize :: Int
, numSearchingWorkers :: Int
}
deriving Generic
instance Store SearchHitsConcurrencyOpts
asyncSearchHits :: forall sig m.
( MonadBaseControl IO m
, MonadIO m
, Has HMMSearch sig m
, Has Prodigal sig m
, Has (Reader WorkDir) sig m
)
=> SearchHitsConcurrencyOpts
-> Path HMMERModel
-> [(GenomeChunkKey, Path (FASTA Nucleotide))]
-> m [(GenomeChunkKey, Path (FASTA Aminoacid), Path (HMMERTable ProtSearchHitCols))]
asyncSearchHits concOpts vpfsFile genomesFiles = do
let nworkers = numSearchingWorkers concOpts
genomesFilesProducer <- liftIO $ PA.stealingEach genomesFiles
PA.feedAsyncConsumer genomesFilesProducer $
P.mapM (\(key, genomesFile) -> do
(protsFile, hitsFile) <- searchGenomeHits key genomesFile vpfsFile
return (key, protsFile, hitsFile))
>-|>
stimes nworkers PA.toListM
distribSearchHits :: forall sigm m sign n w.
( MonadBaseControl IO m
, MonadIO m
, Has (Reader WorkDir) sigm m
, Has (Throw FA.ParseError) sigm m
, HasAny Distributed (Distributed n w) sigm m
, Typeable sign
, Typeable n
)
=> SDict
( MonadBaseControl IO n
, MonadIO n
, Has HMMSearch sign n
, Has Prodigal sign n
, Has (Reader WorkDir) sign n
)
-> SearchHitsConcurrencyOpts
-> Path HMMERModel
-> Path (FASTA Nucleotide)
-> m [(GenomeChunkKey, Path (FASTA Aminoacid), Path (HMMERTable ProtSearchHitCols))]
distribSearchHits sdict concOpts vpfsFile genomesFile = do
nslaves <- getNumWorkers_
wd <- ask @WorkDir
let genomesChunkWriter :: Pipe [FA.FastaEntry Nucleotide] (Integer, (GenomeChunkKey, Path _)) (SafeT IO) r
genomesChunkWriter = P.mapM $ \chunk -> do
kp <- liftIO $ runReaderT (writeGenomesFile (P.each chunk)) wd
return (genericLength chunk, kp)
chunkGenomeCount :: Pipe [(Integer, a)] (Integer, [a]) (SafeT IO) r
chunkGenomeCount = P.map (first sum . unzip)
genomesFilesProducer :: PA.AsyncProducer (Integer, [(_, _)]) (SafeT IO) () m () <- liftIO $
FA.fastaFileReader genomesFile
& PA.bufferedChunks (fromIntegral $ fastaChunkSize concOpts)
& (>-> genomesChunkWriter)
& PA.bufferedChunks (fromIntegral $ numSearchingWorkers concOpts)
& (>-> chunkGenomeCount)
& PA.stealingAsyncProducer (nslaves+1)
& fmap \ap -> ap
& PA.defaultOutput (Right ())
& PA.hoist (liftIO . runSafeT)
& PA.mapResultM (either throwError return)
let asyncSearchHits' kps =
static (\Dict -> asyncSearchHits @sign @n)
<:*> sdict
<:*> spureWith (static Dict) concOpts
<:*> spureWith (static Dict) vpfsFile
<:*> spureWith (static Dict) kps
progress <- liftIO $ Progress.init 0 (\nseqs -> "processed " ++ show nseqs ++ " sequences")
let updateProgress n = liftIO $ Progress.update progress (+ n)
rs <- withWorkers_ $ \w -> do
((), r) <- PA.runAsyncEffect (nslaves+1) $
genomesFilesProducer
>||>
P.mapM (\(n, kps) -> runInWorker_ w (static Dict) (asyncSearchHits' kps) <* updateProgress n)
>-|>
P.concat
>-|>
PA.toListM
return r
liftIO $ Progress.finish progress Nothing
return rs
newtype ProcessHitsConcurrencyOpts = ProcessHitsConcurrencyOpts
{ numProcessingHitsWorkers :: Int
}
asyncProcessHits :: forall sig m.
( MonadIO m
, MonadBaseControl IO m
, Has (Reader ModelConfig) sig m
, Has (Reader WorkDir) sig m
, Has (Throw DSV.ParseError) sig m
, Has (Throw FA.ParseError) sig m
)
=> ProcessHitsConcurrencyOpts
-> [(GenomeChunkKey, Path (FASTA Aminoacid), Path (HMMERTable ProtSearchHitCols))]
-> m [(GenomeChunkKey, Path (DSV "\t" AggregatedHitsCols))]
asyncProcessHits concOpts hitsFiles = do
let nworkers = numProcessingHitsWorkers concOpts
hitsFilesProducer <- liftIO $ PA.stealingEach hitsFiles
PA.feedAsyncConsumer hitsFilesProducer $
P.mapM (\(key, protsFile, hitsFile) -> (,) key <$> processHits key protsFile hitsFile)
>-|>
stimes nworkers PA.toListM
newtype PredictMembershipConcurrencyOpts = PredictMembershipConcurrencyOpts
{ numPredictingWorkers :: Int
}
asyncPredictMemberships :: forall sig m.
( MonadBaseControl IO m
, MonadIO m
, Has (Throw DSV.ParseError) sig m
)
=> PredictMembershipConcurrencyOpts
-> Map (Field Cls.ClassKey) Cls.ClassificationFiles
-> [Path (DSV "\t" AggregatedHitsCols)]
-> Path Directory
-> m [Path (DSV "\t" PredictedCols)]
asyncPredictMemberships concOpts classFiles aggHitsFiles outputDir = do
let nworkers = fromIntegral $ numPredictingWorkers concOpts
liftIO $ D.createDirectoryIfMissing True (untag outputDir)
liftIO $ IO.hPutStrLn IO.stderr $ "loading VPF classifications"
classes <- mapM (L._2 %%~ Cls.loadClassificationParams) (Map.toAscList classFiles)
(Ap errors, paths) <- liftIO $ runSafeT $ do
let sep = T.singleton '\t'
parserOpts = DSV.defParserOptions '\t'
classesWithHandles <-
forM classes \(classKey, classParams) -> do
let path = untag outputDir </> T.unpack (untag classKey) ++ ".tsv"
h <- PS.mask_ $ do
hdl <- liftIO $ IO.openFile path IO.WriteMode
PS.register (IO.hClose hdl)
return hdl
liftIO $ T.hPutStrLn h (DSV.headerToDSV @PredictedCols Proxy sep)
return (Tagged path, (classParams, h))
let (paths, classHandles) = unzip classesWithHandles
liftIO $ IO.hPutStrLn IO.stderr $ "found " ++ show (length aggHitsFiles) ++ " aggregated hit files"
Progress.tracking 0 (\nchunks -> "predicted " ++ show nchunks ++ " units") $ \progress -> do
hitChunks <- liftIO $ PA.stealingEach aggHitsFiles
let toBeWritten :: PA.AsyncProducer' (IO.Handle, Vec.Vector Text) IO (Ap (Either _) ())
toBeWritten = PA.duplicatingAsyncProducer $
(pure () <$ hitChunks)
>->
runApExceptsP (P.mapM (DSV.readFrame parserOpts))
>->
scheduleForWriting classHandles sep
liftIO $ PA.runAsyncEffect nworkers $
stimes nworkers (PA.defaultOutput (pure ()) toBeWritten)
>||>
(paths <$ writeOutput progress)
case errors of
Left errs -> throwErrors @'[DSV.ParseError] errs
Right () -> return paths
where
runApExceptsP ::
Monad n
=> P.Proxy a' a b' b (ExceptsT es n) r
-> P.Proxy a' a b' b n (Ap (Either (Errors es)) r)
runApExceptsP = fmap Ap . runExceptsT . P.distribute
scheduleForWriting ::
[(Cls.ClassificationParams, IO.Handle)]
-> Text
-> Pipe (FrameRec AggregatedHitsCols) (IO.Handle, Vec.Vector Text) IO r
scheduleForWriting classHandles sep =
P.for P.cat \aggHits -> do
let indexed = F.setIndex @"virus_name" aggHits
forM_ classHandles \(classParams, h) -> do
let predictedDSV = predictMembership classParams indexed
& F.resetIndex
& F.rows %~ DSV.rowToDSV sep
& F.toRowsVec
P.yield $! (h, predictedDSV)
writeOutput :: Progress.State Int -> PA.AsyncConsumer' (IO.Handle, Vec.Vector Text) IO ()
writeOutput progress =
PA.duplicatingAsyncConsumer $
P.mapM_ \(h, rows) -> do
mapM_ (T.hPutStrLn h) rows
Progress.update progress (+1)
data Checkpoint
= ContinueSearchingHits
| ContinueFromHitsFiles [GenomeChunkKey]
| ContinueFromProcessedHits [GenomeChunkKey]
deriving Generic
instance Aeson.FromJSON Checkpoint
instance Aeson.ToJSON Checkpoint
newtype CheckpointLoadError = CheckpointJSONLoadError String
deriving Store via CheckpointLoadError
data ClassificationStep
= SearchHitsStep {
runSearchHitsStep :: forall sigm m sign n w.
( MonadBaseControl IO m
, MonadIO m
, Has (Reader WorkDir) sigm m
, Has (Throw FA.ParseError) sigm m
, HasAny Distributed (Distributed n w) sigm m
, Typeable sign
, Typeable n
)
=> SDict
( MonadBaseControl IO n
, MonadIO n
, Has HMMSearch sign n
, Has Prodigal sign n
, Has (Reader WorkDir) sign n
)
-> SearchHitsConcurrencyOpts
-> Path HMMERModel
-> Path (FASTA Nucleotide)
-> m Checkpoint
}
| ProcessHitsStep {
runProcessHitsStep :: forall sig m.
( MonadBaseControl IO m
, MonadIO m
, Has (Reader ModelConfig) sig m
, Has (Reader WorkDir) sig m
, Has (Throw DSV.ParseError) sig m
, Has (Throw FA.ParseError) sig m
)
=> ProcessHitsConcurrencyOpts
-> m Checkpoint
}
| PredictMembershipStep {
runPredictMembershipStep :: forall sig m.
( MonadBaseControl IO m
, MonadIO m
, Has (Reader WorkDir) sig m
, Has (Throw DSV.ParseError) sig m
)
=> PredictMembershipConcurrencyOpts
-> Map (Field Cls.ClassKey) Cls.ClassificationFiles
-> Path Directory
-> m [Path (DSV "\t" PredictedCols)]
}
tryLoadCheckpoint ::
( MonadIO m
, Has (Throw CheckpointLoadError) sig m
)
=> Path (JSON Checkpoint)
-> m (Maybe Checkpoint)
tryLoadCheckpoint checkpointFile = do
exists <- liftIO $ D.doesFileExist (untag checkpointFile)
if exists then do
r <- liftIO $ Aeson.eitherDecodeFileStrict' (untag checkpointFile)
case r of
Left e -> throwError (CheckpointJSONLoadError e)
Right checkpoint -> return (Just checkpoint)
else
return Nothing
saveCheckpoint :: Path (JSON Checkpoint) -> Checkpoint -> IO ()
saveCheckpoint checkpointFile checkpoint =
FS.atomicCreateFile checkpointFile $ \tmp ->
Aeson.encodeFile (untag tmp) checkpoint
checkpointStep :: Checkpoint -> ClassificationStep
checkpointStep checkpoint =
case checkpoint of
ContinueSearchingHits ->
SearchHitsStep $ \sdict concOpts vpfsFile genomesFile -> do
r <- distribSearchHits sdict concOpts vpfsFile genomesFile
return $ ContinueFromHitsFiles (map (L.view L._1) r)
ContinueFromHitsFiles keys ->
ProcessHitsStep $ \concOpts -> do
protsSubdir <- createProteinsSubdir
hitsSubdir <- createHitsSubdir
let hitsFiles =
[ (key, proteinFileFor protsSubdir key, hitsFileFor hitsSubdir key)
| key <- keys
]
r <- asyncProcessHits concOpts hitsFiles
return (ContinueFromProcessedHits (map fst r))
ContinueFromProcessedHits keys ->
PredictMembershipStep $ \concOpts classFiles outputDir -> do
aggHitsSubdir <- createProcessedHitsSubdir
let aggHitsFiles = map (processedHitsFileFor aggHitsSubdir) keys
asyncPredictMemberships concOpts classFiles aggHitsFiles outputDir
checkpointFileFor :: WorkDir -> GenomeChunkKey -> Path (JSON Checkpoint)
checkpointFileFor (WorkDir dir) (GenomeChunkKey hash) =
Tagged (untag dir </> name)
where
name = "checkpoint-" ++ hash ++ ".json"
runClassification :: forall sig m a.
( MonadIO m
, Has (Reader WorkDir) sig m
, Has (Throw CheckpointLoadError) sig m
)
=> Path (FASTA Nucleotide)
-> ((Checkpoint -> m a) -> ClassificationStep -> m a)
-> m a
runClassification fullGenomesFile runSteps = do
key <- liftIO $ getGenomeChunkKey fullGenomesFile
wd <- ask
let checkpointFile = checkpointFileFor wd key
maybeCheckpoint <- tryLoadCheckpoint checkpointFile
let checkpoint = fromMaybe ContinueSearchingHits maybeCheckpoint
runSteps (resume checkpointFile) (checkpointStep checkpoint)
where
resume :: Path (JSON Checkpoint) -> Checkpoint -> m a
resume checkpointFile checkpoint = do
liftIO $ saveCheckpoint checkpointFile checkpoint
runSteps (resume checkpointFile) (checkpointStep checkpoint)
|
0aa4210fffc124bbef5b08182f0c38ba54e9b0365a72adb650a031e44ad7cf00 | haskell/cabal | TH.hs | # LANGUAGE TemplateHaskell #
module TH where
import Language.Haskell.TH (ExpQ)
splice :: ExpQ
splice = [| () |]
| null | https://raw.githubusercontent.com/haskell/cabal/00a2351789a460700a2567eb5ecc42cca0af913f/cabal-testsuite/PackageTests/TemplateHaskell/vanilla/TH.hs | haskell | # LANGUAGE TemplateHaskell #
module TH where
import Language.Haskell.TH (ExpQ)
splice :: ExpQ
splice = [| () |]
|
|
9af154f3102ac80c8ac411cf656f19143cd06400a2aa966ac65d86bc60f460cd | jeromesimeon/Galax | cs_code_typing_top.ml | (***********************************************************************)
(* *)
(* GALAX *)
(* XQuery Engine *)
(* *)
Copyright 2001 - 2007 .
(* Distributed only by permission. *)
(* *)
(***********************************************************************)
$ I d : , v 1.47 2007/10/16 01:25:34
(* Module: Cs_code_typing_top.
Description:
This module implements the physical typing and physical-operator
assignment phase.
*)
open Code_selection_context
open Code_typing_context
open Xquery_algebra_ast
open Xquery_algebra_ast_util
open Xquery_physical_type_ast
open Xquery_physical_type_ast_util
open Xquery_physical_algebra_ast
open Error
Architecture
------------
1 . We are decoupling the code selection into two phases :
Phase1 : physical operator assignment . This decide which physical
operator to use and does the corresponding physical typing .
Phase2 : actual code selection , which :
( 1 ) allocate variable and tuple resources on the stack frame
( 2 ) builds the code for each physical operator
2 . Code selection should remain ( mostly ) unchanged , except that
it will be cleaned up of physical algorithm decision , and of the
corresponding annotation / signature computation .
3 . There is a new phase , which does physical assignment and type
checking . Here is how the recursion will proceed for type checking and
physical assignment :
For Op{D1, ... Dn}(I1, ... ) in environment PEnv
( 1 ) : T1 ... Ik : Tk in environment PEnv
( 2 ) For Op , and T1 .... Tk pick up the corresponding physical
operator POp .
( 3 ) From POp , compute the type T_INPUT of the Input ( item or tuple )
( 4 ) Extend environment to PEnv ' with the type T_INPUT
( 5 ) : T1 ' ... Dn : Tn ' in PEnv '
( 6 ) Apply type checking for possible additional constraints on the
( type of POp ) , and compute the ouput physical type T_OUT ) . This
( yields the physical type signature ) ( 7 ) Annotate the AST with the POp and .
PEnv |- I1 : POp1 ; ( 1 ) above
...
PEnv : POp1 ; Sigk
T_OUTPUT = EXTRACT(Sig1, ... Sigk )
Assign(Op , T_OUTPUT ) = POp , T_INPUT ( 2 ) & ( 3 ) above
PEnv ' = PEnv + INPUT : T_INPUT ( 4 ) above
PEnv ' |- D1 : POp1 ' ; ' ( 5 ) above
...
PEnv ' |- Dn : POpn ' ; Sign '
T_OUTPUT ' = EXTRACT(Sig1', ... Sign ' )
Sig = TypeCheck(POp , T_OUTPUT , T_OUTPUT ' )
----------------------------------------------
PEnv |- Op{D1, ... Dn}(I1, ... ) : POp ; Sig
Architecture
------------
1. We are decoupling the code selection into two phases:
Phase1: physical operator assignment. This decide which physical
operator to use and does the corresponding physical typing.
Phase2: actual code selection, which:
(1) allocate variable and tuple resources on the stack frame
(2) builds the code for each physical operator
2. Code selection should remain (mostly) unchanged, except that
it will be cleaned up of physical algorithm decision, and of the
corresponding annotation / signature computation.
3. There is a new phase, which does physical assignment and type
checking. Here is how the recursion will proceed for type checking and
physical assignment:
For Op{D1,...Dn}(I1,...Ik) in environment PEnv
(1) Typecheck I1 : T1 ... Ik : Tk in environment PEnv
(2) For Op, and T1....Tk pick up the corresponding physical
operator POp.
(3) From POp, compute the type T_INPUT of the Input (item or tuple)
(4) Extend environment to PEnv' with the type T_INPUT
(5) Typecheck D1 : T1' ... Dn : Tn' in PEnv'
(6) Apply type checking for possible additional constraints on the
(type of POp), and compute the ouput physical type T_OUT). This
(yields the physical type signature) P_Sig
(7) Annotate the AST with the POp and P_Sig.
PEnv |- I1 : POp1 ; Sig1 (1) above
...
PEnv |- Ik : POp1 ; Sigk
T_OUTPUT = EXTRACT(Sig1,...Sigk)
Assign(Op,T_OUTPUT) = POp,T_INPUT (2) & (3) above
PEnv' = PEnv + INPUT : T_INPUT (4) above
PEnv' |- D1 : POp1' ; Sig1' (5) above
...
PEnv' |- Dn : POpn' ; Sign'
T_OUTPUT' = EXTRACT(Sig1',...Sign')
Sig = TypeCheck(POp,T_OUTPUT,T_OUTPUT')
----------------------------------------------
PEnv |- Op{D1,...Dn}(I1,...Ik) : POp ; Sig
*)
let lookup_field_type field tuple_type =
try
List.assoc field tuple_type
with
| Not_found ->
raise(Query(Physical_Type_Error(
"Tuple field "^(Namespace_names.prefixed_string_of_rqname field)^" not found in physical type "^(Print_xquery_physical_type.string_of_physical_tuple_type tuple_type))))
let extract_output_signature algop =
match algop.palgop_expr_eval_sig with
| None ->
raise (Query(Malformed_Algebra_Expr("Physical type signature missing for algebraic operator: "^
(Print_xquery_algebra.bprintf_physical_algstatement "" algop))))
| Some (_, _, output_physical_type) -> output_physical_type
(* For an arbitrary algebraic operator, compute the physical type of its input *)
let compute_input_sig subexprs =
match subexprs with
| NoSub -> NoInput
| OneSub subexpr -> OneInput (extract_output_signature subexpr)
| TwoSub (subexpr1, subexpr2) -> TwoInput (extract_output_signature subexpr1, extract_output_signature subexpr2)
| ManySub subexpr_array -> ManyInput (Array.map extract_output_signature subexpr_array)
Select physical operator for logical operator .
Most operators have one physical implementation .
Select physical operator for logical operator.
Most operators have one physical implementation.
*)
let rec select_physical_op ctc code_ctxt algop_expr input_types =
let code_ctxt = store_annotation code_ctxt algop_expr.compile_annotations in
match algop_expr.palgop_expr_name with
(*************************)
(* Functional operations *)
(*************************)
| AOEIf -> POIf
| AOEWhile -> POWhile
| AOELetvar (odt, vn) ->
POLetvar (Code_binding.select_physical_variable_binding code_ctxt input_types (odt, vn))
| AOETypeswitch pat_vn_array -> POTypeswitch (Array.map snd pat_vn_array)
| AOEVar (vn) -> POVar vn
| AOECallBuiltIn ((cfname,arity), optintypes, outtype, _) ->
Code_builtin_fn.select_physical_op code_ctxt input_types algop_expr ((cfname,arity), optintypes, outtype)
| AOECallUserDefined((fname, arity), optintypes, outtype, _, _) -> POCallUserDefined
| AOECallOverloaded((cfname,arity),table) -> POCallOverloaded
| AOEConvertSimple atomic_type -> POConvertSimple
| AOEPromoteNumeric atomic_type -> POPromoteNumeric
| AOEPromoteAnyString -> POPromoteAnyString
| AOEUnsafePromoteNumeric atomic_type -> POUnsafePromoteNumeric
(*****************)
(* Constructors *)
(*****************)
| AOEScalar dmv -> POScalar
| AOEEmpty -> POEmpty
| AOESeq
| AOEImperativeSeq
| AOEDocument
| AOEPI _
| AOEPIComputed
| AOEComment _
| AOECommentComputed
| AOEText _
| AOECharRef _
| AOETextComputed
| AOEElem _
| AOEAnyElem _
| AOEAttr _
| AOEAnyAttr _ ->
Now distinguishing between streamed and materialized versions
of constructors although these do not exist as alternative
implementations . This ' virtual ' distinction is needed
for proper propagation of ' non - streamability ' in case
data flow starts with a constructor . -
of constructors although these do not exist as alternative
implementations. This 'virtual' distinction is needed
for proper propagation of 'non-streamability' in case
data flow starts with a constructor. - Michael *)
Code_constructors.select_physical_op code_ctxt input_types algop_expr
| AOEError -> POError
(******************)
(* Type operators *)
(******************)
| AOETreat cmodel1 -> POTreat
| AOEValidate vmode -> POValidate
| AOECast (nsenv, cmodel1) -> POCast
| AOECastable (nsenv, cmodel1) -> POCastable
(************************)
Item / Tuple operators
(************************)
| AOESome (odt, vn) ->
POSome (Code_binding.select_physical_variable_binding code_ctxt input_types (odt, vn))
| AOEEvery (odt, vn) ->
POEvery (Code_binding.select_physical_variable_binding code_ctxt input_types (odt, vn))
| AOEMapToItem -> POMapToItem
| AOEMapFromItem vn ->
POMapFromItem (Code_binding.select_physical_variable_binding code_ctxt input_types (None, vn))
(*******************)
(* Tuple operators *)
(*******************)
| AOEInputTuple -> POInputTuple
| AOECreateTuple names ->
POCreateTuple (Code_binding.select_physical_tuple_binding code_ctxt input_types names)
| AOEAccessTuple crname1 -> POAccessTuple crname1
| AOEConcatTuples -> POConcatTuples
| AOEProduct -> POProduct
| AOESelect pred -> POSelect
| AOEProject fields -> POProject fields
(**********)
(* Joins *)
(**********)
| AOEJoin pred_desc ->
Code_util_join.select_physical_op Code_util_join.StandardJoin algop_expr
| AOELeftOuterJoin (null_name,pred_desc) ->
Code_util_join.select_physical_op (Code_util_join.OuterJoin null_name) algop_expr
(*****************)
(* Map operators *)
(*****************)
| AOEMapConcat -> POMapConcat
| AOEOuterMapConcat vn -> POOuterMapConcat vn
| AOEMap -> POMap
| AOEMapIndex vname -> POMapIndex vname
| AOEMapIndexStep vname -> POMapIndexStep vname
| AOENullMap v -> PONullMap v
(*********************)
(* Update operations *)
(*********************)
| AOECopy -> POCopy
| AOEDelete -> PODelete
| AOEInsert insert_location -> POInsert
| AOERename _ -> PORename
| AOEReplace value_flag -> POReplace
| AOESnap sm -> POSnap
| AOESet (vn) -> POSet vn
| AOEParse uri ->
Code_parse.select_physical_op code_ctxt algop_expr uri
| AOETreeJoin (axis, anode_test) ->
Now passing on the input signature to treejoin code selection . -
Code_treejoin.select_physical_op code_ctxt input_types algop_expr (axis, anode_test)
| AOETupleTreePattern (input, pattern) ->
Code_tuple_tree_pattern.select_physical_op code_ctxt algop_expr (input, pattern)
Group / order
(* For group operators, we just need the names of the new aggregate fields *)
| AOEGroupBy gd_list -> POGroupBy (List.map Xquery_algebra_ast_util.get_aggregate_name gd_list)
| AOEOrderBy (stablekind, sort_spec_list, osig) -> POOrderBy
(*********)
(* Other *)
(*********)
DXQ
| AOEServerImplements (ncname, uri) ->
begin
let _ = access_onesub algop_expr.psub_expression in
let dep_expr = access_onesub algop_expr.pdep_sub_expression in
let _ = code_typing_expr code_ctxt ctc dep_expr in
match (dep_expr.palgop_expr_eval_sig) with
| Some (_, _, output_type) ->
begin
match output_type with
| PT_XML _ -> POServerImplementsTree
| PT_Table _ -> POServerImplementsTuple
end
| None -> raise(Query(Internal_Error("AOEServerImplements input does not have physical type")))
end
(* for server P close E always returns a tree... *)
| AOEForServerClose (ncname, uri) ->
Debug.print_dxq_debug ("cs_code_typing_top : Before for-server access_onesub\n");
let indep_expr = access_onesub algop_expr.psub_expression in
Debug.print_dxq_debug ("cs_code_typing_top : After for-server access_onesub\n");
let _ = code_typing_expr code_ctxt ctc indep_expr in
POForServerCloseTree
(* eval closure E *)
| AOEEvalClosure ->
Debug.print_dxq_debug ("cs_code_typing_top : Before eval-box access_onesub\n");
Debug.print_dxq_debug ((Print_xquery_algebra.bprintf_logical_algstatement "" algop_expr)^"\n");
let indep_expr = access_onesub algop_expr.psub_expression in
Debug.print_dxq_debug ("cs_code_typing_top : After eval-box access_onesub\n");
let _ = code_typing_expr code_ctxt ctc indep_expr in
(* We have no bloody idea what type the evaluation of a closure returns, so we assume a tree *)
POEvalClosureTree
| AOEExecute (ncname, uri)
Logic is the same for async execute , even though we throw the value away
begin
Physical typing phase .
1 . Examine the physical type of the second argument to AOEExecute
1. Examine the physical type of the second argument to AOEExecute
*)
let (indep_expr1, indep_expr2) = access_twosub algop_expr.psub_expression in
match (indep_expr2.palgop_expr_eval_sig) with
| Some (_, _, output_type) ->
begin
match output_type with
| PT_XML _ -> POExecuteTree
| PT_Table _ -> POExecuteTuple
end
| None -> raise(Query(Internal_Error("AOEExecute's input does not have physical type")))
end
(*
Type check operator and compute output type.
*)
and type_check_physical_op code_ctxt ctc pop indep_expr_types dep_exprs =
3 . From POp , compute the type T_INPUT of the Input ( item or tuple )
4 . Extend environment to PEnv ' with the type T_INPUT
5 . : T1 ' ... Dn : Tn ' in PEnv '
try
let output_type =
match pop with
Function Calls
CTC |- Indep_1 : , < : XML
...
CTC |- Indep_n : PT_n , PT_n < : XML
---------------------------------------------------
CTC |- FuncCallOp{}(Indep_1, ... ,Indep_n ) : DOM LIST
CTC |- Indep_1 : PT_1 , PT_1 <: XML
...
CTC |- Indep_n : PT_n , PT_n <: XML
---------------------------------------------------
CTC |- FuncCallOp{}(Indep_1,...,Indep_n) : DOM LIST
*)
| POCallBuiltIn
| POCallUserDefined
| POCallOverloaded ->
let _ = access_nosub dep_exprs in
let _ = access_many_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
(* Special treatment of streamed fn:count function *)
| POCallBuiltIn_Fn_Count_Stream ->
let _ = access_nosub dep_exprs in
Should assert sax stream input here ! -
let _ = access_many_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
Special treatment of streamed fs : first - item function
| POCallBuiltIn_Fs_First_Stream ->
let _ = access_nosub dep_exprs in
Should assert sax stream input here ! -
let _ = access_many_non_discarded_xml_types indep_expr_types in
sax_stream_xml_type
(* Special treatment of streamed fs:item-to-node() function *)
| POCallBuiltIn_Fs_Item2Node_Stream ->
let _ = access_nosub dep_exprs in
Should assert sax stream input here ! -
let _ = access_many_non_discarded_xml_types indep_expr_types in
sax_stream_xml_type
CTC |- Indep_1 : , < : XML
-----------------------------------------------
CTC |- SpecialFunCallOp{}(Indep_1 ) : DOM CURSOR
CTC |- Indep_1 : PT_1, PT_1 <: XML
-----------------------------------------------
CTC |- SpecialFunCallOp{}(Indep_1) : DOM CURSOR
*)
| POConvertSimple
| POPromoteNumeric
| POPromoteAnyString
| POUnsafePromoteNumeric ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_cursor_xml_type
Var
----------------------------
CTC |- VarOp[v ] { } ( ) : CTC[v ]
----------------------------
CTC |- VarOp[v]{}() : CTC[v]
*)
| POVar vn ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
(* Must assert non-discarded XML type at binding time. *)
(* Forces materialization for global variables -- we need to do better, but this is broken right now *)
PT_XML ( get_variable_type ctc vn )
Constructors
CTC |- Indep_1 : , < : XML
-------------------------------------------------
CTC |- DocumentOp{}(Indep1 ) : SAX STREAM / DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
-------------------------------------------------
CTC |- DocumentOp{}(Indep1) : SAX STREAM/DOM LIST
*)
| PODocument_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
sax_stream_xml_type
| PODocument_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_list_xml_type
----------------------------------------------------
CTC |- PIOp[ncname , target ] { } ( ) : SAX STREAM / DOM LIST
----------------------------------------------------
CTC |- PIOp[ncname,target]{}() : SAX STREAM/DOM LIST
*)
| POPI_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
sax_stream_xml_type
| POPI_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
CTC |- Indep_2 : PT_2 , PT_2 < : XML
-----------------------------------------------------------
CTC |- PIComputedOp{}(Indep1 , Indep2 ) : SAX STREAM / DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Indep_2 : PT_2, PT_2 <: XML
-----------------------------------------------------------
CTC |- PIComputedOp{}(Indep1, Indep2) : SAX STREAM/DOM LIST
*)
| POPIComputed_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_two_non_discarded_xml_types indep_expr_types in
sax_stream_xml_type
| POPIComputed_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_two_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
-----------------------------------------------
CTC |- CommentOp[str ] { } ( ) : SAX STREAM / DOM LIST
-----------------------------------------------
CTC |- CommentOp[str]{}() : SAX STREAM/DOM LIST
*)
| POComment_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
sax_stream_xml_type
| POComment_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
--------------------------------------------------------
CTC ) : SAX STREAM / DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
--------------------------------------------------------
CTC |- CommentComputedOp{}(Indep1) : SAX STREAM/DOM LIST
*)
| POCommentComputed_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
sax_stream_xml_type
| POCommentComputed_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_list_xml_type
--------------------------------------------
CTC |- TextOp[str ] { } ( ) : SAX STREAM / DOM LIST
--------------------------------------------
CTC |- TextOp[str]{}() : SAX STREAM/DOM LIST
*)
| POText_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
sax_stream_xml_type
| POText_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
-----------------------------------------------------
CTC |- TextComputedOp{}(Indep1 ) : SAX STREAM / DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
-----------------------------------------------------
CTC |- TextComputedOp{}(Indep1) : SAX STREAM/DOM LIST
*)
| POTextComputed_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
sax_stream_xml_type
| POTextComputed_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
...
CTC |- Indep_n : PT_n , PT_n < : XML
----------------------------------------------------------------
CTC |- ElemOp[name]{}(Indep_1, ... ,Indep_n ) : SAX STREAM / DOM LIST
CTC |- Indep_1 : PT_1 , PT_1 <: XML
...
CTC |- Indep_n : PT_n , PT_n <: XML
----------------------------------------------------------------
CTC |- ElemOp[name]{}(Indep_1,...,Indep_n) : SAX STREAM/DOM LIST
*)
| POElem_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_many_non_discarded_xml_types indep_expr_types in
sax_stream_xml_type
| POElem_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_many_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
CTC |- Indep_2 : PT_2 , PT_2 < : XML
-------------------------------------------------------
CTC |- AnyElemOp{}(Indep1,Indep2 ) : SAX STREAM / DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Indep_2 : PT_2, PT_2 <: XML
-------------------------------------------------------
CTC |- AnyElemOp{}(Indep1,Indep2) : SAX STREAM/DOM LIST
*)
| POAnyElem_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_two_non_discarded_xml_types indep_expr_types in
sax_stream_xml_type
| POAnyElem_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_two_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
...
CTC |- Indep_n : PT_n , PT_n < : XML
----------------------------------------------------------------
CTC |- AttrOp[name]{}(Indep_1, ... ,Indep_n ) : SAX STREAM / DOM LIST
CTC |- Indep_1 : PT_1 , PT_1 <: XML
...
CTC |- Indep_n : PT_n , PT_n <: XML
----------------------------------------------------------------
CTC |- AttrOp[name]{}(Indep_1,...,Indep_n) : SAX STREAM/DOM LIST
*)
| POAttr_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_many_non_discarded_xml_types indep_expr_types in
sax_stream_xml_type
| POAttr_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_many_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
CTC |- Indep_2 : PT_2 , PT_2 < : XML
-------------------------------------------------------
CTC |- AnyAttrOp{}(Indep1,Indep2 ) : SAX STREAM / DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Indep_2 : PT_2, PT_2 <: XML
-------------------------------------------------------
CTC |- AnyAttrOp{}(Indep1,Indep2) : SAX STREAM/DOM LIST
*)
| POAnyAttr_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_two_non_discarded_xml_types indep_expr_types in
sax_stream_xml_type
| POAnyAttr_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_two_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
(* But all other constructors yield materialized items *)
CTC |- Indep_1 : , < : XML
...
CTC |- Indep_n : PT_n , PT_n < : XML
------------------------------------------------
CTC |- ErrorOp{}(Indep_1, ... ,Indep_n ) : DOM LIST
CTC |- Indep_1 : PT_1 , PT_1 <: XML
...
CTC |- Indep_n : PT_n , PT_n <: XML
------------------------------------------------
CTC |- ErrorOp{}(Indep_1,...,Indep_n) : DOM LIST
*)
| POError ->
let _ = access_nosub dep_exprs in
let _ = access_many_non_discarded_xml_types indep_expr_types in
The output type depends on the indep . input types ! -
dom_list_xml_type
-----------------------------
CTC |- EmptyOp { } ( ) : DOM LIST
-----------------------------
CTC |- EmptyOp{}() : DOM LIST
*)
| POEmpty ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
dom_list_xml_type
(*
---------------------------------
CTC |- ScalarOp[a]{}() : DOM LIST
*)
| POScalar ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
CTC |- Indep_2 : PT_2 , PT_2 < : XML
-----------------------------------------
CTC |- SeqOp{}(Indep1 , Indep2 ) : DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Indep_2 : PT_2, PT_2 <: XML
-----------------------------------------
CTC |- SeqOp{}(Indep1, Indep2) : DOM LIST
*)
| POSeq_Materialized
| POImperativeSeq_Materialized ->
let _ = access_nosub dep_exprs in
let (_,_) = access_two_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
| POSeq_Stream
| POImperativeSeq_Stream ->
let _ = access_nosub dep_exprs in
let (_,_) = access_two_non_discarded_xml_types indep_expr_types in
sax_stream_xml_type
Basic Tuple operations
(*
PT = CTC[INPUT]#q
--------------------------------
CTC |- AccessTupleOp[q]{}() : PT
*)
| POAccessTuple field_name ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
(* Must assert non-discarded XML type at binding time. *)
PT_XML(lookup_field_type field_name (get_input_type ctc))
CTC |- Indep_1 : , < : XML
...
CTC |- Indep_n : PT_n , PT_n < : XML
PTT = [ : PTFT_1 , ... , q_n : PTFT_n ]
---------------------------------------------------------------------
CTC |- CreateTupleOp[[PTT]][q_1, ... ,q_n]{}(Indep_1, ... ,Indep_n ) : PTT
CTC |- Indep_1 : PT_1 , PT_1 <: XML
...
CTC |- Indep_n : PT_n , PT_n <: XML
PTT = [q_1 : PTFT_1, ... , q_n : PTFT_n]
---------------------------------------------------------------------
CTC |- CreateTupleOp[[PTT]][q_1,...,q_n]{}(Indep_1,...,Indep_n) : PTT
*)
| POCreateTuple names_types ->
let _ = access_nosub dep_exprs in
let _ = access_many_non_discarded_xml_types indep_expr_types in
PT_Table(names_types)
PT = CTC[INPUT ] < : Table
----------------------------
CTC |- InputTupleOp { } ( ) : PT
PT = CTC[INPUT] <: Table
----------------------------
CTC |- InputTupleOp{}() : PT
*)
| POInputTuple ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
(* Must assert non-discarded XML type at binding time. *)
PT_Table(get_input_type ctc)
CTC |- Indep_1 : , < : Table
CTC |- Indep_1 : PT_2 , PT_2 < : Table
-----------------------------------------------------
CTC |- ConcatTupleOp{}(Indep_1,Indep_2 ) : @ PT_2
CTC |- Indep_1 : PT_1, PT_1 <: Table
CTC |- Indep_1 : PT_2, PT_2 <: Table
-----------------------------------------------------
CTC |- ConcatTupleOp{}(Indep_1,Indep_2) : PT_1 @ PT_2
*)
| POConcatTuples ->
let _ = access_nosub dep_exprs in
let (t1, t2) = access_two_table_types indep_expr_types in
(PT_Table (t1 @ t2))
Need auxilliary judgement for mat(PT ) according to function
Xquery_physical_type_ast_util.materialize_xml_type . - Michael
CTC |- Indep_1 : , < : Table
CTC |- Indep_2 : PT_2 , PT_2 < : Table
-----------------------------------------------------------
CTC |- ProductTupleOp{}(Indep_1,Indep_2 ) : PT_1 @ mat(PT_2 )
Need auxilliary judgement for mat(PT) according to function
Xquery_physical_type_ast_util.materialize_xml_type. - Michael
CTC |- Indep_1 : PT_1, PT_1 <: Table
CTC |- Indep_2 : PT_2, PT_2 <: Table
-----------------------------------------------------------
CTC |- ProductTupleOp{}(Indep_1,Indep_2) : PT_1 @ mat(PT_2)
*)
| POProduct ->
let _ = access_nosub dep_exprs in
let (t1, t2) = access_two_table_types indep_expr_types in
The right side is materialized to an array of DOM values .
let t2' = List.map (fun (n, t) -> (n, materialize_xml_type t)) t2 in
(PT_Table (t1 @ t2'))
CTC |- Indep_1 : , < : XML
CTC |- Dep_2 : PT_2 ,
-----------------------------------------------
CTC |- ServerImplements{Dep_2}(Indep_1 ) : PT_2
Why is this rule different than all others ?
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Dep_2 : PT_2,
-----------------------------------------------
CTC |- ServerImplements{Dep_2}(Indep_1) : PT_2
Why is this rule different than all others?
*)
| POServerImplementsTree
| POServerImplementsTuple ->
let _ = access_one_non_discarded_xml_type indep_expr_types in
let dep_expr = access_onesub dep_exprs in
begin
match (dep_expr.palgop_expr_eval_sig) with
| Some (_, _, output_type) -> output_type
| None -> raise(Query(Internal_Error("POServerImplements input does not have physical type")))
end
We could have the result of a remote expression be a SAX
type ...
CTC |- Indep_1 : , < : XML
CTC |- Indep_2 : PT_2 , PT_2 < : XML
-----------------------------------------------
CTC |- Execute(Indep_1 , Indep_2 ) : DOM CURSOR
We could have the result of a remote expression be a SAX
type...
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Indep_2 : PT_2, PT_2 <: XML
-----------------------------------------------
CTC |- Execute(Indep_1, Indep_2) : DOM CURSOR
*)
| POExecuteTree ->
let _ = access_nosub dep_exprs in
let _ = access_two_non_discarded_xml_types indep_expr_types in
dom_cursor_xml_type
CTC |- Indep_1 : , < : XML
CTC |- Indep_2 : PT_2 , PT_2 < : Table
-----------------------------------------------
CTC |- Execute(Indep_1 , Indep_2 ) : Table
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Indep_2 : PT_2, PT_2 <: Table
-----------------------------------------------
CTC |- Execute(Indep_1, Indep_2) : Table
*)
| POExecuteTuple ->
let _ = access_nosub dep_exprs in
let (indep_type1, indep_type2) = access_two_types indep_expr_types in
let _ = assert_non_discarded_xml_type indep_type1 in
let _ = assert_table_type indep_type2 in
indep_type2
We have no bloody idea what the physical type of a closure is ...
CTC |- Indep_1 : , < : XML
----------------------------------------
CTC |- EvalClosure(Indep_1 ) : XML
We have no bloody idea what the physical type of a closure is...
CTC |- Indep_1 : PT_1, PT_1 <: XML
----------------------------------------
CTC |- EvalClosure(Indep_1) : XML
*)
| POEvalClosureTree ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_cursor_xml_type
We have no bloody idea what the physical type of a closure is ...
CTC |- Indep_1 : , < : XML
----------------------------------------
CTC |- EvalClosure(Indep_1 ) : Table
We have no bloody idea what the physical type of a closure is...
CTC |- Indep_1 : PT_1, PT_1 <: XML
----------------------------------------
CTC |- EvalClosure(Indep_1) : Table
*)
| POEvalClosureTuple ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
raise (Query (Prototype "No physical typing for eval-box that yields tuples."))
We have no bloody idea what the physical type of a closure is ...
CTC |- Indep_1 : , < : XML
----------------------------------------
CTC |- ForServerClose(Indep_1 ) : XML
We have no bloody idea what the physical type of a closure is...
CTC |- Indep_1 : PT_1, PT_1 <: XML
----------------------------------------
CTC |- ForServerClose(Indep_1) : XML
*)
| POForServerCloseTree ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_cursor_xml_type
We have no bloody idea what the physical type of a closure is ...
CTC |- Indep_1 : , < : XML
----------------------------------------
CTC |- ForServerClose(Indep_1 ) : Table
We have no bloody idea what the physical type of a closure is...
CTC |- Indep_1 : PT_1, PT_1 <: XML
----------------------------------------
CTC |- ForServerClose(Indep_1) : Table
*)
| POForServerCloseTuple ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
raise (Query (Prototype "No physical typing for for-server-box that yields tuples."))
CTC |- Indep_1 : , < : Table
------------------------------------
CTC |- DistinctOp{}(Indep_1 ) :
Does internal materialization of some sort.- | PODistinct name
- >
let _ = access_nosub dep_exprs in
( PT_Table(access_one_table_type indep_expr_types ) )
CTC |- Indep_1 : PT_1, PT_1 <: Table
------------------------------------
CTC |- DistinctOp{}(Indep_1) : PT_1
Does internal materialization of some sort.- Michael
| PODistinct name
->
let _ = access_nosub dep_exprs in
(PT_Table(access_one_table_type indep_expr_types))
*)
CTC |- Indep_1 : , < : Table
--------------------------------------------
CTC |- PruneOp[field , axis]{}(Indep_1 ) : PT_1
| POPrune field
- >
let _ = access_nosub dep_exprs in
( PT_Table(access_one_table_type indep_expr_types ) )
CTC |- Indep_1 : PT_1, PT_1 <: Table
--------------------------------------------
CTC |- PruneOp[field,axis]{}(Indep_1) : PT_1
| POPrune field
->
let _ = access_nosub dep_exprs in
(PT_Table(access_one_table_type indep_expr_types))
*)
XPath evaluation
------------------------------------------
CTC |- ParseStreamOp[uri ] { } ( ) : SAX STREAM
------------------------------------------
CTC |- ParseStreamOp[uri]{}() : SAX STREAM
*)
| POParse_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
sax_stream_xml_type
----------------------------------------
CTC |- ParseLoadOp[uri ] { } ( ) : DOM CURSOR
----------------------------------------
CTC |- ParseLoadOp[uri]{}() : DOM CURSOR
*)
| POParse_Load ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
dom_cursor_xml_type
CTC |- Indep_1 : , < : XML
---------------------------------------
CTC |- TreeJoin_SortOp{}(Indep_1 ) : DOM
CTC |- Indep_1 : PT_1, PT_1 <: XML
---------------------------------------
CTC |- TreeJoin_SortOp{}(Indep_1) : DOM
*)
| POTreeJoin_Sort ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
This is dealing with tables ! -
dom_list_xml_type
CTC |- Indep_1 : , < : XML
----------------------------------------------
CTC |- TreeJoin_SortOp{}(Indep_1 ) : SAX STREAM
CTC |- Indep_1 : PT_1, PT_1 <: XML
----------------------------------------------
CTC |- TreeJoin_SortOp{}(Indep_1) : SAX STREAM
*)
| POTreeJoin_Stream ->
let _ = access_nosub dep_exprs in
Make sure the input is a Sax Stream as expected . -
let _ = access_one_sax_stream_xml_type indep_expr_types in
sax_stream_xml_type
CTC |- Indep_1 : , < : XML
----------------------------------------------------
CTC |- TreeJoin_NestedLoopOp{}(Indep_1 ) : DOM CURSOR
CTC |- Indep_1 : PT_1, PT_1 <: XML
----------------------------------------------------
CTC |- TreeJoin_NestedLoopOp{}(Indep_1) : DOM CURSOR
*)
| POTreeJoin_NestedLoop ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_cursor_xml_type
(* Type operators *)
CTC |- Indep_1 : , < : XML
--------------------------------------
CTC |- TreatOp{}(Indep_1 ) : DOM CURSOR
CTC |- Indep_1 : PT_1, PT_1 <: XML
--------------------------------------
CTC |- TreatOp{}(Indep_1) : DOM CURSOR
*)
| POTreat ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_cursor_xml_type
CTC |- Indep_1 : , < : XML
-----------------------------------
CTC |- CastOp{}(Indep_1 ) : DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
-----------------------------------
CTC |- CastOp{}(Indep_1) : DOM LIST
*)
| POCast ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
-----------------------------------
CTC |- CastOp{}(Indep_1 ) : DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
-----------------------------------
CTC |- CastOp{}(Indep_1) : DOM LIST
*)
| POCastable ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
-----------------------------------------
CTC |- ValidateOp{}(Indep_1 ) : SAX STREAM
CTC |- Indep_1 : PT_1, PT_1 <: XML
-----------------------------------------
CTC |- ValidateOp{}(Indep_1) : SAX STREAM
*)
| POValidate ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
sax_stream_xml_type
(* Tuple Maps *)
CTC |- Indep_1 : , < : Table
PT = [ q : DOM LIST ] @ PT_1
----------------------------------------
CTC |- NullMapOp[q]{}(Indep_1 ) : PT
CTC |- ) : PT
CTC |- MapIndexStepOp[q]{}(Indep_1 ) : PT
CTC |- Indep_1 : PT_1, PT_1 <: Table
PT = [q : DOM LIST] @ PT_1
----------------------------------------
CTC |- NullMapOp[q]{}(Indep_1) : PT
CTC |- MapIndexOp[q]{}(Indep_1) : PT
CTC |- MapIndexStepOp[q]{}(Indep_1) : PT
*)
| PONullMap name
| POMapIndex name
| POMapIndexStep name ->
let _ = access_nosub dep_exprs in
(PT_Table((name, dom_list_type) :: access_one_table_type indep_expr_types))
(* Update operations *)
(* All update operators yield materialized XML *)
CTC |- Indep_1 : , < : XML
----------------------------------
CTC |- CopyOp{}(Indep_1 ) : DOM
CTC |- DeleteOp{}(Indep_1 ) : DOM
CTC |- DetachOp{}(Indep_1 ) : DOM
CTC |- Indep_1 : PT_1, PT_1 <: XML
----------------------------------
CTC |- CopyOp{}(Indep_1) : DOM
CTC |- DeleteOp{}(Indep_1) : DOM
CTC |- DetachOp{}(Indep_1) : DOM
*)
| POCopy
| PODelete
->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_list_xml_type
CTC |- Dep : PT , PT < : XML
--------------------------
CTC |- SnapOp{Dep } ( ) : PT
CTC |- Dep : PT, PT <: XML
--------------------------
CTC |- SnapOp{Dep}() : PT
*)
| POSnap ->
let _ = access_no_type indep_expr_types in
let e = access_onesub dep_exprs in
let _ = assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc e) in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
CTC |- Indep_2 : PT_2 , PT_2 < : XML
----------------------------------------
CTC |- RenameOp{}(Indep_1,Indep_2 ) : DOM
CTC |- InsertOp{}(Indep_1,Indep_2 ) : DOM
CTC |- ReplaceOp{}(Indep_1,Indep_2 ) : DOM
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Indep_2 : PT_2, PT_2 <: XML
----------------------------------------
CTC |- RenameOp{}(Indep_1,Indep_2) : DOM
CTC |- InsertOp{}(Indep_1,Indep_2) : DOM
CTC |- ReplaceOp{}(Indep_1,Indep_2) : DOM
*)
| PORename
| POInsert
| POReplace
->
let _ = access_nosub dep_exprs in
let _ = access_two_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
| POSet vn ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
PT_XML (get_variable_type ctc vn)
XPath evaluation
CTC |- Indep_1 : , < : Table
PT = [ : DOM ; ... , q_n : DOM ] @ PT_1
--------------------------------------------------------
CTC |- TupleTreePatternOp[q_1, ... ,q_n]{}(Indep_1 ) : PT
CTC |- Indep_1 : PT_1, PT_1 <: Table
PT = [q_1 : DOM; ..., q_n : DOM] @ PT_1
--------------------------------------------------------
CTC |- TupleTreePatternOp[q_1,...,q_n]{}(Indep_1) : PT
*)
| POTupleTreePattern_NestedLoop output_fields
| POTupleTreePattern_TwigJoin output_fields
| POTupleTreePattern_SCJoin output_fields
->
let _ = access_nosub dep_exprs in
PT_Table((List.map (fun f -> (f, dom_list_type)) output_fields) @ (access_one_table_type indep_expr_types))
| POTupleTreePattern_IndexSortJoin output_fields ->
raise (Query (Prototype "Index-sort join not supported for Twigs yet."))
| POTupleTreePattern_Streaming output_fields ->
raise (Query (Prototype "Streaming not supported for Twigs yet."))
CTC |- Indep_1 : , < : XML
CTC |- Dep_2 : PT_2 , PT_2 < : XML
-----------------------------------------
CTC |- WhileOp{Dep_2}{Indep_1 } : PT_2
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Dep_2 : PT_2, PT_2 <: XML
-----------------------------------------
CTC |- WhileOp{Dep_2}{Indep_1} : PT_2
*)
| POWhile ->
let _ = access_no_type indep_expr_types in
let dep_sub_expr_types = code_typing_sub_exprs code_ctxt ctc dep_exprs in
let t1,t2 = access_two_non_discarded_xml_types dep_sub_expr_types in
PT_XML(t2)
CTC |- Indep_1 : , < : XML
CTC |- Dep_2 : PT_2 , PT_2 < : XML
CTC |- : PT_3 , PT_3 < : XML
PT = LeastUpperBound(PT_2,PT_3 )
---------------------------------------
CTC |- IfOp{Dep_2 , Dep_3}{Indep_1 } : PT
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Dep_2 : PT_2, PT_2 <: XML
CTC |- Dep_3 : PT_3, PT_3 <: XML
PT = LeastUpperBound(PT_2,PT_3)
---------------------------------------
CTC |- IfOp{Dep_2, Dep_3}{Indep_1} : PT
*)
| POIf ->
let _ = access_one_non_discarded_xml_type indep_expr_types in
let dep_sub_expr_types = code_typing_sub_exprs code_ctxt ctc dep_exprs in
let (t2, t3) = access_two_non_discarded_xml_types dep_sub_expr_types in
PT_XML(least_upper_xml_type t2 t3)
CTC |- Indep_1 : , < : XML
PVT = [ v : ' ]
CTC + ( v : ' ) |- Dep_2 : PT_2
PT_2 < : Table
-----------------------------------------------------
CTC |- MapFromItemOp[[PVT]][v]{Dep_2}{Indep_1 } : PT_2
CTC |- Indep_1 : PT_1, PT_1 <: XML
PVT = [v : PT_1']
CTC + (v : PT_1') |- Dep_2 : PT_2
PT_2 <: Table
-----------------------------------------------------
CTC |- MapFromItemOp[[PVT]][v]{Dep_2}{Indep_1} : PT_2
*)
| POMapFromItem (v, t) ->
let _ = access_one_non_discarded_xml_type indep_expr_types in
let ctc' = add_variable_type ctc v t in
let e1 = access_onesub dep_exprs in
assert_table_type(code_typing_expr code_ctxt ctc' e1)
CTC |- Indep_1 : , < : XML
PVT = [ v : ' ]
CTC + ( v : ' ) |- Dep_2 : PT_2
PT_2 < : XML
---------------------------------------------
CTC |- LetOp[[PVT]][v]{Dep_2}{Indep_1 } : PT_2
CTC |- Indep_1 : PT_1, PT_1 <: XML
PVT = [v : PT_1']
CTC + (v : PT_1') |- Dep_2 : PT_2
PT_2 <: XML
---------------------------------------------
CTC |- LetOp[[PVT]][v]{Dep_2}{Indep_1} : PT_2
*)
| POLetvar (v, t) ->
let _ = access_one_non_discarded_xml_type indep_expr_types in
let ctc' = add_variable_type ctc v t in
let e1 = access_onesub dep_exprs in
PT_XML(assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' e1))
CTC |- Indep : PT , PT < : XML
CTC + ( v : ) |- Dep_1 : , < : XML
...
CTC + ( v : PT_n ) |- Dep_n : PT_n , PT_n < : XML
---------------------------------------------------------
CTC |- Typeswitch[v1, ... ,vn]{Dep_1, ... Dep_n}{Indep } : DOM
CTC |- Indep : PT, PT <: XML
CTC + (v : PT_1) |- Dep_1 : PT_1, PT_1 <: XML
...
CTC + (v : PT_n) |- Dep_n : PT_n, PT_n <: XML
---------------------------------------------------------
CTC |- Typeswitch[v1,...,vn]{Dep_1,...Dep_n}{Indep} : DOM
*)
| POTypeswitch vn_array
->
This needs to be based on use count information .
May return ' too small ' types right now ! -
May return 'too small' types right now! - Michael *)
begin
try
let t1 = access_one_non_discarded_xml_type indep_expr_types in
let earray = access_manysub dep_exprs in
let vn_expr_list = List.combine (Array.to_list vn_array) (Array.to_list earray) in
PT_XML(
List.fold_left
(fun t (vopt, e) ->
let t' =
assert_non_discarded_xml_type(
match vopt with
| None ->
code_typing_expr code_ctxt ctc e
| Some v ->
let ctc' = add_variable_type ctc v t1 in
code_typing_expr code_ctxt ctc' e)
in
least_upper_xml_type t t'
) (PT_Sax PT_Stream) vn_expr_list)
with
| Invalid_argument msg -> raise (Query(Code_Selection("In type_check_physical_op, Typeswitch arguments do not match. "^msg)))
end
CTC |- Indep : PT , PT < : Table
CTC + ( INPUT : PT ) |- Dep_1 : , < : XML
...
CTC + ( INPUT : PT ) |- Dep_n : PT_n , PT_n < : XML
-----------------------------------------------
CTC |- Select{Dep_1, ... ,Dep_n}(Indep ) : PT
CTC |- Indep : PT, PT <: Table
CTC + (INPUT : PT) |- Dep_1 : PT_1, PT_1 <: XML
...
CTC + (INPUT : PT) |- Dep_n : PT_n, PT_n <: XML
-----------------------------------------------
CTC |- Select{Dep_1,...,Dep_n}(Indep) : PT
*)
| POSelect ->
let t1 = access_one_table_type indep_expr_types in
let earray = access_manysub dep_exprs in
let ctc' = add_input_type ctc t1 in
let _ = Array.map (fun ei -> assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' ei)) earray in
PT_Table(t1)
CTC |- Indep_1 : , < : Table
CTC + ( INPUT : ) |- Dep_2 : PT_2 , PT_2 < : Table
-----------------------------------------------------
CTC |- Map{Dep_2}(Indep_1 ) : PT_2
CTC |- Indep_1 : PT_1, PT_1 <: Table
CTC + (INPUT : PT_1) |- Dep_2 : PT_2, PT_2 <: Table
-----------------------------------------------------
CTC |- Map{Dep_2}(Indep_1) : PT_2
*)
| POMap ->
let t1 = access_one_table_type indep_expr_types in
let e2 = access_onesub dep_exprs in
let ctc' = add_input_type ctc t1 in
assert_table_type(code_typing_expr code_ctxt ctc' e2)
CTC |- Indep_1 : , < : Table
CTC + ( INPUT : ) |- Dep_2 : PT_2 , PT_2 < : Table
---------------------------------------------------
CTC |- MapConcatOp{Dep_2}{Indep_1 ) : PT_1 @ PT_2
CTC |- Indep_1 : PT_1, PT_1 <: Table
CTC + (INPUT : PT_1) |- Dep_2 : PT_2, PT_2 <: Table
---------------------------------------------------
CTC |- MapConcatOp{Dep_2}{Indep_1) : PT_1 @ PT_2
*)
| POMapConcat ->
let t1 = access_one_table_type indep_expr_types in
let e2 = access_onesub dep_exprs in
let ctc' = add_input_type ctc t1 in
let t2 = assert_tuple_type(code_typing_expr code_ctxt ctc' e2) in
PT_Table (t1 @ t2)
CTC |- Indep_1 : , < : Table
CTC + ( INPUT : ) |- Dep_2 : PT_2 , PT_2 < : Table
PT_3 = [ v : DOM LIST ] @ PT_1 @ PT2
---------------------------------------------------
CTC |- OMapConcatOp[v]{Dep_2}{Indep_1 ) : PT_3
CTC |- Indep_1 : PT_1, PT_1 <: Table
CTC + (INPUT : PT_1) |- Dep_2 : PT_2, PT_2 <: Table
PT_3 = [v : DOM LIST] @ PT_1 @ PT2
---------------------------------------------------
CTC |- OMapConcatOp[v]{Dep_2}{Indep_1) : PT_3
*)
| POOuterMapConcat v ->
let t1 = access_one_table_type indep_expr_types in
let e2 = access_onesub dep_exprs in
let ctc' = add_input_type ctc t1 in
let t2 = assert_tuple_type(code_typing_expr code_ctxt ctc' e2) in
PT_Table ((v, dom_list_type) :: t1 @ t2)
Need auxilliary judgement for concat(PT ) according to function
Xquery_physical_type_ast_util.concat_xml_type . - Michael
CTC |- Indep_1 : , < : Table
CTC + ( INPUT : ) |- Dep_2 : PT_2 , PT_2 < : XML
-------------------------------------------------
CTC |- MapToItemOp{Dep_2}{Indep_1 ) : concat(PT_2 )
Need auxilliary judgement for concat(PT) according to function
Xquery_physical_type_ast_util.concat_xml_type. - Michael
CTC |- Indep_1 : PT_1, PT_1 <: Table
CTC + (INPUT : PT_1) |- Dep_2 : PT_2, PT_2 <: XML
-------------------------------------------------
CTC |- MapToItemOp{Dep_2}{Indep_1) : concat(PT_2)
*)
| POMapToItem ->
let t1 = access_one_table_type indep_expr_types in
let e2 = access_onesub dep_exprs in
let ctc' = add_input_type ctc t1 in
let t2 = assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' e2) in
A tuple to item map never returns an item list , even if the return
expression evaluates to an item list for each single tuple . -
expression evaluates to an item list for each single tuple. - Michael *)
let t2' = concat_xml_type t2 in
PT_XML(t2')
NB : These rules do not correspond to paper , which compiles
into tuple operators !
Must return item list ! - Michael
CTC |- Indep_1 : , < : XML
PVT = [ v : ' ]
CTC + ( v : ' ) |- Dep_2 : PT_2 , PT_2 < : XML
-----------------------------------------------
CTC |- SomeOp[[PVT]][v]{Dep_2}{Indep_1 ) : PT_2
CTC |- EveryOp[[PVT]][v]{Dep_2}{Indep_1 ) : PT_2
NB: These rules do not correspond to paper, which compiles
into tuple operators!
Must return item list! - Michael
CTC |- Indep_1 : PT_1, PT_1 <: XML
PVT = [v : PT_1']
CTC + (v : PT_1') |- Dep_2 : PT_2, PT_2 <: XML
-----------------------------------------------
CTC |- SomeOp[[PVT]][v]{Dep_2}{Indep_1) : PT_2
CTC |- EveryOp[[PVT]][v]{Dep_2}{Indep_1) : PT_2
*)
| POSome (v, t) ->
let _ = access_one_non_discarded_xml_type indep_expr_types in
let ctc' = add_variable_type ctc v t in
let e2 = access_onesub dep_exprs in
let t2 = assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' e2) in
PT_XML(t2) (* dom_list_xml_type *)
| POEvery (v, t) ->
let _ = access_one_non_discarded_xml_type indep_expr_types in
let ctc' = add_variable_type ctc v t in
let e2 = access_onesub dep_exprs in
let t2 = assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' e2) in
PT_XML(t2) (* dom_list_xml_type *)
Need auxilliary judgement for mat(PT ) according to function
Xquery_physical_type_ast_util.materialize_xml_type . - Michael
CTC |- Indep : PT , PT < : Table
CTC + ( INPUT : PT ) |- Dep_1 : , < : XML
...
CTC + ( INPUT : PT ) |- Dep_n : PT_n , PT_n < : XML
----------------------------------------------------------
CTC |- OrderBy[v1, ... ,vn]{Dep_1, ... Dep_n}{Indep } : mat(PT )
Need auxilliary judgement for mat(PT) according to function
Xquery_physical_type_ast_util.materialize_xml_type. - Michael
CTC |- Indep : PT, PT <: Table
CTC + (INPUT : PT) |- Dep_1 : PT_1, PT_1 <: XML
...
CTC + (INPUT : PT) |- Dep_n : PT_n, PT_n <: XML
----------------------------------------------------------
CTC |- OrderBy[v1,...,vn]{Dep_1,...Dep_n}{Indep} : mat(PT)
*)
| POOrderBy ->
let t1 = access_one_table_type indep_expr_types in
The tuple cursor is materialized to an array of DOM values .
let t1' = List.map (fun (n, t) -> (n, materialize_xml_type t)) t1 in
let earray = access_manysub dep_exprs in
let ctc' = add_input_type ctc t1 in
let _ = Array.map (fun ei -> assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' ei)) earray in
PT_Table(t1')
Operators with TWO Table inputs
Need auxilliary judgement for mat(PT ) according to function
Xquery_physical_type_ast_util.materialize_xml_type . - Michael
CTC |- Indep_1 : , < : Table
CTC |- Indep_2 : PT_2 , PT_2 < : Table
PT = PT_1 @ mat(PT_2 )
CTC + ( INPUT : PT ) |- Dep_1 : , < : XML
...
CTC + ( INPUT : PT ) |- Dep_n : PT_n , PT_n < : XML
----------------------------------------------------
CTC |- JoinOp{Dep_1, ... ,Dep_n}(Indep_1,Indep_2 ) : PT
Need auxilliary judgement for mat(PT) according to function
Xquery_physical_type_ast_util.materialize_xml_type. - Michael
CTC |- Indep_1 : PT_1, PT_1 <: Table
CTC |- Indep_2 : PT_2, PT_2 <: Table
PT = PT_1 @ mat(PT_2)
CTC + (INPUT : PT) |- Dep_1 : PT_1, PT_1 <: XML
...
CTC + (INPUT : PT) |- Dep_n : PT_n, PT_n <: XML
----------------------------------------------------
CTC |- JoinOp{Dep_1,...,Dep_n}(Indep_1,Indep_2) : PT
*)
| POJoin_Hash
| POJoin_Sort
| POJoin_NestedLoop ->
let (t1, t2) = access_two_table_types indep_expr_types in
The right side is materialized to an array of DOM values .
let t2' = List.map (fun (n, t) -> (n, materialize_xml_type t)) t2 in
let pt = (t1 @ t2') in
let earray = access_manysub dep_exprs in
let ctc' = add_input_type ctc pt in
let _ = Array.map (fun ei -> assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' ei)) earray in
PT_Table(pt)
CTC |- Indep_1 : , < : Table
CTC |- Indep_2 : PT_2 , PT_2 < : Table
PT = PT_1 @ PT_2
CTC + ( INPUT : PT ) |- Dep_1 : , < : XML
...
CTC + ( INPUT : PT ) |- Dep_n : PT_n , PT_n < : XML
PT ' = [ v : DOM ] @ PT
------------------------------------------------------
CTC |- LeftOuterJoinOp[v]{Dep_1, ... ,Dep_n}(Indep_1,Indep_2 ) : PT '
CTC |- Indep_1 : PT_1, PT_1 <: Table
CTC |- Indep_2 : PT_2, PT_2 <: Table
PT = PT_1 @ PT_2
CTC + (INPUT : PT) |- Dep_1 : PT_1, PT_1 <: XML
...
CTC + (INPUT : PT) |- Dep_n : PT_n, PT_n <: XML
PT' = [v : DOM] @ PT
------------------------------------------------------
CTC |- LeftOuterJoinOp[v]{Dep_1,...,Dep_n}(Indep_1,Indep_2) : PT'
*)
| POLeftOuterJoin_Hash v
| POLeftOuterJoin_Sort v
| POLeftOuterJoin_NestedLoop v
->
let (t1, t2) = access_two_table_types indep_expr_types in
let pt = (t1 @ t2) in
let earray = access_manysub dep_exprs in
let ctc' = add_input_type ctc pt in
let _ = Array.map (fun ei -> assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' ei)) earray in
PT_Table((v, dom_list_type) :: pt)
Grouping and Ordering operations
CTC |- Indep : PT , PT < : Table
CTC + ( INPUT : PT ) |- Dep_1 : , < : XML
...
CTC + ( INPUT : PT ) |- Dep_n : PT_n , PT_n < : XML
PT ' = [ v_1 : DOM; ... : DOM ] @ PT
------------------------------------------------------
CTC |- GroupByOp[v_1, ... ,v_k]{Dep_1, ... ,Dep_n}(Indep ) : PT '
CTC |- Indep : PT, PT <: Table
CTC + (INPUT : PT) |- Dep_1 : PT_1, PT_1 <: XML
...
CTC + (INPUT : PT) |- Dep_n : PT_n, PT_n <: XML
PT' = [v_1 : DOM;...;v_k : DOM] @ PT
------------------------------------------------------
CTC |- GroupByOp[v_1,...,v_k]{Dep_1,...,Dep_n}(Indep) : PT'
*)
(* ??Question:?? Are only the aggregate fields added to the result tuple ?? *)
| POGroupBy agg_name_list ->
let t1 = access_one_table_type indep_expr_types in
let earray = access_manysub dep_exprs in
let ctc' = add_input_type ctc t1 in
let _ = Array.map (fun ei -> assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' ei)) earray in
PT_Table((List.map (fun vi -> (vi, dom_list_type)) agg_name_list) @ t1)
| POProject fields ->
let _ = access_nosub dep_exprs in
PT_Table(List.map (fun f -> (f, dom_list_type)) (Array.to_list fields))
@ ( access_one_table_type indep_expr_types ) )
in (pop, indep_expr_types, output_type)
with exn -> (print_string ((Print_xquery_physical_type.string_of_physop_expr_name pop)^" XXXXX\n"); raise exn)
and code_typing_expr_parts code_ctxt ctc algop_expr =
try
let indep_sub_exprs = algop_expr.psub_expression in
let dep_sub_exprs = algop_expr.pdep_sub_expression in
1 . : T1 ... Ik : Tk in environment PEnv
2 . For , and T1 .... Tk pick up the corresponding physical operator POp .
let indep_sub_expr_types = code_typing_sub_exprs code_ctxt ctc indep_sub_exprs in
let pop = select_physical_op ctc code_ctxt algop_expr indep_sub_expr_types in
3 - 6 . Apply type checking for possible additional constraints on the
( type of POp ) , and compute the output physical type T_OUT ) . This
( yields the physical type signature )
(type of POp), and compute the output physical type T_OUT). This
(yields the physical type signature) P_Sig *)
type_check_physical_op code_ctxt ctc pop indep_sub_expr_types dep_sub_exprs
with
| exn -> (raise (error_with_file_location algop_expr.palgop_expr_loc exn))
and code_typing_expr code_ctxt ctc algop_expr =
let phys_sig = code_typing_expr_parts code_ctxt ctc algop_expr in
7 . Annotate the AST with the physical operator and types .
algop_expr.palgop_expr_eval_sig <- (Some phys_sig);
let (phys_op, input_types, output_type) = phys_sig in
output_type
(* sax_stream_xml_type *)
(* Recursively type sub-expressions, which has the side effect of
annotating sub-expressions with their physical operators and
physical types. *)
and code_typing_sub_exprs code_ctxt ctc sub_exprs =
match sub_exprs with
| NoSub ->
NoInput
| OneSub op1 ->
OneInput (code_typing_expr code_ctxt ctc op1)
| TwoSub (op1,op2) ->
TwoInput(code_typing_expr code_ctxt ctc op1, code_typing_expr code_ctxt ctc op2)
| ManySub op_array ->
ManyInput (Array.map (code_typing_expr code_ctxt ctc) op_array)
let code_typing_statement code_ctxt astmt =
(* For a top-level statement, we store the compilation annotations
as both global and local annotations *)
let code_ctxt' = store_annotation code_ctxt astmt.compile_annotations in
let code_ctxt'' = store_global_annotation code_ctxt' astmt.compile_annotations in
let ctc = (code_type_context_from_code_selection_context code_ctxt) in
ignore(code_typing_expr code_ctxt'' ctc astmt);
ctc
(* Variable or index declaration *)
(* Physical typing of the top-level variable/index declarations
extends the code-type context *)
let code_typing_decl code_ctxt ctc var_decl =
match var_decl.alg_decl_name with
| AOEVarDecl (_, cvname) ->
let e1 = access_onesub var_decl.alg_decl_indep in
let _ = access_nosub var_decl.alg_decl_dep in
let code_ctxt' = store_global_annotation code_ctxt e1.compile_annotations in
let output_type = code_typing_expr code_ctxt' ctc e1 in
add_variable_type ctc cvname (assert_non_discarded_xml_type output_type)
| AOEVarDeclExternal (_, cvname)
| AOEVarDeclImported (_, cvname) ->
(* TODO! What is the physical type of externally declared and imported variables?
A completely materialized XML value?
*)
let _ = access_nosub var_decl.alg_decl_indep in
let _ = access_nosub var_decl.alg_decl_dep in
add_variable_type ctc cvname dom_list_type
| AOEValueIndexDecl str ->
let e1 = access_onesub var_decl.alg_decl_indep in
let e2 = access_onesub var_decl.alg_decl_dep in
let _ = code_typing_expr code_ctxt ctc e1 in
let _ = code_typing_expr code_ctxt ctc e2 in
ctc
| AOENameIndexDecl rsym ->
let _ = access_nosub var_decl.alg_decl_indep in
let _ = access_nosub var_decl.alg_decl_dep in
ctc
(* Function declaration *)
let code_typing_function_decl code_ctxt ctc func_decl =
let ((fname, ct), sign, func_defn,_) = func_decl.palgop_function_decl_desc in
(* Now we have to assign physical types to the formal vars and
compute the physical types for the function body *)
let ctc' = Array.fold_left (fun ctc v -> add_variable_type ctc v dom_list_type) ctc func_defn.palgop_func_formal_args in
match !(func_defn.palgop_func_optimized_logical_plan) with
| AOEFunctionImported -> ()
| AOEFunctionUser userbody ->
let code_ctxt' = store_global_annotation code_ctxt userbody.compile_annotations in
ignore(code_typing_expr code_ctxt' ctc' userbody)
Prolog
let code_typing_prolog_aux code_ctxt ctc aprolog =
let ctc' = List.fold_left (code_typing_decl code_ctxt) ctc aprolog.palgop_prolog_vars in
let ctc'' = List.fold_left (code_typing_decl code_ctxt) ctc' aprolog.palgop_prolog_indices in
let _ = List.iter (code_typing_function_decl code_ctxt ctc'') aprolog.palgop_prolog_functions in
ctc''
let code_typing_prolog code_ctxt aprolog =
print_string " In code_typing_prolog\n " ;
let x = Print_xquery_algebra.bprintf_logical_algprolog " > > > > > > > > > > > > > > \n " aprolog
in print_string ( x^"\n<<<<<<<<<<\n\n " ) ;
print_string "In code_typing_prolog\n";
let x = Print_xquery_algebra.bprintf_logical_algprolog ">>>>>>>>>>>>>>\n" aprolog
in print_string (x^"\n<<<<<<<<<<\n\n");
*)
let ctc = (code_type_context_from_code_selection_context code_ctxt) in
code_typing_prolog_aux code_ctxt ctc aprolog
| exn - > ( printf_error_safe " \nIn Cs_code_typing_top.code_typing_prolog " exn ; ctc )
(* Module *)
let code_typing_module code_ctxt amodule =
(* print_string "In code_typing_module\n";*)
let ctc = (code_type_context_from_code_selection_context code_ctxt) in
let ctc' = code_typing_prolog_aux code_ctxt ctc amodule.palgop_module_prolog in
let _ = List.map (code_typing_expr code_ctxt ctc') amodule.palgop_module_statements in
ctc'
| exn - > ( printf_error_safe " \nIn Cs_code_typing_top.code_typing_module " exn ; ctc )
| null | https://raw.githubusercontent.com/jeromesimeon/Galax/bc565acf782c140291911d08c1c784c9ac09b432/code_selection/cs_code_typing_top.ml | ocaml | *********************************************************************
GALAX
XQuery Engine
Distributed only by permission.
*********************************************************************
Module: Cs_code_typing_top.
Description:
This module implements the physical typing and physical-operator
assignment phase.
For an arbitrary algebraic operator, compute the physical type of its input
***********************
Functional operations
***********************
***************
Constructors
***************
****************
Type operators
****************
**********************
**********************
*****************
Tuple operators
*****************
********
Joins
********
***************
Map operators
***************
*******************
Update operations
*******************
For group operators, we just need the names of the new aggregate fields
*******
Other
*******
for server P close E always returns a tree...
eval closure E
We have no bloody idea what type the evaluation of a closure returns, so we assume a tree
Type check operator and compute output type.
Special treatment of streamed fn:count function
Special treatment of streamed fs:item-to-node() function
Must assert non-discarded XML type at binding time.
Forces materialization for global variables -- we need to do better, but this is broken right now
But all other constructors yield materialized items
---------------------------------
CTC |- ScalarOp[a]{}() : DOM LIST
PT = CTC[INPUT]#q
--------------------------------
CTC |- AccessTupleOp[q]{}() : PT
Must assert non-discarded XML type at binding time.
Must assert non-discarded XML type at binding time.
Type operators
Tuple Maps
Update operations
All update operators yield materialized XML
dom_list_xml_type
dom_list_xml_type
??Question:?? Are only the aggregate fields added to the result tuple ??
sax_stream_xml_type
Recursively type sub-expressions, which has the side effect of
annotating sub-expressions with their physical operators and
physical types.
For a top-level statement, we store the compilation annotations
as both global and local annotations
Variable or index declaration
Physical typing of the top-level variable/index declarations
extends the code-type context
TODO! What is the physical type of externally declared and imported variables?
A completely materialized XML value?
Function declaration
Now we have to assign physical types to the formal vars and
compute the physical types for the function body
Module
print_string "In code_typing_module\n"; | Copyright 2001 - 2007 .
$ I d : , v 1.47 2007/10/16 01:25:34
open Code_selection_context
open Code_typing_context
open Xquery_algebra_ast
open Xquery_algebra_ast_util
open Xquery_physical_type_ast
open Xquery_physical_type_ast_util
open Xquery_physical_algebra_ast
open Error
Architecture
------------
1 . We are decoupling the code selection into two phases :
Phase1 : physical operator assignment . This decide which physical
operator to use and does the corresponding physical typing .
Phase2 : actual code selection , which :
( 1 ) allocate variable and tuple resources on the stack frame
( 2 ) builds the code for each physical operator
2 . Code selection should remain ( mostly ) unchanged , except that
it will be cleaned up of physical algorithm decision , and of the
corresponding annotation / signature computation .
3 . There is a new phase , which does physical assignment and type
checking . Here is how the recursion will proceed for type checking and
physical assignment :
For Op{D1, ... Dn}(I1, ... ) in environment PEnv
( 1 ) : T1 ... Ik : Tk in environment PEnv
( 2 ) For Op , and T1 .... Tk pick up the corresponding physical
operator POp .
( 3 ) From POp , compute the type T_INPUT of the Input ( item or tuple )
( 4 ) Extend environment to PEnv ' with the type T_INPUT
( 5 ) : T1 ' ... Dn : Tn ' in PEnv '
( 6 ) Apply type checking for possible additional constraints on the
( type of POp ) , and compute the ouput physical type T_OUT ) . This
( yields the physical type signature ) ( 7 ) Annotate the AST with the POp and .
PEnv |- I1 : POp1 ; ( 1 ) above
...
PEnv : POp1 ; Sigk
T_OUTPUT = EXTRACT(Sig1, ... Sigk )
Assign(Op , T_OUTPUT ) = POp , T_INPUT ( 2 ) & ( 3 ) above
PEnv ' = PEnv + INPUT : T_INPUT ( 4 ) above
PEnv ' |- D1 : POp1 ' ; ' ( 5 ) above
...
PEnv ' |- Dn : POpn ' ; Sign '
T_OUTPUT ' = EXTRACT(Sig1', ... Sign ' )
Sig = TypeCheck(POp , T_OUTPUT , T_OUTPUT ' )
----------------------------------------------
PEnv |- Op{D1, ... Dn}(I1, ... ) : POp ; Sig
Architecture
------------
1. We are decoupling the code selection into two phases:
Phase1: physical operator assignment. This decide which physical
operator to use and does the corresponding physical typing.
Phase2: actual code selection, which:
(1) allocate variable and tuple resources on the stack frame
(2) builds the code for each physical operator
2. Code selection should remain (mostly) unchanged, except that
it will be cleaned up of physical algorithm decision, and of the
corresponding annotation / signature computation.
3. There is a new phase, which does physical assignment and type
checking. Here is how the recursion will proceed for type checking and
physical assignment:
For Op{D1,...Dn}(I1,...Ik) in environment PEnv
(1) Typecheck I1 : T1 ... Ik : Tk in environment PEnv
(2) For Op, and T1....Tk pick up the corresponding physical
operator POp.
(3) From POp, compute the type T_INPUT of the Input (item or tuple)
(4) Extend environment to PEnv' with the type T_INPUT
(5) Typecheck D1 : T1' ... Dn : Tn' in PEnv'
(6) Apply type checking for possible additional constraints on the
(type of POp), and compute the ouput physical type T_OUT). This
(yields the physical type signature) P_Sig
(7) Annotate the AST with the POp and P_Sig.
PEnv |- I1 : POp1 ; Sig1 (1) above
...
PEnv |- Ik : POp1 ; Sigk
T_OUTPUT = EXTRACT(Sig1,...Sigk)
Assign(Op,T_OUTPUT) = POp,T_INPUT (2) & (3) above
PEnv' = PEnv + INPUT : T_INPUT (4) above
PEnv' |- D1 : POp1' ; Sig1' (5) above
...
PEnv' |- Dn : POpn' ; Sign'
T_OUTPUT' = EXTRACT(Sig1',...Sign')
Sig = TypeCheck(POp,T_OUTPUT,T_OUTPUT')
----------------------------------------------
PEnv |- Op{D1,...Dn}(I1,...Ik) : POp ; Sig
*)
let lookup_field_type field tuple_type =
try
List.assoc field tuple_type
with
| Not_found ->
raise(Query(Physical_Type_Error(
"Tuple field "^(Namespace_names.prefixed_string_of_rqname field)^" not found in physical type "^(Print_xquery_physical_type.string_of_physical_tuple_type tuple_type))))
let extract_output_signature algop =
match algop.palgop_expr_eval_sig with
| None ->
raise (Query(Malformed_Algebra_Expr("Physical type signature missing for algebraic operator: "^
(Print_xquery_algebra.bprintf_physical_algstatement "" algop))))
| Some (_, _, output_physical_type) -> output_physical_type
let compute_input_sig subexprs =
match subexprs with
| NoSub -> NoInput
| OneSub subexpr -> OneInput (extract_output_signature subexpr)
| TwoSub (subexpr1, subexpr2) -> TwoInput (extract_output_signature subexpr1, extract_output_signature subexpr2)
| ManySub subexpr_array -> ManyInput (Array.map extract_output_signature subexpr_array)
Select physical operator for logical operator .
Most operators have one physical implementation .
Select physical operator for logical operator.
Most operators have one physical implementation.
*)
let rec select_physical_op ctc code_ctxt algop_expr input_types =
let code_ctxt = store_annotation code_ctxt algop_expr.compile_annotations in
match algop_expr.palgop_expr_name with
| AOEIf -> POIf
| AOEWhile -> POWhile
| AOELetvar (odt, vn) ->
POLetvar (Code_binding.select_physical_variable_binding code_ctxt input_types (odt, vn))
| AOETypeswitch pat_vn_array -> POTypeswitch (Array.map snd pat_vn_array)
| AOEVar (vn) -> POVar vn
| AOECallBuiltIn ((cfname,arity), optintypes, outtype, _) ->
Code_builtin_fn.select_physical_op code_ctxt input_types algop_expr ((cfname,arity), optintypes, outtype)
| AOECallUserDefined((fname, arity), optintypes, outtype, _, _) -> POCallUserDefined
| AOECallOverloaded((cfname,arity),table) -> POCallOverloaded
| AOEConvertSimple atomic_type -> POConvertSimple
| AOEPromoteNumeric atomic_type -> POPromoteNumeric
| AOEPromoteAnyString -> POPromoteAnyString
| AOEUnsafePromoteNumeric atomic_type -> POUnsafePromoteNumeric
| AOEScalar dmv -> POScalar
| AOEEmpty -> POEmpty
| AOESeq
| AOEImperativeSeq
| AOEDocument
| AOEPI _
| AOEPIComputed
| AOEComment _
| AOECommentComputed
| AOEText _
| AOECharRef _
| AOETextComputed
| AOEElem _
| AOEAnyElem _
| AOEAttr _
| AOEAnyAttr _ ->
Now distinguishing between streamed and materialized versions
of constructors although these do not exist as alternative
implementations . This ' virtual ' distinction is needed
for proper propagation of ' non - streamability ' in case
data flow starts with a constructor . -
of constructors although these do not exist as alternative
implementations. This 'virtual' distinction is needed
for proper propagation of 'non-streamability' in case
data flow starts with a constructor. - Michael *)
Code_constructors.select_physical_op code_ctxt input_types algop_expr
| AOEError -> POError
| AOETreat cmodel1 -> POTreat
| AOEValidate vmode -> POValidate
| AOECast (nsenv, cmodel1) -> POCast
| AOECastable (nsenv, cmodel1) -> POCastable
Item / Tuple operators
| AOESome (odt, vn) ->
POSome (Code_binding.select_physical_variable_binding code_ctxt input_types (odt, vn))
| AOEEvery (odt, vn) ->
POEvery (Code_binding.select_physical_variable_binding code_ctxt input_types (odt, vn))
| AOEMapToItem -> POMapToItem
| AOEMapFromItem vn ->
POMapFromItem (Code_binding.select_physical_variable_binding code_ctxt input_types (None, vn))
| AOEInputTuple -> POInputTuple
| AOECreateTuple names ->
POCreateTuple (Code_binding.select_physical_tuple_binding code_ctxt input_types names)
| AOEAccessTuple crname1 -> POAccessTuple crname1
| AOEConcatTuples -> POConcatTuples
| AOEProduct -> POProduct
| AOESelect pred -> POSelect
| AOEProject fields -> POProject fields
| AOEJoin pred_desc ->
Code_util_join.select_physical_op Code_util_join.StandardJoin algop_expr
| AOELeftOuterJoin (null_name,pred_desc) ->
Code_util_join.select_physical_op (Code_util_join.OuterJoin null_name) algop_expr
| AOEMapConcat -> POMapConcat
| AOEOuterMapConcat vn -> POOuterMapConcat vn
| AOEMap -> POMap
| AOEMapIndex vname -> POMapIndex vname
| AOEMapIndexStep vname -> POMapIndexStep vname
| AOENullMap v -> PONullMap v
| AOECopy -> POCopy
| AOEDelete -> PODelete
| AOEInsert insert_location -> POInsert
| AOERename _ -> PORename
| AOEReplace value_flag -> POReplace
| AOESnap sm -> POSnap
| AOESet (vn) -> POSet vn
| AOEParse uri ->
Code_parse.select_physical_op code_ctxt algop_expr uri
| AOETreeJoin (axis, anode_test) ->
Now passing on the input signature to treejoin code selection . -
Code_treejoin.select_physical_op code_ctxt input_types algop_expr (axis, anode_test)
| AOETupleTreePattern (input, pattern) ->
Code_tuple_tree_pattern.select_physical_op code_ctxt algop_expr (input, pattern)
Group / order
| AOEGroupBy gd_list -> POGroupBy (List.map Xquery_algebra_ast_util.get_aggregate_name gd_list)
| AOEOrderBy (stablekind, sort_spec_list, osig) -> POOrderBy
DXQ
| AOEServerImplements (ncname, uri) ->
begin
let _ = access_onesub algop_expr.psub_expression in
let dep_expr = access_onesub algop_expr.pdep_sub_expression in
let _ = code_typing_expr code_ctxt ctc dep_expr in
match (dep_expr.palgop_expr_eval_sig) with
| Some (_, _, output_type) ->
begin
match output_type with
| PT_XML _ -> POServerImplementsTree
| PT_Table _ -> POServerImplementsTuple
end
| None -> raise(Query(Internal_Error("AOEServerImplements input does not have physical type")))
end
| AOEForServerClose (ncname, uri) ->
Debug.print_dxq_debug ("cs_code_typing_top : Before for-server access_onesub\n");
let indep_expr = access_onesub algop_expr.psub_expression in
Debug.print_dxq_debug ("cs_code_typing_top : After for-server access_onesub\n");
let _ = code_typing_expr code_ctxt ctc indep_expr in
POForServerCloseTree
| AOEEvalClosure ->
Debug.print_dxq_debug ("cs_code_typing_top : Before eval-box access_onesub\n");
Debug.print_dxq_debug ((Print_xquery_algebra.bprintf_logical_algstatement "" algop_expr)^"\n");
let indep_expr = access_onesub algop_expr.psub_expression in
Debug.print_dxq_debug ("cs_code_typing_top : After eval-box access_onesub\n");
let _ = code_typing_expr code_ctxt ctc indep_expr in
POEvalClosureTree
| AOEExecute (ncname, uri)
Logic is the same for async execute , even though we throw the value away
begin
Physical typing phase .
1 . Examine the physical type of the second argument to AOEExecute
1. Examine the physical type of the second argument to AOEExecute
*)
let (indep_expr1, indep_expr2) = access_twosub algop_expr.psub_expression in
match (indep_expr2.palgop_expr_eval_sig) with
| Some (_, _, output_type) ->
begin
match output_type with
| PT_XML _ -> POExecuteTree
| PT_Table _ -> POExecuteTuple
end
| None -> raise(Query(Internal_Error("AOEExecute's input does not have physical type")))
end
and type_check_physical_op code_ctxt ctc pop indep_expr_types dep_exprs =
3 . From POp , compute the type T_INPUT of the Input ( item or tuple )
4 . Extend environment to PEnv ' with the type T_INPUT
5 . : T1 ' ... Dn : Tn ' in PEnv '
try
let output_type =
match pop with
Function Calls
CTC |- Indep_1 : , < : XML
...
CTC |- Indep_n : PT_n , PT_n < : XML
---------------------------------------------------
CTC |- FuncCallOp{}(Indep_1, ... ,Indep_n ) : DOM LIST
CTC |- Indep_1 : PT_1 , PT_1 <: XML
...
CTC |- Indep_n : PT_n , PT_n <: XML
---------------------------------------------------
CTC |- FuncCallOp{}(Indep_1,...,Indep_n) : DOM LIST
*)
| POCallBuiltIn
| POCallUserDefined
| POCallOverloaded ->
let _ = access_nosub dep_exprs in
let _ = access_many_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
| POCallBuiltIn_Fn_Count_Stream ->
let _ = access_nosub dep_exprs in
Should assert sax stream input here ! -
let _ = access_many_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
Special treatment of streamed fs : first - item function
| POCallBuiltIn_Fs_First_Stream ->
let _ = access_nosub dep_exprs in
Should assert sax stream input here ! -
let _ = access_many_non_discarded_xml_types indep_expr_types in
sax_stream_xml_type
| POCallBuiltIn_Fs_Item2Node_Stream ->
let _ = access_nosub dep_exprs in
Should assert sax stream input here ! -
let _ = access_many_non_discarded_xml_types indep_expr_types in
sax_stream_xml_type
CTC |- Indep_1 : , < : XML
-----------------------------------------------
CTC |- SpecialFunCallOp{}(Indep_1 ) : DOM CURSOR
CTC |- Indep_1 : PT_1, PT_1 <: XML
-----------------------------------------------
CTC |- SpecialFunCallOp{}(Indep_1) : DOM CURSOR
*)
| POConvertSimple
| POPromoteNumeric
| POPromoteAnyString
| POUnsafePromoteNumeric ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_cursor_xml_type
Var
----------------------------
CTC |- VarOp[v ] { } ( ) : CTC[v ]
----------------------------
CTC |- VarOp[v]{}() : CTC[v]
*)
| POVar vn ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
PT_XML ( get_variable_type ctc vn )
Constructors
CTC |- Indep_1 : , < : XML
-------------------------------------------------
CTC |- DocumentOp{}(Indep1 ) : SAX STREAM / DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
-------------------------------------------------
CTC |- DocumentOp{}(Indep1) : SAX STREAM/DOM LIST
*)
| PODocument_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
sax_stream_xml_type
| PODocument_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_list_xml_type
----------------------------------------------------
CTC |- PIOp[ncname , target ] { } ( ) : SAX STREAM / DOM LIST
----------------------------------------------------
CTC |- PIOp[ncname,target]{}() : SAX STREAM/DOM LIST
*)
| POPI_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
sax_stream_xml_type
| POPI_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
CTC |- Indep_2 : PT_2 , PT_2 < : XML
-----------------------------------------------------------
CTC |- PIComputedOp{}(Indep1 , Indep2 ) : SAX STREAM / DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Indep_2 : PT_2, PT_2 <: XML
-----------------------------------------------------------
CTC |- PIComputedOp{}(Indep1, Indep2) : SAX STREAM/DOM LIST
*)
| POPIComputed_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_two_non_discarded_xml_types indep_expr_types in
sax_stream_xml_type
| POPIComputed_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_two_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
-----------------------------------------------
CTC |- CommentOp[str ] { } ( ) : SAX STREAM / DOM LIST
-----------------------------------------------
CTC |- CommentOp[str]{}() : SAX STREAM/DOM LIST
*)
| POComment_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
sax_stream_xml_type
| POComment_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
--------------------------------------------------------
CTC ) : SAX STREAM / DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
--------------------------------------------------------
CTC |- CommentComputedOp{}(Indep1) : SAX STREAM/DOM LIST
*)
| POCommentComputed_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
sax_stream_xml_type
| POCommentComputed_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_list_xml_type
--------------------------------------------
CTC |- TextOp[str ] { } ( ) : SAX STREAM / DOM LIST
--------------------------------------------
CTC |- TextOp[str]{}() : SAX STREAM/DOM LIST
*)
| POText_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
sax_stream_xml_type
| POText_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
-----------------------------------------------------
CTC |- TextComputedOp{}(Indep1 ) : SAX STREAM / DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
-----------------------------------------------------
CTC |- TextComputedOp{}(Indep1) : SAX STREAM/DOM LIST
*)
| POTextComputed_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
sax_stream_xml_type
| POTextComputed_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
...
CTC |- Indep_n : PT_n , PT_n < : XML
----------------------------------------------------------------
CTC |- ElemOp[name]{}(Indep_1, ... ,Indep_n ) : SAX STREAM / DOM LIST
CTC |- Indep_1 : PT_1 , PT_1 <: XML
...
CTC |- Indep_n : PT_n , PT_n <: XML
----------------------------------------------------------------
CTC |- ElemOp[name]{}(Indep_1,...,Indep_n) : SAX STREAM/DOM LIST
*)
| POElem_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_many_non_discarded_xml_types indep_expr_types in
sax_stream_xml_type
| POElem_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_many_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
CTC |- Indep_2 : PT_2 , PT_2 < : XML
-------------------------------------------------------
CTC |- AnyElemOp{}(Indep1,Indep2 ) : SAX STREAM / DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Indep_2 : PT_2, PT_2 <: XML
-------------------------------------------------------
CTC |- AnyElemOp{}(Indep1,Indep2) : SAX STREAM/DOM LIST
*)
| POAnyElem_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_two_non_discarded_xml_types indep_expr_types in
sax_stream_xml_type
| POAnyElem_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_two_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
...
CTC |- Indep_n : PT_n , PT_n < : XML
----------------------------------------------------------------
CTC |- AttrOp[name]{}(Indep_1, ... ,Indep_n ) : SAX STREAM / DOM LIST
CTC |- Indep_1 : PT_1 , PT_1 <: XML
...
CTC |- Indep_n : PT_n , PT_n <: XML
----------------------------------------------------------------
CTC |- AttrOp[name]{}(Indep_1,...,Indep_n) : SAX STREAM/DOM LIST
*)
| POAttr_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_many_non_discarded_xml_types indep_expr_types in
sax_stream_xml_type
| POAttr_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_many_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
CTC |- Indep_2 : PT_2 , PT_2 < : XML
-------------------------------------------------------
CTC |- AnyAttrOp{}(Indep1,Indep2 ) : SAX STREAM / DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Indep_2 : PT_2, PT_2 <: XML
-------------------------------------------------------
CTC |- AnyAttrOp{}(Indep1,Indep2) : SAX STREAM/DOM LIST
*)
| POAnyAttr_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_two_non_discarded_xml_types indep_expr_types in
sax_stream_xml_type
| POAnyAttr_Materialized ->
let _ = access_nosub dep_exprs in
let _ = access_two_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
...
CTC |- Indep_n : PT_n , PT_n < : XML
------------------------------------------------
CTC |- ErrorOp{}(Indep_1, ... ,Indep_n ) : DOM LIST
CTC |- Indep_1 : PT_1 , PT_1 <: XML
...
CTC |- Indep_n : PT_n , PT_n <: XML
------------------------------------------------
CTC |- ErrorOp{}(Indep_1,...,Indep_n) : DOM LIST
*)
| POError ->
let _ = access_nosub dep_exprs in
let _ = access_many_non_discarded_xml_types indep_expr_types in
The output type depends on the indep . input types ! -
dom_list_xml_type
-----------------------------
CTC |- EmptyOp { } ( ) : DOM LIST
-----------------------------
CTC |- EmptyOp{}() : DOM LIST
*)
| POEmpty ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
dom_list_xml_type
| POScalar ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
CTC |- Indep_2 : PT_2 , PT_2 < : XML
-----------------------------------------
CTC |- SeqOp{}(Indep1 , Indep2 ) : DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Indep_2 : PT_2, PT_2 <: XML
-----------------------------------------
CTC |- SeqOp{}(Indep1, Indep2) : DOM LIST
*)
| POSeq_Materialized
| POImperativeSeq_Materialized ->
let _ = access_nosub dep_exprs in
let (_,_) = access_two_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
| POSeq_Stream
| POImperativeSeq_Stream ->
let _ = access_nosub dep_exprs in
let (_,_) = access_two_non_discarded_xml_types indep_expr_types in
sax_stream_xml_type
Basic Tuple operations
| POAccessTuple field_name ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
PT_XML(lookup_field_type field_name (get_input_type ctc))
CTC |- Indep_1 : , < : XML
...
CTC |- Indep_n : PT_n , PT_n < : XML
PTT = [ : PTFT_1 , ... , q_n : PTFT_n ]
---------------------------------------------------------------------
CTC |- CreateTupleOp[[PTT]][q_1, ... ,q_n]{}(Indep_1, ... ,Indep_n ) : PTT
CTC |- Indep_1 : PT_1 , PT_1 <: XML
...
CTC |- Indep_n : PT_n , PT_n <: XML
PTT = [q_1 : PTFT_1, ... , q_n : PTFT_n]
---------------------------------------------------------------------
CTC |- CreateTupleOp[[PTT]][q_1,...,q_n]{}(Indep_1,...,Indep_n) : PTT
*)
| POCreateTuple names_types ->
let _ = access_nosub dep_exprs in
let _ = access_many_non_discarded_xml_types indep_expr_types in
PT_Table(names_types)
PT = CTC[INPUT ] < : Table
----------------------------
CTC |- InputTupleOp { } ( ) : PT
PT = CTC[INPUT] <: Table
----------------------------
CTC |- InputTupleOp{}() : PT
*)
| POInputTuple ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
PT_Table(get_input_type ctc)
CTC |- Indep_1 : , < : Table
CTC |- Indep_1 : PT_2 , PT_2 < : Table
-----------------------------------------------------
CTC |- ConcatTupleOp{}(Indep_1,Indep_2 ) : @ PT_2
CTC |- Indep_1 : PT_1, PT_1 <: Table
CTC |- Indep_1 : PT_2, PT_2 <: Table
-----------------------------------------------------
CTC |- ConcatTupleOp{}(Indep_1,Indep_2) : PT_1 @ PT_2
*)
| POConcatTuples ->
let _ = access_nosub dep_exprs in
let (t1, t2) = access_two_table_types indep_expr_types in
(PT_Table (t1 @ t2))
Need auxilliary judgement for mat(PT ) according to function
Xquery_physical_type_ast_util.materialize_xml_type . - Michael
CTC |- Indep_1 : , < : Table
CTC |- Indep_2 : PT_2 , PT_2 < : Table
-----------------------------------------------------------
CTC |- ProductTupleOp{}(Indep_1,Indep_2 ) : PT_1 @ mat(PT_2 )
Need auxilliary judgement for mat(PT) according to function
Xquery_physical_type_ast_util.materialize_xml_type. - Michael
CTC |- Indep_1 : PT_1, PT_1 <: Table
CTC |- Indep_2 : PT_2, PT_2 <: Table
-----------------------------------------------------------
CTC |- ProductTupleOp{}(Indep_1,Indep_2) : PT_1 @ mat(PT_2)
*)
| POProduct ->
let _ = access_nosub dep_exprs in
let (t1, t2) = access_two_table_types indep_expr_types in
The right side is materialized to an array of DOM values .
let t2' = List.map (fun (n, t) -> (n, materialize_xml_type t)) t2 in
(PT_Table (t1 @ t2'))
CTC |- Indep_1 : , < : XML
CTC |- Dep_2 : PT_2 ,
-----------------------------------------------
CTC |- ServerImplements{Dep_2}(Indep_1 ) : PT_2
Why is this rule different than all others ?
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Dep_2 : PT_2,
-----------------------------------------------
CTC |- ServerImplements{Dep_2}(Indep_1) : PT_2
Why is this rule different than all others?
*)
| POServerImplementsTree
| POServerImplementsTuple ->
let _ = access_one_non_discarded_xml_type indep_expr_types in
let dep_expr = access_onesub dep_exprs in
begin
match (dep_expr.palgop_expr_eval_sig) with
| Some (_, _, output_type) -> output_type
| None -> raise(Query(Internal_Error("POServerImplements input does not have physical type")))
end
We could have the result of a remote expression be a SAX
type ...
CTC |- Indep_1 : , < : XML
CTC |- Indep_2 : PT_2 , PT_2 < : XML
-----------------------------------------------
CTC |- Execute(Indep_1 , Indep_2 ) : DOM CURSOR
We could have the result of a remote expression be a SAX
type...
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Indep_2 : PT_2, PT_2 <: XML
-----------------------------------------------
CTC |- Execute(Indep_1, Indep_2) : DOM CURSOR
*)
| POExecuteTree ->
let _ = access_nosub dep_exprs in
let _ = access_two_non_discarded_xml_types indep_expr_types in
dom_cursor_xml_type
CTC |- Indep_1 : , < : XML
CTC |- Indep_2 : PT_2 , PT_2 < : Table
-----------------------------------------------
CTC |- Execute(Indep_1 , Indep_2 ) : Table
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Indep_2 : PT_2, PT_2 <: Table
-----------------------------------------------
CTC |- Execute(Indep_1, Indep_2) : Table
*)
| POExecuteTuple ->
let _ = access_nosub dep_exprs in
let (indep_type1, indep_type2) = access_two_types indep_expr_types in
let _ = assert_non_discarded_xml_type indep_type1 in
let _ = assert_table_type indep_type2 in
indep_type2
We have no bloody idea what the physical type of a closure is ...
CTC |- Indep_1 : , < : XML
----------------------------------------
CTC |- EvalClosure(Indep_1 ) : XML
We have no bloody idea what the physical type of a closure is...
CTC |- Indep_1 : PT_1, PT_1 <: XML
----------------------------------------
CTC |- EvalClosure(Indep_1) : XML
*)
| POEvalClosureTree ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_cursor_xml_type
We have no bloody idea what the physical type of a closure is ...
CTC |- Indep_1 : , < : XML
----------------------------------------
CTC |- EvalClosure(Indep_1 ) : Table
We have no bloody idea what the physical type of a closure is...
CTC |- Indep_1 : PT_1, PT_1 <: XML
----------------------------------------
CTC |- EvalClosure(Indep_1) : Table
*)
| POEvalClosureTuple ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
raise (Query (Prototype "No physical typing for eval-box that yields tuples."))
We have no bloody idea what the physical type of a closure is ...
CTC |- Indep_1 : , < : XML
----------------------------------------
CTC |- ForServerClose(Indep_1 ) : XML
We have no bloody idea what the physical type of a closure is...
CTC |- Indep_1 : PT_1, PT_1 <: XML
----------------------------------------
CTC |- ForServerClose(Indep_1) : XML
*)
| POForServerCloseTree ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_cursor_xml_type
We have no bloody idea what the physical type of a closure is ...
CTC |- Indep_1 : , < : XML
----------------------------------------
CTC |- ForServerClose(Indep_1 ) : Table
We have no bloody idea what the physical type of a closure is...
CTC |- Indep_1 : PT_1, PT_1 <: XML
----------------------------------------
CTC |- ForServerClose(Indep_1) : Table
*)
| POForServerCloseTuple ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
raise (Query (Prototype "No physical typing for for-server-box that yields tuples."))
CTC |- Indep_1 : , < : Table
------------------------------------
CTC |- DistinctOp{}(Indep_1 ) :
Does internal materialization of some sort.- | PODistinct name
- >
let _ = access_nosub dep_exprs in
( PT_Table(access_one_table_type indep_expr_types ) )
CTC |- Indep_1 : PT_1, PT_1 <: Table
------------------------------------
CTC |- DistinctOp{}(Indep_1) : PT_1
Does internal materialization of some sort.- Michael
| PODistinct name
->
let _ = access_nosub dep_exprs in
(PT_Table(access_one_table_type indep_expr_types))
*)
CTC |- Indep_1 : , < : Table
--------------------------------------------
CTC |- PruneOp[field , axis]{}(Indep_1 ) : PT_1
| POPrune field
- >
let _ = access_nosub dep_exprs in
( PT_Table(access_one_table_type indep_expr_types ) )
CTC |- Indep_1 : PT_1, PT_1 <: Table
--------------------------------------------
CTC |- PruneOp[field,axis]{}(Indep_1) : PT_1
| POPrune field
->
let _ = access_nosub dep_exprs in
(PT_Table(access_one_table_type indep_expr_types))
*)
XPath evaluation
------------------------------------------
CTC |- ParseStreamOp[uri ] { } ( ) : SAX STREAM
------------------------------------------
CTC |- ParseStreamOp[uri]{}() : SAX STREAM
*)
| POParse_Stream ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
sax_stream_xml_type
----------------------------------------
CTC |- ParseLoadOp[uri ] { } ( ) : DOM CURSOR
----------------------------------------
CTC |- ParseLoadOp[uri]{}() : DOM CURSOR
*)
| POParse_Load ->
let _ = access_nosub dep_exprs in
let _ = access_no_type indep_expr_types in
dom_cursor_xml_type
CTC |- Indep_1 : , < : XML
---------------------------------------
CTC |- TreeJoin_SortOp{}(Indep_1 ) : DOM
CTC |- Indep_1 : PT_1, PT_1 <: XML
---------------------------------------
CTC |- TreeJoin_SortOp{}(Indep_1) : DOM
*)
| POTreeJoin_Sort ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
This is dealing with tables ! -
dom_list_xml_type
CTC |- Indep_1 : , < : XML
----------------------------------------------
CTC |- TreeJoin_SortOp{}(Indep_1 ) : SAX STREAM
CTC |- Indep_1 : PT_1, PT_1 <: XML
----------------------------------------------
CTC |- TreeJoin_SortOp{}(Indep_1) : SAX STREAM
*)
| POTreeJoin_Stream ->
let _ = access_nosub dep_exprs in
Make sure the input is a Sax Stream as expected . -
let _ = access_one_sax_stream_xml_type indep_expr_types in
sax_stream_xml_type
CTC |- Indep_1 : , < : XML
----------------------------------------------------
CTC |- TreeJoin_NestedLoopOp{}(Indep_1 ) : DOM CURSOR
CTC |- Indep_1 : PT_1, PT_1 <: XML
----------------------------------------------------
CTC |- TreeJoin_NestedLoopOp{}(Indep_1) : DOM CURSOR
*)
| POTreeJoin_NestedLoop ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_cursor_xml_type
CTC |- Indep_1 : , < : XML
--------------------------------------
CTC |- TreatOp{}(Indep_1 ) : DOM CURSOR
CTC |- Indep_1 : PT_1, PT_1 <: XML
--------------------------------------
CTC |- TreatOp{}(Indep_1) : DOM CURSOR
*)
| POTreat ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_cursor_xml_type
CTC |- Indep_1 : , < : XML
-----------------------------------
CTC |- CastOp{}(Indep_1 ) : DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
-----------------------------------
CTC |- CastOp{}(Indep_1) : DOM LIST
*)
| POCast ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
-----------------------------------
CTC |- CastOp{}(Indep_1 ) : DOM LIST
CTC |- Indep_1 : PT_1, PT_1 <: XML
-----------------------------------
CTC |- CastOp{}(Indep_1) : DOM LIST
*)
| POCastable ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
-----------------------------------------
CTC |- ValidateOp{}(Indep_1 ) : SAX STREAM
CTC |- Indep_1 : PT_1, PT_1 <: XML
-----------------------------------------
CTC |- ValidateOp{}(Indep_1) : SAX STREAM
*)
| POValidate ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
sax_stream_xml_type
CTC |- Indep_1 : , < : Table
PT = [ q : DOM LIST ] @ PT_1
----------------------------------------
CTC |- NullMapOp[q]{}(Indep_1 ) : PT
CTC |- ) : PT
CTC |- MapIndexStepOp[q]{}(Indep_1 ) : PT
CTC |- Indep_1 : PT_1, PT_1 <: Table
PT = [q : DOM LIST] @ PT_1
----------------------------------------
CTC |- NullMapOp[q]{}(Indep_1) : PT
CTC |- MapIndexOp[q]{}(Indep_1) : PT
CTC |- MapIndexStepOp[q]{}(Indep_1) : PT
*)
| PONullMap name
| POMapIndex name
| POMapIndexStep name ->
let _ = access_nosub dep_exprs in
(PT_Table((name, dom_list_type) :: access_one_table_type indep_expr_types))
CTC |- Indep_1 : , < : XML
----------------------------------
CTC |- CopyOp{}(Indep_1 ) : DOM
CTC |- DeleteOp{}(Indep_1 ) : DOM
CTC |- DetachOp{}(Indep_1 ) : DOM
CTC |- Indep_1 : PT_1, PT_1 <: XML
----------------------------------
CTC |- CopyOp{}(Indep_1) : DOM
CTC |- DeleteOp{}(Indep_1) : DOM
CTC |- DetachOp{}(Indep_1) : DOM
*)
| POCopy
| PODelete
->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
dom_list_xml_type
CTC |- Dep : PT , PT < : XML
--------------------------
CTC |- SnapOp{Dep } ( ) : PT
CTC |- Dep : PT, PT <: XML
--------------------------
CTC |- SnapOp{Dep}() : PT
*)
| POSnap ->
let _ = access_no_type indep_expr_types in
let e = access_onesub dep_exprs in
let _ = assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc e) in
dom_list_xml_type
CTC |- Indep_1 : , < : XML
CTC |- Indep_2 : PT_2 , PT_2 < : XML
----------------------------------------
CTC |- RenameOp{}(Indep_1,Indep_2 ) : DOM
CTC |- InsertOp{}(Indep_1,Indep_2 ) : DOM
CTC |- ReplaceOp{}(Indep_1,Indep_2 ) : DOM
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Indep_2 : PT_2, PT_2 <: XML
----------------------------------------
CTC |- RenameOp{}(Indep_1,Indep_2) : DOM
CTC |- InsertOp{}(Indep_1,Indep_2) : DOM
CTC |- ReplaceOp{}(Indep_1,Indep_2) : DOM
*)
| PORename
| POInsert
| POReplace
->
let _ = access_nosub dep_exprs in
let _ = access_two_non_discarded_xml_types indep_expr_types in
dom_list_xml_type
| POSet vn ->
let _ = access_nosub dep_exprs in
let _ = access_one_non_discarded_xml_type indep_expr_types in
PT_XML (get_variable_type ctc vn)
XPath evaluation
CTC |- Indep_1 : , < : Table
PT = [ : DOM ; ... , q_n : DOM ] @ PT_1
--------------------------------------------------------
CTC |- TupleTreePatternOp[q_1, ... ,q_n]{}(Indep_1 ) : PT
CTC |- Indep_1 : PT_1, PT_1 <: Table
PT = [q_1 : DOM; ..., q_n : DOM] @ PT_1
--------------------------------------------------------
CTC |- TupleTreePatternOp[q_1,...,q_n]{}(Indep_1) : PT
*)
| POTupleTreePattern_NestedLoop output_fields
| POTupleTreePattern_TwigJoin output_fields
| POTupleTreePattern_SCJoin output_fields
->
let _ = access_nosub dep_exprs in
PT_Table((List.map (fun f -> (f, dom_list_type)) output_fields) @ (access_one_table_type indep_expr_types))
| POTupleTreePattern_IndexSortJoin output_fields ->
raise (Query (Prototype "Index-sort join not supported for Twigs yet."))
| POTupleTreePattern_Streaming output_fields ->
raise (Query (Prototype "Streaming not supported for Twigs yet."))
CTC |- Indep_1 : , < : XML
CTC |- Dep_2 : PT_2 , PT_2 < : XML
-----------------------------------------
CTC |- WhileOp{Dep_2}{Indep_1 } : PT_2
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Dep_2 : PT_2, PT_2 <: XML
-----------------------------------------
CTC |- WhileOp{Dep_2}{Indep_1} : PT_2
*)
| POWhile ->
let _ = access_no_type indep_expr_types in
let dep_sub_expr_types = code_typing_sub_exprs code_ctxt ctc dep_exprs in
let t1,t2 = access_two_non_discarded_xml_types dep_sub_expr_types in
PT_XML(t2)
CTC |- Indep_1 : , < : XML
CTC |- Dep_2 : PT_2 , PT_2 < : XML
CTC |- : PT_3 , PT_3 < : XML
PT = LeastUpperBound(PT_2,PT_3 )
---------------------------------------
CTC |- IfOp{Dep_2 , Dep_3}{Indep_1 } : PT
CTC |- Indep_1 : PT_1, PT_1 <: XML
CTC |- Dep_2 : PT_2, PT_2 <: XML
CTC |- Dep_3 : PT_3, PT_3 <: XML
PT = LeastUpperBound(PT_2,PT_3)
---------------------------------------
CTC |- IfOp{Dep_2, Dep_3}{Indep_1} : PT
*)
| POIf ->
let _ = access_one_non_discarded_xml_type indep_expr_types in
let dep_sub_expr_types = code_typing_sub_exprs code_ctxt ctc dep_exprs in
let (t2, t3) = access_two_non_discarded_xml_types dep_sub_expr_types in
PT_XML(least_upper_xml_type t2 t3)
CTC |- Indep_1 : , < : XML
PVT = [ v : ' ]
CTC + ( v : ' ) |- Dep_2 : PT_2
PT_2 < : Table
-----------------------------------------------------
CTC |- MapFromItemOp[[PVT]][v]{Dep_2}{Indep_1 } : PT_2
CTC |- Indep_1 : PT_1, PT_1 <: XML
PVT = [v : PT_1']
CTC + (v : PT_1') |- Dep_2 : PT_2
PT_2 <: Table
-----------------------------------------------------
CTC |- MapFromItemOp[[PVT]][v]{Dep_2}{Indep_1} : PT_2
*)
| POMapFromItem (v, t) ->
let _ = access_one_non_discarded_xml_type indep_expr_types in
let ctc' = add_variable_type ctc v t in
let e1 = access_onesub dep_exprs in
assert_table_type(code_typing_expr code_ctxt ctc' e1)
CTC |- Indep_1 : , < : XML
PVT = [ v : ' ]
CTC + ( v : ' ) |- Dep_2 : PT_2
PT_2 < : XML
---------------------------------------------
CTC |- LetOp[[PVT]][v]{Dep_2}{Indep_1 } : PT_2
CTC |- Indep_1 : PT_1, PT_1 <: XML
PVT = [v : PT_1']
CTC + (v : PT_1') |- Dep_2 : PT_2
PT_2 <: XML
---------------------------------------------
CTC |- LetOp[[PVT]][v]{Dep_2}{Indep_1} : PT_2
*)
| POLetvar (v, t) ->
let _ = access_one_non_discarded_xml_type indep_expr_types in
let ctc' = add_variable_type ctc v t in
let e1 = access_onesub dep_exprs in
PT_XML(assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' e1))
CTC |- Indep : PT , PT < : XML
CTC + ( v : ) |- Dep_1 : , < : XML
...
CTC + ( v : PT_n ) |- Dep_n : PT_n , PT_n < : XML
---------------------------------------------------------
CTC |- Typeswitch[v1, ... ,vn]{Dep_1, ... Dep_n}{Indep } : DOM
CTC |- Indep : PT, PT <: XML
CTC + (v : PT_1) |- Dep_1 : PT_1, PT_1 <: XML
...
CTC + (v : PT_n) |- Dep_n : PT_n, PT_n <: XML
---------------------------------------------------------
CTC |- Typeswitch[v1,...,vn]{Dep_1,...Dep_n}{Indep} : DOM
*)
| POTypeswitch vn_array
->
This needs to be based on use count information .
May return ' too small ' types right now ! -
May return 'too small' types right now! - Michael *)
begin
try
let t1 = access_one_non_discarded_xml_type indep_expr_types in
let earray = access_manysub dep_exprs in
let vn_expr_list = List.combine (Array.to_list vn_array) (Array.to_list earray) in
PT_XML(
List.fold_left
(fun t (vopt, e) ->
let t' =
assert_non_discarded_xml_type(
match vopt with
| None ->
code_typing_expr code_ctxt ctc e
| Some v ->
let ctc' = add_variable_type ctc v t1 in
code_typing_expr code_ctxt ctc' e)
in
least_upper_xml_type t t'
) (PT_Sax PT_Stream) vn_expr_list)
with
| Invalid_argument msg -> raise (Query(Code_Selection("In type_check_physical_op, Typeswitch arguments do not match. "^msg)))
end
CTC |- Indep : PT , PT < : Table
CTC + ( INPUT : PT ) |- Dep_1 : , < : XML
...
CTC + ( INPUT : PT ) |- Dep_n : PT_n , PT_n < : XML
-----------------------------------------------
CTC |- Select{Dep_1, ... ,Dep_n}(Indep ) : PT
CTC |- Indep : PT, PT <: Table
CTC + (INPUT : PT) |- Dep_1 : PT_1, PT_1 <: XML
...
CTC + (INPUT : PT) |- Dep_n : PT_n, PT_n <: XML
-----------------------------------------------
CTC |- Select{Dep_1,...,Dep_n}(Indep) : PT
*)
| POSelect ->
let t1 = access_one_table_type indep_expr_types in
let earray = access_manysub dep_exprs in
let ctc' = add_input_type ctc t1 in
let _ = Array.map (fun ei -> assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' ei)) earray in
PT_Table(t1)
CTC |- Indep_1 : , < : Table
CTC + ( INPUT : ) |- Dep_2 : PT_2 , PT_2 < : Table
-----------------------------------------------------
CTC |- Map{Dep_2}(Indep_1 ) : PT_2
CTC |- Indep_1 : PT_1, PT_1 <: Table
CTC + (INPUT : PT_1) |- Dep_2 : PT_2, PT_2 <: Table
-----------------------------------------------------
CTC |- Map{Dep_2}(Indep_1) : PT_2
*)
| POMap ->
let t1 = access_one_table_type indep_expr_types in
let e2 = access_onesub dep_exprs in
let ctc' = add_input_type ctc t1 in
assert_table_type(code_typing_expr code_ctxt ctc' e2)
CTC |- Indep_1 : , < : Table
CTC + ( INPUT : ) |- Dep_2 : PT_2 , PT_2 < : Table
---------------------------------------------------
CTC |- MapConcatOp{Dep_2}{Indep_1 ) : PT_1 @ PT_2
CTC |- Indep_1 : PT_1, PT_1 <: Table
CTC + (INPUT : PT_1) |- Dep_2 : PT_2, PT_2 <: Table
---------------------------------------------------
CTC |- MapConcatOp{Dep_2}{Indep_1) : PT_1 @ PT_2
*)
| POMapConcat ->
let t1 = access_one_table_type indep_expr_types in
let e2 = access_onesub dep_exprs in
let ctc' = add_input_type ctc t1 in
let t2 = assert_tuple_type(code_typing_expr code_ctxt ctc' e2) in
PT_Table (t1 @ t2)
CTC |- Indep_1 : , < : Table
CTC + ( INPUT : ) |- Dep_2 : PT_2 , PT_2 < : Table
PT_3 = [ v : DOM LIST ] @ PT_1 @ PT2
---------------------------------------------------
CTC |- OMapConcatOp[v]{Dep_2}{Indep_1 ) : PT_3
CTC |- Indep_1 : PT_1, PT_1 <: Table
CTC + (INPUT : PT_1) |- Dep_2 : PT_2, PT_2 <: Table
PT_3 = [v : DOM LIST] @ PT_1 @ PT2
---------------------------------------------------
CTC |- OMapConcatOp[v]{Dep_2}{Indep_1) : PT_3
*)
| POOuterMapConcat v ->
let t1 = access_one_table_type indep_expr_types in
let e2 = access_onesub dep_exprs in
let ctc' = add_input_type ctc t1 in
let t2 = assert_tuple_type(code_typing_expr code_ctxt ctc' e2) in
PT_Table ((v, dom_list_type) :: t1 @ t2)
Need auxilliary judgement for concat(PT ) according to function
Xquery_physical_type_ast_util.concat_xml_type . - Michael
CTC |- Indep_1 : , < : Table
CTC + ( INPUT : ) |- Dep_2 : PT_2 , PT_2 < : XML
-------------------------------------------------
CTC |- MapToItemOp{Dep_2}{Indep_1 ) : concat(PT_2 )
Need auxilliary judgement for concat(PT) according to function
Xquery_physical_type_ast_util.concat_xml_type. - Michael
CTC |- Indep_1 : PT_1, PT_1 <: Table
CTC + (INPUT : PT_1) |- Dep_2 : PT_2, PT_2 <: XML
-------------------------------------------------
CTC |- MapToItemOp{Dep_2}{Indep_1) : concat(PT_2)
*)
| POMapToItem ->
let t1 = access_one_table_type indep_expr_types in
let e2 = access_onesub dep_exprs in
let ctc' = add_input_type ctc t1 in
let t2 = assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' e2) in
A tuple to item map never returns an item list , even if the return
expression evaluates to an item list for each single tuple . -
expression evaluates to an item list for each single tuple. - Michael *)
let t2' = concat_xml_type t2 in
PT_XML(t2')
NB : These rules do not correspond to paper , which compiles
into tuple operators !
Must return item list ! - Michael
CTC |- Indep_1 : , < : XML
PVT = [ v : ' ]
CTC + ( v : ' ) |- Dep_2 : PT_2 , PT_2 < : XML
-----------------------------------------------
CTC |- SomeOp[[PVT]][v]{Dep_2}{Indep_1 ) : PT_2
CTC |- EveryOp[[PVT]][v]{Dep_2}{Indep_1 ) : PT_2
NB: These rules do not correspond to paper, which compiles
into tuple operators!
Must return item list! - Michael
CTC |- Indep_1 : PT_1, PT_1 <: XML
PVT = [v : PT_1']
CTC + (v : PT_1') |- Dep_2 : PT_2, PT_2 <: XML
-----------------------------------------------
CTC |- SomeOp[[PVT]][v]{Dep_2}{Indep_1) : PT_2
CTC |- EveryOp[[PVT]][v]{Dep_2}{Indep_1) : PT_2
*)
| POSome (v, t) ->
let _ = access_one_non_discarded_xml_type indep_expr_types in
let ctc' = add_variable_type ctc v t in
let e2 = access_onesub dep_exprs in
let t2 = assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' e2) in
| POEvery (v, t) ->
let _ = access_one_non_discarded_xml_type indep_expr_types in
let ctc' = add_variable_type ctc v t in
let e2 = access_onesub dep_exprs in
let t2 = assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' e2) in
Need auxilliary judgement for mat(PT ) according to function
Xquery_physical_type_ast_util.materialize_xml_type . - Michael
CTC |- Indep : PT , PT < : Table
CTC + ( INPUT : PT ) |- Dep_1 : , < : XML
...
CTC + ( INPUT : PT ) |- Dep_n : PT_n , PT_n < : XML
----------------------------------------------------------
CTC |- OrderBy[v1, ... ,vn]{Dep_1, ... Dep_n}{Indep } : mat(PT )
Need auxilliary judgement for mat(PT) according to function
Xquery_physical_type_ast_util.materialize_xml_type. - Michael
CTC |- Indep : PT, PT <: Table
CTC + (INPUT : PT) |- Dep_1 : PT_1, PT_1 <: XML
...
CTC + (INPUT : PT) |- Dep_n : PT_n, PT_n <: XML
----------------------------------------------------------
CTC |- OrderBy[v1,...,vn]{Dep_1,...Dep_n}{Indep} : mat(PT)
*)
| POOrderBy ->
let t1 = access_one_table_type indep_expr_types in
The tuple cursor is materialized to an array of DOM values .
let t1' = List.map (fun (n, t) -> (n, materialize_xml_type t)) t1 in
let earray = access_manysub dep_exprs in
let ctc' = add_input_type ctc t1 in
let _ = Array.map (fun ei -> assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' ei)) earray in
PT_Table(t1')
Operators with TWO Table inputs
Need auxilliary judgement for mat(PT ) according to function
Xquery_physical_type_ast_util.materialize_xml_type . - Michael
CTC |- Indep_1 : , < : Table
CTC |- Indep_2 : PT_2 , PT_2 < : Table
PT = PT_1 @ mat(PT_2 )
CTC + ( INPUT : PT ) |- Dep_1 : , < : XML
...
CTC + ( INPUT : PT ) |- Dep_n : PT_n , PT_n < : XML
----------------------------------------------------
CTC |- JoinOp{Dep_1, ... ,Dep_n}(Indep_1,Indep_2 ) : PT
Need auxilliary judgement for mat(PT) according to function
Xquery_physical_type_ast_util.materialize_xml_type. - Michael
CTC |- Indep_1 : PT_1, PT_1 <: Table
CTC |- Indep_2 : PT_2, PT_2 <: Table
PT = PT_1 @ mat(PT_2)
CTC + (INPUT : PT) |- Dep_1 : PT_1, PT_1 <: XML
...
CTC + (INPUT : PT) |- Dep_n : PT_n, PT_n <: XML
----------------------------------------------------
CTC |- JoinOp{Dep_1,...,Dep_n}(Indep_1,Indep_2) : PT
*)
| POJoin_Hash
| POJoin_Sort
| POJoin_NestedLoop ->
let (t1, t2) = access_two_table_types indep_expr_types in
The right side is materialized to an array of DOM values .
let t2' = List.map (fun (n, t) -> (n, materialize_xml_type t)) t2 in
let pt = (t1 @ t2') in
let earray = access_manysub dep_exprs in
let ctc' = add_input_type ctc pt in
let _ = Array.map (fun ei -> assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' ei)) earray in
PT_Table(pt)
CTC |- Indep_1 : , < : Table
CTC |- Indep_2 : PT_2 , PT_2 < : Table
PT = PT_1 @ PT_2
CTC + ( INPUT : PT ) |- Dep_1 : , < : XML
...
CTC + ( INPUT : PT ) |- Dep_n : PT_n , PT_n < : XML
PT ' = [ v : DOM ] @ PT
------------------------------------------------------
CTC |- LeftOuterJoinOp[v]{Dep_1, ... ,Dep_n}(Indep_1,Indep_2 ) : PT '
CTC |- Indep_1 : PT_1, PT_1 <: Table
CTC |- Indep_2 : PT_2, PT_2 <: Table
PT = PT_1 @ PT_2
CTC + (INPUT : PT) |- Dep_1 : PT_1, PT_1 <: XML
...
CTC + (INPUT : PT) |- Dep_n : PT_n, PT_n <: XML
PT' = [v : DOM] @ PT
------------------------------------------------------
CTC |- LeftOuterJoinOp[v]{Dep_1,...,Dep_n}(Indep_1,Indep_2) : PT'
*)
| POLeftOuterJoin_Hash v
| POLeftOuterJoin_Sort v
| POLeftOuterJoin_NestedLoop v
->
let (t1, t2) = access_two_table_types indep_expr_types in
let pt = (t1 @ t2) in
let earray = access_manysub dep_exprs in
let ctc' = add_input_type ctc pt in
let _ = Array.map (fun ei -> assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' ei)) earray in
PT_Table((v, dom_list_type) :: pt)
Grouping and Ordering operations
CTC |- Indep : PT , PT < : Table
CTC + ( INPUT : PT ) |- Dep_1 : , < : XML
...
CTC + ( INPUT : PT ) |- Dep_n : PT_n , PT_n < : XML
PT ' = [ v_1 : DOM; ... : DOM ] @ PT
------------------------------------------------------
CTC |- GroupByOp[v_1, ... ,v_k]{Dep_1, ... ,Dep_n}(Indep ) : PT '
CTC |- Indep : PT, PT <: Table
CTC + (INPUT : PT) |- Dep_1 : PT_1, PT_1 <: XML
...
CTC + (INPUT : PT) |- Dep_n : PT_n, PT_n <: XML
PT' = [v_1 : DOM;...;v_k : DOM] @ PT
------------------------------------------------------
CTC |- GroupByOp[v_1,...,v_k]{Dep_1,...,Dep_n}(Indep) : PT'
*)
| POGroupBy agg_name_list ->
let t1 = access_one_table_type indep_expr_types in
let earray = access_manysub dep_exprs in
let ctc' = add_input_type ctc t1 in
let _ = Array.map (fun ei -> assert_non_discarded_xml_type(code_typing_expr code_ctxt ctc' ei)) earray in
PT_Table((List.map (fun vi -> (vi, dom_list_type)) agg_name_list) @ t1)
| POProject fields ->
let _ = access_nosub dep_exprs in
PT_Table(List.map (fun f -> (f, dom_list_type)) (Array.to_list fields))
@ ( access_one_table_type indep_expr_types ) )
in (pop, indep_expr_types, output_type)
with exn -> (print_string ((Print_xquery_physical_type.string_of_physop_expr_name pop)^" XXXXX\n"); raise exn)
and code_typing_expr_parts code_ctxt ctc algop_expr =
try
let indep_sub_exprs = algop_expr.psub_expression in
let dep_sub_exprs = algop_expr.pdep_sub_expression in
1 . : T1 ... Ik : Tk in environment PEnv
2 . For , and T1 .... Tk pick up the corresponding physical operator POp .
let indep_sub_expr_types = code_typing_sub_exprs code_ctxt ctc indep_sub_exprs in
let pop = select_physical_op ctc code_ctxt algop_expr indep_sub_expr_types in
3 - 6 . Apply type checking for possible additional constraints on the
( type of POp ) , and compute the output physical type T_OUT ) . This
( yields the physical type signature )
(type of POp), and compute the output physical type T_OUT). This
(yields the physical type signature) P_Sig *)
type_check_physical_op code_ctxt ctc pop indep_sub_expr_types dep_sub_exprs
with
| exn -> (raise (error_with_file_location algop_expr.palgop_expr_loc exn))
and code_typing_expr code_ctxt ctc algop_expr =
let phys_sig = code_typing_expr_parts code_ctxt ctc algop_expr in
7 . Annotate the AST with the physical operator and types .
algop_expr.palgop_expr_eval_sig <- (Some phys_sig);
let (phys_op, input_types, output_type) = phys_sig in
output_type
and code_typing_sub_exprs code_ctxt ctc sub_exprs =
match sub_exprs with
| NoSub ->
NoInput
| OneSub op1 ->
OneInput (code_typing_expr code_ctxt ctc op1)
| TwoSub (op1,op2) ->
TwoInput(code_typing_expr code_ctxt ctc op1, code_typing_expr code_ctxt ctc op2)
| ManySub op_array ->
ManyInput (Array.map (code_typing_expr code_ctxt ctc) op_array)
let code_typing_statement code_ctxt astmt =
let code_ctxt' = store_annotation code_ctxt astmt.compile_annotations in
let code_ctxt'' = store_global_annotation code_ctxt' astmt.compile_annotations in
let ctc = (code_type_context_from_code_selection_context code_ctxt) in
ignore(code_typing_expr code_ctxt'' ctc astmt);
ctc
let code_typing_decl code_ctxt ctc var_decl =
match var_decl.alg_decl_name with
| AOEVarDecl (_, cvname) ->
let e1 = access_onesub var_decl.alg_decl_indep in
let _ = access_nosub var_decl.alg_decl_dep in
let code_ctxt' = store_global_annotation code_ctxt e1.compile_annotations in
let output_type = code_typing_expr code_ctxt' ctc e1 in
add_variable_type ctc cvname (assert_non_discarded_xml_type output_type)
| AOEVarDeclExternal (_, cvname)
| AOEVarDeclImported (_, cvname) ->
let _ = access_nosub var_decl.alg_decl_indep in
let _ = access_nosub var_decl.alg_decl_dep in
add_variable_type ctc cvname dom_list_type
| AOEValueIndexDecl str ->
let e1 = access_onesub var_decl.alg_decl_indep in
let e2 = access_onesub var_decl.alg_decl_dep in
let _ = code_typing_expr code_ctxt ctc e1 in
let _ = code_typing_expr code_ctxt ctc e2 in
ctc
| AOENameIndexDecl rsym ->
let _ = access_nosub var_decl.alg_decl_indep in
let _ = access_nosub var_decl.alg_decl_dep in
ctc
let code_typing_function_decl code_ctxt ctc func_decl =
let ((fname, ct), sign, func_defn,_) = func_decl.palgop_function_decl_desc in
let ctc' = Array.fold_left (fun ctc v -> add_variable_type ctc v dom_list_type) ctc func_defn.palgop_func_formal_args in
match !(func_defn.palgop_func_optimized_logical_plan) with
| AOEFunctionImported -> ()
| AOEFunctionUser userbody ->
let code_ctxt' = store_global_annotation code_ctxt userbody.compile_annotations in
ignore(code_typing_expr code_ctxt' ctc' userbody)
Prolog
let code_typing_prolog_aux code_ctxt ctc aprolog =
let ctc' = List.fold_left (code_typing_decl code_ctxt) ctc aprolog.palgop_prolog_vars in
let ctc'' = List.fold_left (code_typing_decl code_ctxt) ctc' aprolog.palgop_prolog_indices in
let _ = List.iter (code_typing_function_decl code_ctxt ctc'') aprolog.palgop_prolog_functions in
ctc''
let code_typing_prolog code_ctxt aprolog =
print_string " In code_typing_prolog\n " ;
let x = Print_xquery_algebra.bprintf_logical_algprolog " > > > > > > > > > > > > > > \n " aprolog
in print_string ( x^"\n<<<<<<<<<<\n\n " ) ;
print_string "In code_typing_prolog\n";
let x = Print_xquery_algebra.bprintf_logical_algprolog ">>>>>>>>>>>>>>\n" aprolog
in print_string (x^"\n<<<<<<<<<<\n\n");
*)
let ctc = (code_type_context_from_code_selection_context code_ctxt) in
code_typing_prolog_aux code_ctxt ctc aprolog
| exn - > ( printf_error_safe " \nIn Cs_code_typing_top.code_typing_prolog " exn ; ctc )
let code_typing_module code_ctxt amodule =
let ctc = (code_type_context_from_code_selection_context code_ctxt) in
let ctc' = code_typing_prolog_aux code_ctxt ctc amodule.palgop_module_prolog in
let _ = List.map (code_typing_expr code_ctxt ctc') amodule.palgop_module_statements in
ctc'
| exn - > ( printf_error_safe " \nIn Cs_code_typing_top.code_typing_module " exn ; ctc )
|
989e15fbf2742216e7a9ab08a6f14bc841de1db200be3e17f961a2fc19b5f227 | metosin/jsonista | tagged_test.clj | (ns jsonista.tagged-test
(:require [clojure.test :refer [deftest is testing]]
[jsonista.core :as j]
[jsonista.tagged :as jt])
(:import (clojure.lang Keyword PersistentHashSet)))
(deftest tagged-value-test
(let [mapper (j/object-mapper {:modules [(jt/module
{:handlers {Keyword {:tag "!kw"
:encode jt/encode-keyword
:decode keyword}
PersistentHashSet {:tag "!set"
:encode jt/encode-collection
:decode set}}})]})
data {:system/status :status/good
:system/statuses #{:status/good :status/bad}}]
(testing "encoding"
(testing "with defaults"
(is (= "{\"system/status\":\"status/good\",\"system/statuses\":[\"status/good\",\"status/bad\"]}"
(j/write-value-as-string data))))
(testing "with installed module"
(is (= "{\"system/status\":[\"!kw\",\"status/good\"],\"system/statuses\":[\"!set\",[[\"!kw\",\"status/good\"],[\"!kw\",\"status/bad\"]]]}"
(j/write-value-as-string data mapper)))))
(testing "decoding"
(testing "with defaults"
(is (= {"system/status" "status/good"
"system/statuses" ["status/good" "status/bad"]}
(j/read-value (j/write-value-as-string data)))))
(testing "with installed module"
(is (= {"system/status" :status/good
"system/statuses" #{:status/good :status/bad}}
(j/read-value (j/write-value-as-string data mapper) mapper)))))
(testing "empty list"
(is (= {"foo" []} (j/read-value (j/write-value-as-string {:foo []} mapper) mapper))))))
| null | https://raw.githubusercontent.com/metosin/jsonista/2a17eeb78ed1d10b037494da41a15a21a1a026d6/test/jsonista/tagged_test.clj | clojure | (ns jsonista.tagged-test
(:require [clojure.test :refer [deftest is testing]]
[jsonista.core :as j]
[jsonista.tagged :as jt])
(:import (clojure.lang Keyword PersistentHashSet)))
(deftest tagged-value-test
(let [mapper (j/object-mapper {:modules [(jt/module
{:handlers {Keyword {:tag "!kw"
:encode jt/encode-keyword
:decode keyword}
PersistentHashSet {:tag "!set"
:encode jt/encode-collection
:decode set}}})]})
data {:system/status :status/good
:system/statuses #{:status/good :status/bad}}]
(testing "encoding"
(testing "with defaults"
(is (= "{\"system/status\":\"status/good\",\"system/statuses\":[\"status/good\",\"status/bad\"]}"
(j/write-value-as-string data))))
(testing "with installed module"
(is (= "{\"system/status\":[\"!kw\",\"status/good\"],\"system/statuses\":[\"!set\",[[\"!kw\",\"status/good\"],[\"!kw\",\"status/bad\"]]]}"
(j/write-value-as-string data mapper)))))
(testing "decoding"
(testing "with defaults"
(is (= {"system/status" "status/good"
"system/statuses" ["status/good" "status/bad"]}
(j/read-value (j/write-value-as-string data)))))
(testing "with installed module"
(is (= {"system/status" :status/good
"system/statuses" #{:status/good :status/bad}}
(j/read-value (j/write-value-as-string data mapper) mapper)))))
(testing "empty list"
(is (= {"foo" []} (j/read-value (j/write-value-as-string {:foo []} mapper) mapper))))))
|
|
cf204b4e39d14b62751a5b420cdc2dafc87078163e385b356a9ccf8c5eab13a9 | binsec/binsec | kernel_options.mli | (**************************************************************************)
This file is part of BINSEC .
(* *)
Copyright ( C ) 2016 - 2022
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
module Logger : Logger.S
(** General command-line options (globals vars) *)
module ExecFile : Cli.STRING_OPT
(** Executable file (or unnamed argument) *)
module Config_file : Cli.STRING_OPT
(** User-provided configuration file *)
module Machine : sig
include Cli.GENERIC with type t := Machine.t
val isa : unit -> Machine.isa
val endianness : unit -> Machine.endianness
val bits : unit -> Machine.bitwidth
val word_size : unit -> int
val stack_register : unit -> string
include Sigs.PRINTABLE with type t := unit
end
module Decoder : Cli.STRING
(** Use external decoder
This is for example needed for arm support.
*)
* { 2 Static disassembly / Analysis }
module Dba_file : Cli.STRING_OPT
module Dba_config : Cli.STRING_OPT
(** DBA start address *)
module Entry_point : Cli.STRING_OPT
module Describe_binary : Cli.BOOLEAN
* { 2 Tests }
module Experimental : Cli.BOOLEAN
(** {b Experimental purposes only} *)
module Version : Cli.BOOLEAN
| null | https://raw.githubusercontent.com/binsec/binsec/8ed9991d36451a3ae7487b966c4b38acca21a5b3/src/kernel/kernel_options.mli | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
* General command-line options (globals vars)
* Executable file (or unnamed argument)
* User-provided configuration file
* Use external decoder
This is for example needed for arm support.
* DBA start address
* {b Experimental purposes only} | This file is part of BINSEC .
Copyright ( C ) 2016 - 2022
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
module Logger : Logger.S
module ExecFile : Cli.STRING_OPT
module Config_file : Cli.STRING_OPT
module Machine : sig
include Cli.GENERIC with type t := Machine.t
val isa : unit -> Machine.isa
val endianness : unit -> Machine.endianness
val bits : unit -> Machine.bitwidth
val word_size : unit -> int
val stack_register : unit -> string
include Sigs.PRINTABLE with type t := unit
end
module Decoder : Cli.STRING
* { 2 Static disassembly / Analysis }
module Dba_file : Cli.STRING_OPT
module Dba_config : Cli.STRING_OPT
module Entry_point : Cli.STRING_OPT
module Describe_binary : Cli.BOOLEAN
* { 2 Tests }
module Experimental : Cli.BOOLEAN
module Version : Cli.BOOLEAN
|
6232284841416accfcd5e9ae97fa6eddc452a4835e63630ebb32684039fb8433 | processone/ejabberd | ejabberd_logger.erl | %%%-------------------------------------------------------------------
%%% File : ejabberd_logger.erl
Author : < >
%%% Purpose : ejabberd logger wrapper
Created : 12 May 2013 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2013 - 2023 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% 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. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%-------------------------------------------------------------------
-module(ejabberd_logger).
-compile({no_auto_import, [get/0]}).
%% API
-export([start/0, get/0, set/1, get_log_path/0, flush/0]).
-export([convert_loglevel/1, loglevels/0, set_modules_fully_logged/1]).
-ifndef(LAGER).
-export([progress_filter/2]).
-endif.
%% Deprecated functions
-export([restart/0, reopen_log/0, rotate_log/0]).
-deprecated([{restart, 0},
{reopen_log, 0},
{rotate_log, 0}]).
-type loglevel() :: none | emergency | alert | critical |
error | warning | notice | info | debug.
-define(is_loglevel(L),
((L == none) or (L == emergency) or (L == alert)
or (L == critical) or (L == error) or (L == warning)
or (L == notice) or (L == info) or (L == debug))).
-export_type([loglevel/0]).
%%%===================================================================
%%% API
%%%===================================================================
-spec get_log_path() -> string().
get_log_path() ->
case ejabberd_config:env_binary_to_list(ejabberd, log_path) of
{ok, Path} ->
Path;
undefined ->
case os:getenv("EJABBERD_LOG_PATH") of
false ->
"ejabberd.log";
Path ->
Path
end
end.
-spec loglevels() -> [loglevel(), ...].
loglevels() ->
[none, emergency, alert, critical, error, warning, notice, info, debug].
-spec convert_loglevel(0..5) -> loglevel().
convert_loglevel(0) -> none;
convert_loglevel(1) -> critical;
convert_loglevel(2) -> error;
convert_loglevel(3) -> warning;
convert_loglevel(4) -> info;
convert_loglevel(5) -> debug.
quiet_mode() ->
case application:get_env(ejabberd, quiet) of
{ok, true} -> true;
_ -> false
end.
-spec get_integer_env(atom(), T) -> T.
get_integer_env(Name, Default) ->
case application:get_env(ejabberd, Name) of
{ok, I} when is_integer(I), I>=0 ->
I;
{ok, infinity} ->
infinity;
undefined ->
Default;
{ok, Junk} ->
error_logger:error_msg("wrong value for ~ts: ~p; "
"using ~p as a fallback~n",
[Name, Junk, Default]),
Default
end.
-ifdef(LAGER).
-spec get_string_env(atom(), T) -> T.
get_string_env(Name, Default) ->
case application:get_env(ejabberd, Name) of
{ok, L} when is_list(L) ->
L;
undefined ->
Default;
{ok, Junk} ->
error_logger:error_msg("wrong value for ~ts: ~p; "
"using ~p as a fallback~n",
[Name, Junk, Default]),
Default
end.
start() ->
start(info).
start(Level) ->
StartedApps = application:which_applications(5000),
case lists:keyfind(logger, 1, StartedApps) of
%% Elixir logger is started. We assume everything is in place
%% to use lager to Elixir logger bridge.
{logger, _, _} ->
error_logger:info_msg("Ignoring ejabberd logger options, using Elixir Logger.", []),
Do not start lager , we rely on
do_start_for_logger(Level);
_ ->
do_start(Level)
end.
do_start_for_logger(Level) ->
application:load(sasl),
application:set_env(sasl, sasl_error_logger, false),
application:load(lager),
application:set_env(lager, error_logger_redirect, false),
application:set_env(lager, error_logger_whitelist, ['Elixir.Logger.ErrorHandler']),
application:set_env(lager, crash_log, false),
application:set_env(lager, handlers, [{elixir_logger_backend, [{level, Level}]}]),
ejabberd:start_app(lager),
ok.
do_start(Level) ->
application:load(sasl),
application:set_env(sasl, sasl_error_logger, false),
application:load(lager),
ConsoleLog = get_log_path(),
Dir = filename:dirname(ConsoleLog),
ErrorLog = filename:join([Dir, "error.log"]),
CrashLog = filename:join([Dir, "crash.log"]),
LogRotateDate = get_string_env(log_rotate_date, ""),
LogRotateSize = case get_integer_env(log_rotate_size, 10*1024*1024) of
infinity -> 0;
V -> V
end,
LogRotateCount = get_integer_env(log_rotate_count, 1),
LogRateLimit = get_integer_env(log_rate_limit, 100),
ConsoleLevel0 = case quiet_mode() of
true -> critical;
_ -> Level
end,
ConsoleLevel = case get_lager_version() >= "3.6.0" of
true -> [{level, ConsoleLevel0}];
false -> ConsoleLevel0
end,
application:set_env(lager, error_logger_hwm, LogRateLimit),
application:set_env(
lager, handlers,
[{lager_console_backend, ConsoleLevel},
{lager_file_backend, [{file, ConsoleLog}, {level, Level}, {date, LogRotateDate},
{count, LogRotateCount}, {size, LogRotateSize}]},
{lager_file_backend, [{file, ErrorLog}, {level, error}, {date, LogRotateDate},
{count, LogRotateCount}, {size, LogRotateSize}]}]),
application:set_env(lager, crash_log, CrashLog),
application:set_env(lager, crash_log_date, LogRotateDate),
application:set_env(lager, crash_log_size, LogRotateSize),
application:set_env(lager, crash_log_count, LogRotateCount),
ejabberd:start_app(lager),
lists:foreach(fun(Handler) ->
lager:set_loghwm(Handler, LogRateLimit)
end, gen_event:which_handlers(lager_event)).
restart() ->
Level = ejabberd_option:loglevel(),
application:stop(lager),
start(Level).
reopen_log() ->
ok.
rotate_log() ->
catch lager_crash_log ! rotate,
lists:foreach(
fun({lager_file_backend, File}) ->
whereis(lager_event) ! {rotate, File};
(_) ->
ok
end, gen_event:which_handlers(lager_event)).
get() ->
Handlers = get_lager_handlers(),
lists:foldl(fun(lager_console_backend, _Acc) ->
lager:get_loglevel(lager_console_backend);
(elixir_logger_backend, _Acc) ->
lager:get_loglevel(elixir_logger_backend);
(_, Acc) ->
Acc
end,
none, Handlers).
set(N) when is_integer(N), N>=0, N=<5 ->
set(convert_loglevel(N));
set(Level) when ?is_loglevel(Level) ->
case get() of
Level ->
ok;
_ ->
ConsoleLog = get_log_path(),
QuietMode = quiet_mode(),
lists:foreach(
fun({lager_file_backend, File} = H) when File == ConsoleLog ->
lager:set_loglevel(H, Level);
(lager_console_backend = H) when not QuietMode ->
lager:set_loglevel(H, Level);
(elixir_logger_backend = H) ->
lager:set_loglevel(H, Level);
(_) ->
ok
end, get_lager_handlers())
end,
case Level of
debug -> xmpp:set_config([{debug, true}]);
_ -> xmpp:set_config([{debug, false}])
end.
get_lager_handlers() ->
case catch gen_event:which_handlers(lager_event) of
{'EXIT',noproc} ->
[];
Result ->
Result
end.
-spec get_lager_version() -> string().
get_lager_version() ->
Apps = application:loaded_applications(),
case lists:keyfind(lager, 1, Apps) of
{_, _, Vsn} -> Vsn;
false -> "0.0.0"
end.
set_modules_fully_logged(_) -> ok.
flush() ->
application:stop(lager),
application:stop(sasl).
-else.
-include_lib("kernel/include/logger.hrl").
-spec start() -> ok | {error, term()}.
start() ->
start(info).
start(Level) ->
EjabberdLog = get_log_path(),
Dir = filename:dirname(EjabberdLog),
ErrorLog = filename:join([Dir, "error.log"]),
LogRotateSize = get_integer_env(log_rotate_size, 10*1024*1024),
LogRotateCount = get_integer_env(log_rotate_count, 1),
LogBurstLimitWindowTime = get_integer_env(log_burst_limit_window_time, 1000),
LogBurstLimitCount = get_integer_env(log_burst_limit_count, 500),
Config = #{max_no_bytes => LogRotateSize,
max_no_files => LogRotateCount,
filesync_repeat_interval => no_repeat,
file_check => 1000,
sync_mode_qlen => 1000,
drop_mode_qlen => 1000,
flush_qlen => 5000,
burst_limit_window_time => LogBurstLimitWindowTime,
burst_limit_max_count => LogBurstLimitCount},
FmtConfig = #{legacy_header => false,
time_designator => $ ,
max_size => 100*1024,
single_line => false},
FileFmtConfig = FmtConfig#{template => file_template()},
ConsoleFmtConfig = FmtConfig#{template => console_template()},
try
ok = logger:set_primary_config(level, Level),
DefaultHandlerId = get_default_handlerid(),
ok = logger:update_formatter_config(DefaultHandlerId, ConsoleFmtConfig),
case quiet_mode() of
true ->
ok = logger:set_handler_config(DefaultHandlerId, level, critical);
_ ->
ok
end,
case logger:add_primary_filter(progress_report,
{fun ?MODULE:progress_filter/2, stop}) of
ok -> ok;
{error, {already_exist, _}} -> ok
end,
case logger:add_handler(ejabberd_log, logger_std_h,
#{level => all,
config => Config#{file => EjabberdLog},
formatter => {logger_formatter, FileFmtConfig}}) of
ok -> ok;
{error, {already_exist, _}} -> ok
end,
case logger:add_handler(error_log, logger_std_h,
#{level => error,
config => Config#{file => ErrorLog},
formatter => {logger_formatter, FileFmtConfig}}) of
ok -> ok;
{error, {already_exist, _}} -> ok
end
catch _:{Tag, Err} when Tag == badmatch; Tag == case_clause ->
?LOG_CRITICAL("Failed to set logging: ~p", [Err]),
Err
end.
get_default_handlerid() ->
Ids = logger:get_handler_ids(),
case lists:member(default, Ids) of
true -> default;
false -> hd(Ids)
end.
-spec restart() -> ok.
restart() ->
ok.
progress_filter(#{level:=info,msg:={report,#{label:={_,progress}}}} = Event, _) ->
case get() of
debug ->
logger_filters:progress(Event#{level => debug}, log);
_ ->
stop
end;
progress_filter(Event, _) ->
Event.
console_template() ->
[time, " [", level, "] " | msg()].
file_template() ->
[time, " [", level, "] ", pid,
{mfa, ["@", mfa, {line, [":", line], []}], []}, " " | msg()].
msg() ->
[{logger_formatter, [[logger_formatter, title], ":", io_lib:nl()], []},
msg, io_lib:nl()].
-spec reopen_log() -> ok.
reopen_log() ->
ok.
-spec rotate_log() -> ok.
rotate_log() ->
ok.
-spec get() -> loglevel().
get() ->
#{level := Level} = logger:get_primary_config(),
Level.
-spec set(0..5 | loglevel()) -> ok.
set(N) when is_integer(N), N>=0, N=<5 ->
set(convert_loglevel(N));
set(Level) when ?is_loglevel(Level) ->
case get() of
Level -> ok;
PrevLevel ->
?LOG_NOTICE("Changing loglevel from '~s' to '~s'",
[PrevLevel, Level]),
logger:set_primary_config(level, Level),
case Level of
debug -> xmpp:set_config([{debug, true}]);
_ -> xmpp:set_config([{debug, false}])
end
end.
set_modules_fully_logged(Modules) ->
logger:unset_module_level(),
logger:set_module_level(Modules, all).
-spec flush() -> ok.
flush() ->
lists:foreach(
fun(#{id := HandlerId, module := logger_std_h}) ->
logger_std_h:filesync(HandlerId);
(#{id := HandlerId, module := logger_disk_log_h}) ->
logger_disk_log_h:filesync(HandlerId);
(_) ->
ok
end, logger:get_handler_config()).
-endif.
| null | https://raw.githubusercontent.com/processone/ejabberd/c103182bc7e5b8a8ab123ce02d1959a54e939480/src/ejabberd_logger.erl | erlang | -------------------------------------------------------------------
File : ejabberd_logger.erl
Purpose : ejabberd logger wrapper
This program is free software; you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
-------------------------------------------------------------------
API
Deprecated functions
===================================================================
API
===================================================================
Elixir logger is started. We assume everything is in place
to use lager to Elixir logger bridge. | Author : < >
Created : 12 May 2013 by < >
ejabberd , Copyright ( C ) 2013 - 2023 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
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. ,
51 Franklin Street , Fifth Floor , Boston , USA .
-module(ejabberd_logger).
-compile({no_auto_import, [get/0]}).
-export([start/0, get/0, set/1, get_log_path/0, flush/0]).
-export([convert_loglevel/1, loglevels/0, set_modules_fully_logged/1]).
-ifndef(LAGER).
-export([progress_filter/2]).
-endif.
-export([restart/0, reopen_log/0, rotate_log/0]).
-deprecated([{restart, 0},
{reopen_log, 0},
{rotate_log, 0}]).
-type loglevel() :: none | emergency | alert | critical |
error | warning | notice | info | debug.
-define(is_loglevel(L),
((L == none) or (L == emergency) or (L == alert)
or (L == critical) or (L == error) or (L == warning)
or (L == notice) or (L == info) or (L == debug))).
-export_type([loglevel/0]).
-spec get_log_path() -> string().
get_log_path() ->
case ejabberd_config:env_binary_to_list(ejabberd, log_path) of
{ok, Path} ->
Path;
undefined ->
case os:getenv("EJABBERD_LOG_PATH") of
false ->
"ejabberd.log";
Path ->
Path
end
end.
-spec loglevels() -> [loglevel(), ...].
loglevels() ->
[none, emergency, alert, critical, error, warning, notice, info, debug].
-spec convert_loglevel(0..5) -> loglevel().
convert_loglevel(0) -> none;
convert_loglevel(1) -> critical;
convert_loglevel(2) -> error;
convert_loglevel(3) -> warning;
convert_loglevel(4) -> info;
convert_loglevel(5) -> debug.
quiet_mode() ->
case application:get_env(ejabberd, quiet) of
{ok, true} -> true;
_ -> false
end.
-spec get_integer_env(atom(), T) -> T.
get_integer_env(Name, Default) ->
case application:get_env(ejabberd, Name) of
{ok, I} when is_integer(I), I>=0 ->
I;
{ok, infinity} ->
infinity;
undefined ->
Default;
{ok, Junk} ->
error_logger:error_msg("wrong value for ~ts: ~p; "
"using ~p as a fallback~n",
[Name, Junk, Default]),
Default
end.
-ifdef(LAGER).
-spec get_string_env(atom(), T) -> T.
get_string_env(Name, Default) ->
case application:get_env(ejabberd, Name) of
{ok, L} when is_list(L) ->
L;
undefined ->
Default;
{ok, Junk} ->
error_logger:error_msg("wrong value for ~ts: ~p; "
"using ~p as a fallback~n",
[Name, Junk, Default]),
Default
end.
start() ->
start(info).
start(Level) ->
StartedApps = application:which_applications(5000),
case lists:keyfind(logger, 1, StartedApps) of
{logger, _, _} ->
error_logger:info_msg("Ignoring ejabberd logger options, using Elixir Logger.", []),
Do not start lager , we rely on
do_start_for_logger(Level);
_ ->
do_start(Level)
end.
do_start_for_logger(Level) ->
application:load(sasl),
application:set_env(sasl, sasl_error_logger, false),
application:load(lager),
application:set_env(lager, error_logger_redirect, false),
application:set_env(lager, error_logger_whitelist, ['Elixir.Logger.ErrorHandler']),
application:set_env(lager, crash_log, false),
application:set_env(lager, handlers, [{elixir_logger_backend, [{level, Level}]}]),
ejabberd:start_app(lager),
ok.
do_start(Level) ->
application:load(sasl),
application:set_env(sasl, sasl_error_logger, false),
application:load(lager),
ConsoleLog = get_log_path(),
Dir = filename:dirname(ConsoleLog),
ErrorLog = filename:join([Dir, "error.log"]),
CrashLog = filename:join([Dir, "crash.log"]),
LogRotateDate = get_string_env(log_rotate_date, ""),
LogRotateSize = case get_integer_env(log_rotate_size, 10*1024*1024) of
infinity -> 0;
V -> V
end,
LogRotateCount = get_integer_env(log_rotate_count, 1),
LogRateLimit = get_integer_env(log_rate_limit, 100),
ConsoleLevel0 = case quiet_mode() of
true -> critical;
_ -> Level
end,
ConsoleLevel = case get_lager_version() >= "3.6.0" of
true -> [{level, ConsoleLevel0}];
false -> ConsoleLevel0
end,
application:set_env(lager, error_logger_hwm, LogRateLimit),
application:set_env(
lager, handlers,
[{lager_console_backend, ConsoleLevel},
{lager_file_backend, [{file, ConsoleLog}, {level, Level}, {date, LogRotateDate},
{count, LogRotateCount}, {size, LogRotateSize}]},
{lager_file_backend, [{file, ErrorLog}, {level, error}, {date, LogRotateDate},
{count, LogRotateCount}, {size, LogRotateSize}]}]),
application:set_env(lager, crash_log, CrashLog),
application:set_env(lager, crash_log_date, LogRotateDate),
application:set_env(lager, crash_log_size, LogRotateSize),
application:set_env(lager, crash_log_count, LogRotateCount),
ejabberd:start_app(lager),
lists:foreach(fun(Handler) ->
lager:set_loghwm(Handler, LogRateLimit)
end, gen_event:which_handlers(lager_event)).
restart() ->
Level = ejabberd_option:loglevel(),
application:stop(lager),
start(Level).
reopen_log() ->
ok.
rotate_log() ->
catch lager_crash_log ! rotate,
lists:foreach(
fun({lager_file_backend, File}) ->
whereis(lager_event) ! {rotate, File};
(_) ->
ok
end, gen_event:which_handlers(lager_event)).
get() ->
Handlers = get_lager_handlers(),
lists:foldl(fun(lager_console_backend, _Acc) ->
lager:get_loglevel(lager_console_backend);
(elixir_logger_backend, _Acc) ->
lager:get_loglevel(elixir_logger_backend);
(_, Acc) ->
Acc
end,
none, Handlers).
set(N) when is_integer(N), N>=0, N=<5 ->
set(convert_loglevel(N));
set(Level) when ?is_loglevel(Level) ->
case get() of
Level ->
ok;
_ ->
ConsoleLog = get_log_path(),
QuietMode = quiet_mode(),
lists:foreach(
fun({lager_file_backend, File} = H) when File == ConsoleLog ->
lager:set_loglevel(H, Level);
(lager_console_backend = H) when not QuietMode ->
lager:set_loglevel(H, Level);
(elixir_logger_backend = H) ->
lager:set_loglevel(H, Level);
(_) ->
ok
end, get_lager_handlers())
end,
case Level of
debug -> xmpp:set_config([{debug, true}]);
_ -> xmpp:set_config([{debug, false}])
end.
get_lager_handlers() ->
case catch gen_event:which_handlers(lager_event) of
{'EXIT',noproc} ->
[];
Result ->
Result
end.
-spec get_lager_version() -> string().
get_lager_version() ->
Apps = application:loaded_applications(),
case lists:keyfind(lager, 1, Apps) of
{_, _, Vsn} -> Vsn;
false -> "0.0.0"
end.
set_modules_fully_logged(_) -> ok.
flush() ->
application:stop(lager),
application:stop(sasl).
-else.
-include_lib("kernel/include/logger.hrl").
-spec start() -> ok | {error, term()}.
start() ->
start(info).
start(Level) ->
EjabberdLog = get_log_path(),
Dir = filename:dirname(EjabberdLog),
ErrorLog = filename:join([Dir, "error.log"]),
LogRotateSize = get_integer_env(log_rotate_size, 10*1024*1024),
LogRotateCount = get_integer_env(log_rotate_count, 1),
LogBurstLimitWindowTime = get_integer_env(log_burst_limit_window_time, 1000),
LogBurstLimitCount = get_integer_env(log_burst_limit_count, 500),
Config = #{max_no_bytes => LogRotateSize,
max_no_files => LogRotateCount,
filesync_repeat_interval => no_repeat,
file_check => 1000,
sync_mode_qlen => 1000,
drop_mode_qlen => 1000,
flush_qlen => 5000,
burst_limit_window_time => LogBurstLimitWindowTime,
burst_limit_max_count => LogBurstLimitCount},
FmtConfig = #{legacy_header => false,
time_designator => $ ,
max_size => 100*1024,
single_line => false},
FileFmtConfig = FmtConfig#{template => file_template()},
ConsoleFmtConfig = FmtConfig#{template => console_template()},
try
ok = logger:set_primary_config(level, Level),
DefaultHandlerId = get_default_handlerid(),
ok = logger:update_formatter_config(DefaultHandlerId, ConsoleFmtConfig),
case quiet_mode() of
true ->
ok = logger:set_handler_config(DefaultHandlerId, level, critical);
_ ->
ok
end,
case logger:add_primary_filter(progress_report,
{fun ?MODULE:progress_filter/2, stop}) of
ok -> ok;
{error, {already_exist, _}} -> ok
end,
case logger:add_handler(ejabberd_log, logger_std_h,
#{level => all,
config => Config#{file => EjabberdLog},
formatter => {logger_formatter, FileFmtConfig}}) of
ok -> ok;
{error, {already_exist, _}} -> ok
end,
case logger:add_handler(error_log, logger_std_h,
#{level => error,
config => Config#{file => ErrorLog},
formatter => {logger_formatter, FileFmtConfig}}) of
ok -> ok;
{error, {already_exist, _}} -> ok
end
catch _:{Tag, Err} when Tag == badmatch; Tag == case_clause ->
?LOG_CRITICAL("Failed to set logging: ~p", [Err]),
Err
end.
get_default_handlerid() ->
Ids = logger:get_handler_ids(),
case lists:member(default, Ids) of
true -> default;
false -> hd(Ids)
end.
-spec restart() -> ok.
restart() ->
ok.
progress_filter(#{level:=info,msg:={report,#{label:={_,progress}}}} = Event, _) ->
case get() of
debug ->
logger_filters:progress(Event#{level => debug}, log);
_ ->
stop
end;
progress_filter(Event, _) ->
Event.
console_template() ->
[time, " [", level, "] " | msg()].
file_template() ->
[time, " [", level, "] ", pid,
{mfa, ["@", mfa, {line, [":", line], []}], []}, " " | msg()].
msg() ->
[{logger_formatter, [[logger_formatter, title], ":", io_lib:nl()], []},
msg, io_lib:nl()].
-spec reopen_log() -> ok.
reopen_log() ->
ok.
-spec rotate_log() -> ok.
rotate_log() ->
ok.
-spec get() -> loglevel().
get() ->
#{level := Level} = logger:get_primary_config(),
Level.
-spec set(0..5 | loglevel()) -> ok.
set(N) when is_integer(N), N>=0, N=<5 ->
set(convert_loglevel(N));
set(Level) when ?is_loglevel(Level) ->
case get() of
Level -> ok;
PrevLevel ->
?LOG_NOTICE("Changing loglevel from '~s' to '~s'",
[PrevLevel, Level]),
logger:set_primary_config(level, Level),
case Level of
debug -> xmpp:set_config([{debug, true}]);
_ -> xmpp:set_config([{debug, false}])
end
end.
set_modules_fully_logged(Modules) ->
logger:unset_module_level(),
logger:set_module_level(Modules, all).
-spec flush() -> ok.
flush() ->
lists:foreach(
fun(#{id := HandlerId, module := logger_std_h}) ->
logger_std_h:filesync(HandlerId);
(#{id := HandlerId, module := logger_disk_log_h}) ->
logger_disk_log_h:filesync(HandlerId);
(_) ->
ok
end, logger:get_handler_config()).
-endif.
|
952c39067382e06e0d5abfe9c38c73a59b2418047c4454a12ad315670b91b5e0 | rizo/snowflake-os | liveness.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ Id$
Liveness analysis .
Annotate mach code with the set of regs live at each point .
Annotate mach code with the set of regs live at each point. *)
open Mach
let live_at_exit = ref []
let find_live_at_exit k =
try
List.assoc k !live_at_exit
with
| Not_found -> Misc.fatal_error "Spill.find_live_at_exit"
let live_at_break = ref Reg.Set.empty
let live_at_raise = ref Reg.Set.empty
let rec live i finally =
(* finally is the set of registers live after execution of the
instruction sequence.
The result of the function is the set of registers live just
before the instruction sequence.
The instruction i is annotated by the set of registers live across
the instruction. *)
match i.desc with
Iend ->
i.live <- finally;
finally
| Ireturn | Iop(Itailcall_ind) | Iop(Itailcall_imm _) ->
(* i.live remains empty since no regs are live across *)
Reg.set_of_array i.arg
| Iifthenelse(test, ifso, ifnot) ->
let at_join = live i.next finally in
let at_fork = Reg.Set.union (live ifso at_join) (live ifnot at_join) in
i.live <- at_fork;
Reg.add_set_array at_fork i.arg
| Iswitch(index, cases) ->
let at_join = live i.next finally in
let at_fork = ref Reg.Set.empty in
for i = 0 to Array.length cases - 1 do
at_fork := Reg.Set.union !at_fork (live cases.(i) at_join)
done;
i.live <- !at_fork;
Reg.add_set_array !at_fork i.arg
| Iloop(body) ->
let at_top = ref Reg.Set.empty in
(* Yes, there are better algorithms, but we'll just iterate till
reaching a fixpoint. *)
begin try
while true do
let new_at_top = Reg.Set.union !at_top (live body !at_top) in
if Reg.Set.equal !at_top new_at_top then raise Exit;
at_top := new_at_top
done
with Exit -> ()
end;
i.live <- !at_top;
!at_top
| Icatch(nfail, body, handler) ->
let at_join = live i.next finally in
let before_handler = live handler at_join in
let before_body =
live_at_exit := (nfail,before_handler) :: !live_at_exit ;
let before_body = live body at_join in
live_at_exit := List.tl !live_at_exit ;
before_body in
i.live <- before_body;
before_body
| Iexit nfail ->
let this_live = find_live_at_exit nfail in
i.live <- this_live ;
this_live
| Itrywith(body, handler) ->
let at_join = live i.next finally in
let before_handler = live handler at_join in
let saved_live_at_raise = !live_at_raise in
live_at_raise := Reg.Set.remove Proc.loc_exn_bucket before_handler;
let before_body = live body at_join in
live_at_raise := saved_live_at_raise;
i.live <- before_body;
before_body
| Iraise ->
(* i.live remains empty since no regs are live across *)
Reg.add_set_array !live_at_raise i.arg
| _ ->
let across_after = Reg.diff_set_array (live i.next finally) i.res in
let across =
match i.desc with
Iop Icall_ind | Iop(Icall_imm _) | Iop(Iextcall _)
| Iop(Iintop Icheckbound) | Iop(Iintop_imm(Icheckbound, _)) ->
The function call may raise an exception , branching to the
nearest enclosing try ... with . Similarly for bounds checks .
Hence , everything that must be live at the beginning of
the exception handler must also be live across this instr .
nearest enclosing try ... with. Similarly for bounds checks.
Hence, everything that must be live at the beginning of
the exception handler must also be live across this instr. *)
Reg.Set.union across_after !live_at_raise
| _ ->
across_after in
i.live <- across;
Reg.add_set_array across i.arg
let fundecl ppf f =
let initially_live = live f.fun_body Reg.Set.empty in
(* Sanity check: only function parameters can be live at entrypoint *)
let wrong_live = Reg.Set.diff initially_live (Reg.set_of_array f.fun_args) in
if not (Reg.Set.is_empty wrong_live) then begin
Format.fprintf ppf "%a@." Printmach.regset wrong_live;
Misc.fatal_error "Liveness.fundecl"
end
| null | https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/plugins/ocamlopt.opt/asmcomp/liveness.ml | ocaml | *********************************************************************
Objective Caml
*********************************************************************
finally is the set of registers live after execution of the
instruction sequence.
The result of the function is the set of registers live just
before the instruction sequence.
The instruction i is annotated by the set of registers live across
the instruction.
i.live remains empty since no regs are live across
Yes, there are better algorithms, but we'll just iterate till
reaching a fixpoint.
i.live remains empty since no regs are live across
Sanity check: only function parameters can be live at entrypoint | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ Id$
Liveness analysis .
Annotate mach code with the set of regs live at each point .
Annotate mach code with the set of regs live at each point. *)
open Mach
let live_at_exit = ref []
let find_live_at_exit k =
try
List.assoc k !live_at_exit
with
| Not_found -> Misc.fatal_error "Spill.find_live_at_exit"
let live_at_break = ref Reg.Set.empty
let live_at_raise = ref Reg.Set.empty
let rec live i finally =
match i.desc with
Iend ->
i.live <- finally;
finally
| Ireturn | Iop(Itailcall_ind) | Iop(Itailcall_imm _) ->
Reg.set_of_array i.arg
| Iifthenelse(test, ifso, ifnot) ->
let at_join = live i.next finally in
let at_fork = Reg.Set.union (live ifso at_join) (live ifnot at_join) in
i.live <- at_fork;
Reg.add_set_array at_fork i.arg
| Iswitch(index, cases) ->
let at_join = live i.next finally in
let at_fork = ref Reg.Set.empty in
for i = 0 to Array.length cases - 1 do
at_fork := Reg.Set.union !at_fork (live cases.(i) at_join)
done;
i.live <- !at_fork;
Reg.add_set_array !at_fork i.arg
| Iloop(body) ->
let at_top = ref Reg.Set.empty in
begin try
while true do
let new_at_top = Reg.Set.union !at_top (live body !at_top) in
if Reg.Set.equal !at_top new_at_top then raise Exit;
at_top := new_at_top
done
with Exit -> ()
end;
i.live <- !at_top;
!at_top
| Icatch(nfail, body, handler) ->
let at_join = live i.next finally in
let before_handler = live handler at_join in
let before_body =
live_at_exit := (nfail,before_handler) :: !live_at_exit ;
let before_body = live body at_join in
live_at_exit := List.tl !live_at_exit ;
before_body in
i.live <- before_body;
before_body
| Iexit nfail ->
let this_live = find_live_at_exit nfail in
i.live <- this_live ;
this_live
| Itrywith(body, handler) ->
let at_join = live i.next finally in
let before_handler = live handler at_join in
let saved_live_at_raise = !live_at_raise in
live_at_raise := Reg.Set.remove Proc.loc_exn_bucket before_handler;
let before_body = live body at_join in
live_at_raise := saved_live_at_raise;
i.live <- before_body;
before_body
| Iraise ->
Reg.add_set_array !live_at_raise i.arg
| _ ->
let across_after = Reg.diff_set_array (live i.next finally) i.res in
let across =
match i.desc with
Iop Icall_ind | Iop(Icall_imm _) | Iop(Iextcall _)
| Iop(Iintop Icheckbound) | Iop(Iintop_imm(Icheckbound, _)) ->
The function call may raise an exception , branching to the
nearest enclosing try ... with . Similarly for bounds checks .
Hence , everything that must be live at the beginning of
the exception handler must also be live across this instr .
nearest enclosing try ... with. Similarly for bounds checks.
Hence, everything that must be live at the beginning of
the exception handler must also be live across this instr. *)
Reg.Set.union across_after !live_at_raise
| _ ->
across_after in
i.live <- across;
Reg.add_set_array across i.arg
let fundecl ppf f =
let initially_live = live f.fun_body Reg.Set.empty in
let wrong_live = Reg.Set.diff initially_live (Reg.set_of_array f.fun_args) in
if not (Reg.Set.is_empty wrong_live) then begin
Format.fprintf ppf "%a@." Printmach.regset wrong_live;
Misc.fatal_error "Liveness.fundecl"
end
|
0500d4ea267c6e9703ac88859ffe96017c93369d7fe4e68296a021080bbeca29 | Clozure/ccl | constants.lisp | ;;;
;;; Copyright 2016 Clozure Associates
;;;
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
;;;
;;; -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.
(in-package "GUI")
;;; action menu item tags
(defconstant $inspect-item-tag 0)
(defconstant $source-item-tag 1)
| null | https://raw.githubusercontent.com/Clozure/ccl/6c1a9458f7a5437b73ec227e989aa5b825f32fd3/cocoa-ide/constants.lisp | lisp |
Copyright 2016 Clozure Associates
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
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.
action menu item tags | distributed under the License is distributed on an " AS IS " BASIS ,
(in-package "GUI")
(defconstant $inspect-item-tag 0)
(defconstant $source-item-tag 1)
|
079c3998a3e5e155234b8c2638344367d91677ad3a23f2d71f7fb90e4f8fede5 | erlang/rebar3 | rebar_state.erl | -module(rebar_state).
-export([new/0, new/1, new/2, new/3,
get/2, get/3, set/3,
format_error/1,
has_all_artifacts/1,
code_paths/2, code_paths/3, update_code_paths/3,
opts/1, opts/2,
default/1, default/2,
escript_path/1, escript_path/2,
lock/1, lock/2,
current_profiles/1, current_profiles/2,
command_args/1, command_args/2,
command_parsed_args/1, command_parsed_args/2,
add_to_profile/3, apply_profiles/2,
dir/1, dir/2,
create_logic_providers/2,
current_app/1, current_app/2,
project_apps/1, project_apps/2,
deps_to_build/1, deps_to_build/2,
all_plugin_deps/1, all_plugin_deps/2, update_all_plugin_deps/2,
all_deps/1, all_deps/2, update_all_deps/2, merge_all_deps/2,
all_checkout_deps/1,
namespace/1, namespace/2,
default_hex_repo_url_override/1,
deps_names/1,
to_list/1,
compilers/1, compilers/2,
prepend_compilers/2, append_compilers/2,
project_builders/1, add_project_builder/3,
create_resources/2, set_resources/2,
resources/1, resources/2, add_resource/2,
providers/1, providers/2, add_provider/2,
allow_provider_overrides/1, allow_provider_overrides/2
]).
-include("rebar.hrl").
-include_lib("providers/include/providers.hrl").
-record(state_t, {dir :: file:name(),
opts = dict:new() :: rebar_dict(),
code_paths = dict:new() :: rebar_dict(),
default = dict:new() :: rebar_dict(),
escript_path :: undefined | file:filename_all(),
lock = [],
current_profiles = [default] :: [atom()],
namespace = default :: atom(),
command_args = [],
command_parsed_args = {[], []},
current_app :: undefined | rebar_app_info:t(),
project_apps = [] :: [rebar_app_info:t()],
deps_to_build = [] :: [rebar_app_info:t()],
all_plugin_deps = [] :: [rebar_app_info:t()],
all_deps = [] :: [rebar_app_info:t()],
compilers = [] :: [module()],
project_builders = [] :: [{rebar_app_info:project_type(), module()}],
resources = [],
providers = [],
allow_provider_overrides = false :: boolean()}).
-export_type([t/0]).
-type t() :: #state_t{}.
-spec new() -> t().
new() ->
BaseState = base_state(dict:new()),
BaseState#state_t{dir = rebar_dir:get_cwd()}.
-spec new(list()) -> t().
new(Config) when is_list(Config) ->
Opts = base_opts(Config),
BaseState = base_state(Opts),
BaseState#state_t{dir=rebar_dir:get_cwd(),
default=Opts}.
-spec new(t() | atom(), list()) -> t().
new(Profile, Config) when is_atom(Profile)
, is_list(Config) ->
Opts = base_opts(Config),
BaseState = base_state(Opts),
BaseState#state_t{dir = rebar_dir:get_cwd(),
current_profiles = [Profile],
default = Opts};
new(ParentState=#state_t{}, Config) ->
%% Load terms from rebar.config, if it exists
Dir = rebar_dir:get_cwd(),
new(ParentState, Config, Dir).
-spec new(t(), list(), file:filename_all()) -> t().
new(ParentState, Config, Dir) ->
new(ParentState, Config, deps_from_config(Dir, Config), Dir).
new(ParentState, Config, Deps, Dir) ->
Opts = ParentState#state_t.opts,
Plugins = proplists:get_value(plugins, Config, []),
ProjectPlugins = proplists:get_value(project_plugins, Config, []),
Terms = Deps++[{{project_plugins, default}, ProjectPlugins}, {{plugins, default}, Plugins} | Config],
true = rebar_config:verify_config_format(Terms),
LocalOpts = dict:from_list(Terms),
NewOpts = rebar_opts:merge_opts(LocalOpts, Opts),
ParentState#state_t{dir=Dir
,opts=NewOpts
,default=NewOpts}.
deps_from_config(Dir, Config) ->
case rebar_config:consult_lock_file(filename:join(Dir, ?LOCK_FILE)) of
[] ->
[{{deps, default}, proplists:get_value(deps, Config, [])}];
D ->
We want the top level only from the lock file .
%% This ensures deterministic overrides for configs.
Deps = [X || X <- D, element(3, X) =:= 0],
[{{locks, default}, D}, {{deps, default}, Deps}]
end.
base_state(Opts) ->
#state_t{opts=Opts}.
base_opts(Config) ->
Deps = proplists:get_value(deps, Config, []),
Plugins = proplists:get_value(plugins, Config, []),
ProjectPlugins = proplists:get_value(project_plugins, Config, []),
Terms = [{{deps, default}, Deps}, {{plugins, default}, Plugins},
{{project_plugins, default}, ProjectPlugins} | Config],
true = rebar_config:verify_config_format(Terms),
dict:from_list(Terms).
get(State, Key) ->
{ok, Value} = dict:find(Key, State#state_t.opts),
Value.
get(State, Key, Default) ->
case dict:find(Key, State#state_t.opts) of
{ok, Value} ->
Value;
error ->
Default
end.
-spec set(t(), any(), any()) -> t().
set(State=#state_t{opts=Opts}, Key, Value) ->
State#state_t{ opts = dict:store(Key, Value, Opts) }.
default(#state_t{default=Opts}) ->
Opts.
default(State, Opts) ->
State#state_t{default=Opts}.
format_error({profile_not_list, Profile, Other}) ->
io_lib:format("Profile config must be a list but for profile '~p' config given as:~n~p", [Profile, Other]).
-spec has_all_artifacts(#state_t{}) -> true | {false, file:filename()}.
has_all_artifacts(State) ->
Artifacts = rebar_state:get(State, artifacts, []),
Dir = rebar_dir:base_dir(State),
all(Dir, Artifacts).
all(_, []) ->
true;
all(Dir, [File|Artifacts]) ->
case filelib:is_regular(filename:join(Dir, File)) of
false ->
?DEBUG("Missing artifact ~ts", [filename:join(Dir, File)]),
{false, File};
true ->
all(Dir, Artifacts)
end.
-spec code_paths(#state_t{}, atom()) -> [file:filename()].
code_paths(#state_t{code_paths=CodePaths}, Key) ->
case dict:find(Key, CodePaths) of
{ok, CodePath} ->
CodePath;
_ ->
[]
end.
-spec code_paths(#state_t{}, atom(), [file:filename()]) -> #state_t{}.
code_paths(State=#state_t{code_paths=CodePaths}, Key, CodePath) ->
State#state_t{code_paths=dict:store(Key, CodePath, CodePaths)}.
-spec update_code_paths(#state_t{}, atom(), [file:filename()]) -> #state_t{}.
update_code_paths(State=#state_t{code_paths=CodePaths}, Key, CodePath) ->
case dict:is_key(Key, CodePaths) of
true ->
State#state_t{code_paths=dict:append_list(Key, CodePath, CodePaths)};
false ->
State#state_t{code_paths=dict:store(Key, CodePath, CodePaths)}
end.
opts(#state_t{opts=Opts}) ->
Opts.
opts(State, Opts) ->
State#state_t{opts=Opts}.
current_profiles(#state_t{current_profiles=Profiles}) ->
Profiles.
current_profiles(State, Profiles) ->
State#state_t{current_profiles=Profiles}.
lock(#state_t{lock=Lock}) ->
Lock.
lock(State=#state_t{}, Apps) when is_list(Apps) ->
State#state_t{lock=Apps};
lock(State=#state_t{lock=Lock}, App) ->
State#state_t{lock=[App | Lock]}.
escript_path(#state_t{escript_path=EscriptPath}) ->
EscriptPath.
escript_path(State, EscriptPath) ->
State#state_t{escript_path=EscriptPath}.
command_args(#state_t{command_args=CmdArgs}) ->
CmdArgs.
command_args(State, CmdArgs) ->
State#state_t{command_args=CmdArgs}.
command_parsed_args(#state_t{command_parsed_args=CmdArgs}) ->
CmdArgs.
command_parsed_args(State, CmdArgs) ->
State#state_t{command_parsed_args=CmdArgs}.
add_to_profile(State, Profile, KVs) when is_atom(Profile), is_list(KVs) ->
Opts = rebar_opts:add_to_profile(opts(State), Profile, KVs),
State#state_t{opts=Opts}.
apply_profiles(State, Profile) when not is_list(Profile) ->
apply_profiles(State, [Profile]);
apply_profiles(State, [default]) ->
State;
apply_profiles(State=#state_t{default = Defaults, current_profiles=CurrentProfiles}, Profiles) ->
ProvidedProfiles = lists:prefix([default|Profiles], CurrentProfiles),
AppliedProfiles = case Profiles of
%% Head of list global profile is special, only for use by rebar3
%% It does not clash if a user does `rebar3 as global...` but when
%% it is the head we must make sure not to prepend `default`
[global | _] ->
Profiles;
_ when ProvidedProfiles ->
deduplicate(CurrentProfiles);
_ ->
deduplicate(CurrentProfiles ++ Profiles)
end,
ConfigProfiles = rebar_state:get(State, profiles, []),
NewOpts =
lists:foldl(fun(default, OptsAcc) ->
OptsAcc;
(Profile, OptsAcc) ->
case proplists:get_value(Profile, ConfigProfiles, []) of
OptsList when is_list(OptsList) ->
ProfileOpts = dict:from_list(OptsList),
rebar_opts:merge_opts(Profile, ProfileOpts, OptsAcc);
Other ->
throw(?PRV_ERROR({profile_not_list, Profile, Other}))
end
end, Defaults, AppliedProfiles),
State#state_t{current_profiles = AppliedProfiles, opts=NewOpts}.
deduplicate(Profiles) ->
do_deduplicate(lists:reverse(Profiles), []).
do_deduplicate([], Acc) ->
Acc;
do_deduplicate([Head | Rest], Acc) ->
case lists:member(Head, Acc) of
true -> do_deduplicate(Rest, Acc);
false -> do_deduplicate(Rest, [Head | Acc])
end.
dir(#state_t{dir=Dir}) ->
Dir.
dir(State=#state_t{}, Dir) ->
State#state_t{dir=filename:absname(Dir)}.
deps_names(Deps) when is_list(Deps) ->
lists:map(fun(Dep) when is_tuple(Dep) ->
rebar_utils:to_binary(element(1, Dep));
(Dep) when is_atom(Dep) ->
rebar_utils:to_binary(Dep)
end, Deps);
deps_names(State) ->
Deps = rebar_state:get(State, deps, []),
deps_names(Deps).
current_app(#state_t{current_app=CurrentApp}) ->
CurrentApp.
current_app(State=#state_t{}, CurrentApp) ->
State#state_t{current_app=CurrentApp}.
project_apps(#state_t{project_apps=Apps}) ->
Apps.
project_apps(State=#state_t{}, NewApps) when is_list(NewApps) ->
State#state_t{project_apps=NewApps};
project_apps(State=#state_t{project_apps=Apps}, App) ->
State#state_t{project_apps=lists:keystore(rebar_app_info:name(App), 2, Apps, App)}.
deps_to_build(#state_t{deps_to_build=Apps}) ->
Apps.
deps_to_build(State=#state_t{deps_to_build=Apps}, NewApps) when is_list(NewApps) ->
State#state_t{deps_to_build=Apps++NewApps};
deps_to_build(State=#state_t{deps_to_build=Apps}, App) ->
State#state_t{deps_to_build=lists:keystore(rebar_app_info:name(App), 2, Apps, App)}.
all_deps(#state_t{all_deps=Apps}) ->
Apps.
all_deps(State=#state_t{}, NewApps) ->
State#state_t{all_deps=NewApps}.
all_checkout_deps(#state_t{all_deps=Apps}) ->
[App || App <- Apps, rebar_app_info:is_checkout(App)].
all_plugin_deps(#state_t{all_plugin_deps=Apps}) ->
Apps.
all_plugin_deps(State=#state_t{}, NewApps) ->
State#state_t{all_plugin_deps=NewApps}.
update_all_plugin_deps(State=#state_t{all_plugin_deps=Apps}, NewApps) ->
State#state_t{all_plugin_deps=Apps++NewApps}.
update_all_deps(State=#state_t{all_deps=Apps}, NewApps) ->
State#state_t{all_deps=Apps++NewApps}.
merge_all_deps(State=#state_t{all_deps=Apps}, UpdatedApps) when is_list(UpdatedApps) ->
State#state_t{all_deps=lists:ukeymerge(2, lists:keysort(2, UpdatedApps), lists:keysort(2, Apps))}.
namespace(#state_t{namespace=Namespace}) ->
Namespace.
namespace(State=#state_t{}, Namespace) ->
State#state_t{namespace=Namespace}.
-spec resources(t()) -> [{rebar_resource_v2:type(), module()}].
resources(#state_t{resources=Resources}) ->
Resources.
-spec set_resources(t(), [{rebar_resource_v2:type(), module()}]) -> t().
set_resources(State, Resources) ->
State#state_t{resources=Resources}.
-spec resources(t(), [{rebar_resource_v2:type(), module()}]) -> t().
resources(State, NewResources) ->
lists:foldl(fun(Resource, StateAcc) ->
add_resource(StateAcc, Resource)
end, State, NewResources).
-spec add_resource(t(), {rebar_resource_v2:type(), module()}) -> t().
add_resource(State=#state_t{resources=Resources}, {ResourceType, ResourceModule}) ->
_ = code:ensure_loaded(ResourceModule),
Resource = case erlang:function_exported(ResourceModule, init, 2) of
true ->
case ResourceModule:init(ResourceType, State) of
{ok, R=#resource{}} ->
R;
_ ->
%% init didn't return a resource
%% must be an old resource
warn_old_resource(ResourceModule),
rebar_resource:new(ResourceType,
ResourceModule,
#{})
end;
false ->
%% no init, must be initial implementation
warn_old_resource(ResourceModule),
rebar_resource:new(ResourceType,
ResourceModule,
#{})
end,
State#state_t{resources=[Resource | Resources]}.
warn_old_resource(ResourceModule) ->
?WARN("Using custom resource ~s that implements a deprecated api. "
"It should be upgraded to rebar_resource_v2.", [ResourceModule]).
%% @doc get a list of all registered compiler modules, which should implement
%% the `rebar_compiler' behaviour
-spec compilers(t()) -> [module()].
compilers(#state_t{compilers=Compilers}) ->
Compilers.
%% @doc register compiler modules prior to the existing ones. Each compiler
%% module should implement the `rebar_compiler' behaviour. Use this when
%% your custom compiler generates .erl files (or files of another type) and
%% that should run before other compiler modules.
-spec prepend_compilers(t(), [module()]) -> t().
prepend_compilers(State=#state_t{compilers=Compilers}, NewCompilers) ->
State#state_t{compilers=NewCompilers++Compilers}.
%% @doc register compiler modules. Each compiler
%% module should implement the `rebar_compiler' behaviour. Use this when
%% your custom compiler generates binary artifacts and does not have
%% a particular need to run before any other compiler.
-spec append_compilers(t(), [module()]) -> t().
append_compilers(State=#state_t{compilers=Compilers}, NewCompilers) ->
State#state_t{compilers=Compilers++NewCompilers}.
@private reset all compiler modules by replacing them by a list of
%% modules that implement the `rebar_compiler' behaviour.
-spec compilers(t(), [module()]) -> t().
compilers(State, Compilers) ->
State#state_t{compilers=Compilers}.
project_builders(#state_t{project_builders=ProjectBuilders}) ->
ProjectBuilders.
add_project_builder(State=#state_t{project_builders=ProjectBuilders}, Type, Module) ->
_ = code:ensure_loaded(Module),
case erlang:function_exported(Module, build, 1) of
true ->
State#state_t{project_builders=[{Type, Module} | ProjectBuilders]};
false ->
?WARN("Unable to add project builder for type ~s, required function ~s:build/1 not found.",
[Type, Module]),
State
end.
create_resources(Resources, State) ->
lists:foldl(fun(R, StateAcc) ->
add_resource(StateAcc, R)
end, State, Resources).
providers(#state_t{providers=Providers}) ->
Providers.
providers(State, NewProviders) ->
State#state_t{providers=NewProviders}.
allow_provider_overrides(#state_t{allow_provider_overrides=Allow}) ->
Allow.
allow_provider_overrides(State, Allow) ->
State#state_t{allow_provider_overrides=Allow}.
-spec add_provider(t(), providers:t()) -> t().
add_provider(State=#state_t{providers=Providers, allow_provider_overrides=true}, Provider) ->
State#state_t{providers=[Provider | Providers]};
add_provider(State=#state_t{providers=Providers, allow_provider_overrides=false}, Provider) ->
Name = providers:impl(Provider),
Namespace = providers:namespace(Provider),
Module = providers:module(Provider),
case lists:any(fun(P) ->
case {providers:impl(P), providers:namespace(P)} of
{Name, Namespace} ->
?DEBUG("Not adding provider ~ts ~ts from module ~ts because it already exists from module ~ts",
[atom_to_list(Namespace), atom_to_list(Name),
atom_to_list(Module), atom_to_list(providers:module(P))]),
true;
_ ->
false
end
end, Providers) of
true ->
State;
false ->
State#state_t{providers=[Provider | Providers]}
end.
-spec default_hex_repo_url_override(t()) -> binary().
default_hex_repo_url_override(State) ->
CDN = rebar_state:get(State, rebar_packages_cdn, ?DEFAULT_CDN),
rebar_utils:to_binary(CDN).
we want to be permissive with providers :
create_logic_providers(ProviderModules, State0) ->
try
lists:foldl(fun(ProviderMod, StateAcc) ->
case providers:new(ProviderMod, StateAcc) of
{error, {Mod, Error}} ->
?WARN("~ts", [Mod:format_error(Error)]),
StateAcc;
{error, Reason} ->
?WARN(Reason++"~n", []),
StateAcc;
{ok, StateAcc1} ->
StateAcc1
end
end, State0, ProviderModules)
catch
?WITH_STACKTRACE(C,T,S)
?DEBUG("~p: ~p ~p", [C, T, S]),
?CRASHDUMP("~p: ~p~n~p~n~n~p", [C, T, S, State0]),
throw({error, "Failed creating providers. Run with DIAGNOSTIC=1 for stacktrace or consult rebar3.crashdump."})
end.
to_list(#state_t{} = State) ->
Fields = record_info(fields, state_t),
Values = tl(tuple_to_list(State)),
lists:zip(Fields, [reformat(I) || I <- Values]).
reformat({K,V}) when is_list(V) ->
{K, [reformat(I) || I <- V]};
reformat({K,V}) ->
try
{K, [reformat(I) || I <- dict:to_list(V)]}
catch
error:{badrecord,dict} ->
{K,V}
end;
reformat(V) ->
try
[reformat(I) || I <- dict:to_list(V)]
catch
error:{badrecord,dict} ->
V
end.
%% ===================================================================
Internal functions
%% ===================================================================
| null | https://raw.githubusercontent.com/erlang/rebar3/048412ed4593e19097f4fa91747593aac6706afb/apps/rebar/src/rebar_state.erl | erlang | Load terms from rebar.config, if it exists
This ensures deterministic overrides for configs.
Head of list global profile is special, only for use by rebar3
It does not clash if a user does `rebar3 as global...` but when
it is the head we must make sure not to prepend `default`
init didn't return a resource
must be an old resource
no init, must be initial implementation
@doc get a list of all registered compiler modules, which should implement
the `rebar_compiler' behaviour
@doc register compiler modules prior to the existing ones. Each compiler
module should implement the `rebar_compiler' behaviour. Use this when
your custom compiler generates .erl files (or files of another type) and
that should run before other compiler modules.
@doc register compiler modules. Each compiler
module should implement the `rebar_compiler' behaviour. Use this when
your custom compiler generates binary artifacts and does not have
a particular need to run before any other compiler.
modules that implement the `rebar_compiler' behaviour.
===================================================================
=================================================================== | -module(rebar_state).
-export([new/0, new/1, new/2, new/3,
get/2, get/3, set/3,
format_error/1,
has_all_artifacts/1,
code_paths/2, code_paths/3, update_code_paths/3,
opts/1, opts/2,
default/1, default/2,
escript_path/1, escript_path/2,
lock/1, lock/2,
current_profiles/1, current_profiles/2,
command_args/1, command_args/2,
command_parsed_args/1, command_parsed_args/2,
add_to_profile/3, apply_profiles/2,
dir/1, dir/2,
create_logic_providers/2,
current_app/1, current_app/2,
project_apps/1, project_apps/2,
deps_to_build/1, deps_to_build/2,
all_plugin_deps/1, all_plugin_deps/2, update_all_plugin_deps/2,
all_deps/1, all_deps/2, update_all_deps/2, merge_all_deps/2,
all_checkout_deps/1,
namespace/1, namespace/2,
default_hex_repo_url_override/1,
deps_names/1,
to_list/1,
compilers/1, compilers/2,
prepend_compilers/2, append_compilers/2,
project_builders/1, add_project_builder/3,
create_resources/2, set_resources/2,
resources/1, resources/2, add_resource/2,
providers/1, providers/2, add_provider/2,
allow_provider_overrides/1, allow_provider_overrides/2
]).
-include("rebar.hrl").
-include_lib("providers/include/providers.hrl").
-record(state_t, {dir :: file:name(),
opts = dict:new() :: rebar_dict(),
code_paths = dict:new() :: rebar_dict(),
default = dict:new() :: rebar_dict(),
escript_path :: undefined | file:filename_all(),
lock = [],
current_profiles = [default] :: [atom()],
namespace = default :: atom(),
command_args = [],
command_parsed_args = {[], []},
current_app :: undefined | rebar_app_info:t(),
project_apps = [] :: [rebar_app_info:t()],
deps_to_build = [] :: [rebar_app_info:t()],
all_plugin_deps = [] :: [rebar_app_info:t()],
all_deps = [] :: [rebar_app_info:t()],
compilers = [] :: [module()],
project_builders = [] :: [{rebar_app_info:project_type(), module()}],
resources = [],
providers = [],
allow_provider_overrides = false :: boolean()}).
-export_type([t/0]).
-type t() :: #state_t{}.
-spec new() -> t().
new() ->
BaseState = base_state(dict:new()),
BaseState#state_t{dir = rebar_dir:get_cwd()}.
-spec new(list()) -> t().
new(Config) when is_list(Config) ->
Opts = base_opts(Config),
BaseState = base_state(Opts),
BaseState#state_t{dir=rebar_dir:get_cwd(),
default=Opts}.
-spec new(t() | atom(), list()) -> t().
new(Profile, Config) when is_atom(Profile)
, is_list(Config) ->
Opts = base_opts(Config),
BaseState = base_state(Opts),
BaseState#state_t{dir = rebar_dir:get_cwd(),
current_profiles = [Profile],
default = Opts};
new(ParentState=#state_t{}, Config) ->
Dir = rebar_dir:get_cwd(),
new(ParentState, Config, Dir).
-spec new(t(), list(), file:filename_all()) -> t().
new(ParentState, Config, Dir) ->
new(ParentState, Config, deps_from_config(Dir, Config), Dir).
new(ParentState, Config, Deps, Dir) ->
Opts = ParentState#state_t.opts,
Plugins = proplists:get_value(plugins, Config, []),
ProjectPlugins = proplists:get_value(project_plugins, Config, []),
Terms = Deps++[{{project_plugins, default}, ProjectPlugins}, {{plugins, default}, Plugins} | Config],
true = rebar_config:verify_config_format(Terms),
LocalOpts = dict:from_list(Terms),
NewOpts = rebar_opts:merge_opts(LocalOpts, Opts),
ParentState#state_t{dir=Dir
,opts=NewOpts
,default=NewOpts}.
deps_from_config(Dir, Config) ->
case rebar_config:consult_lock_file(filename:join(Dir, ?LOCK_FILE)) of
[] ->
[{{deps, default}, proplists:get_value(deps, Config, [])}];
D ->
We want the top level only from the lock file .
Deps = [X || X <- D, element(3, X) =:= 0],
[{{locks, default}, D}, {{deps, default}, Deps}]
end.
base_state(Opts) ->
#state_t{opts=Opts}.
base_opts(Config) ->
Deps = proplists:get_value(deps, Config, []),
Plugins = proplists:get_value(plugins, Config, []),
ProjectPlugins = proplists:get_value(project_plugins, Config, []),
Terms = [{{deps, default}, Deps}, {{plugins, default}, Plugins},
{{project_plugins, default}, ProjectPlugins} | Config],
true = rebar_config:verify_config_format(Terms),
dict:from_list(Terms).
get(State, Key) ->
{ok, Value} = dict:find(Key, State#state_t.opts),
Value.
get(State, Key, Default) ->
case dict:find(Key, State#state_t.opts) of
{ok, Value} ->
Value;
error ->
Default
end.
-spec set(t(), any(), any()) -> t().
set(State=#state_t{opts=Opts}, Key, Value) ->
State#state_t{ opts = dict:store(Key, Value, Opts) }.
default(#state_t{default=Opts}) ->
Opts.
default(State, Opts) ->
State#state_t{default=Opts}.
format_error({profile_not_list, Profile, Other}) ->
io_lib:format("Profile config must be a list but for profile '~p' config given as:~n~p", [Profile, Other]).
-spec has_all_artifacts(#state_t{}) -> true | {false, file:filename()}.
has_all_artifacts(State) ->
Artifacts = rebar_state:get(State, artifacts, []),
Dir = rebar_dir:base_dir(State),
all(Dir, Artifacts).
all(_, []) ->
true;
all(Dir, [File|Artifacts]) ->
case filelib:is_regular(filename:join(Dir, File)) of
false ->
?DEBUG("Missing artifact ~ts", [filename:join(Dir, File)]),
{false, File};
true ->
all(Dir, Artifacts)
end.
-spec code_paths(#state_t{}, atom()) -> [file:filename()].
code_paths(#state_t{code_paths=CodePaths}, Key) ->
case dict:find(Key, CodePaths) of
{ok, CodePath} ->
CodePath;
_ ->
[]
end.
-spec code_paths(#state_t{}, atom(), [file:filename()]) -> #state_t{}.
code_paths(State=#state_t{code_paths=CodePaths}, Key, CodePath) ->
State#state_t{code_paths=dict:store(Key, CodePath, CodePaths)}.
-spec update_code_paths(#state_t{}, atom(), [file:filename()]) -> #state_t{}.
update_code_paths(State=#state_t{code_paths=CodePaths}, Key, CodePath) ->
case dict:is_key(Key, CodePaths) of
true ->
State#state_t{code_paths=dict:append_list(Key, CodePath, CodePaths)};
false ->
State#state_t{code_paths=dict:store(Key, CodePath, CodePaths)}
end.
opts(#state_t{opts=Opts}) ->
Opts.
opts(State, Opts) ->
State#state_t{opts=Opts}.
current_profiles(#state_t{current_profiles=Profiles}) ->
Profiles.
current_profiles(State, Profiles) ->
State#state_t{current_profiles=Profiles}.
lock(#state_t{lock=Lock}) ->
Lock.
lock(State=#state_t{}, Apps) when is_list(Apps) ->
State#state_t{lock=Apps};
lock(State=#state_t{lock=Lock}, App) ->
State#state_t{lock=[App | Lock]}.
escript_path(#state_t{escript_path=EscriptPath}) ->
EscriptPath.
escript_path(State, EscriptPath) ->
State#state_t{escript_path=EscriptPath}.
command_args(#state_t{command_args=CmdArgs}) ->
CmdArgs.
command_args(State, CmdArgs) ->
State#state_t{command_args=CmdArgs}.
command_parsed_args(#state_t{command_parsed_args=CmdArgs}) ->
CmdArgs.
command_parsed_args(State, CmdArgs) ->
State#state_t{command_parsed_args=CmdArgs}.
add_to_profile(State, Profile, KVs) when is_atom(Profile), is_list(KVs) ->
Opts = rebar_opts:add_to_profile(opts(State), Profile, KVs),
State#state_t{opts=Opts}.
apply_profiles(State, Profile) when not is_list(Profile) ->
apply_profiles(State, [Profile]);
apply_profiles(State, [default]) ->
State;
apply_profiles(State=#state_t{default = Defaults, current_profiles=CurrentProfiles}, Profiles) ->
ProvidedProfiles = lists:prefix([default|Profiles], CurrentProfiles),
AppliedProfiles = case Profiles of
[global | _] ->
Profiles;
_ when ProvidedProfiles ->
deduplicate(CurrentProfiles);
_ ->
deduplicate(CurrentProfiles ++ Profiles)
end,
ConfigProfiles = rebar_state:get(State, profiles, []),
NewOpts =
lists:foldl(fun(default, OptsAcc) ->
OptsAcc;
(Profile, OptsAcc) ->
case proplists:get_value(Profile, ConfigProfiles, []) of
OptsList when is_list(OptsList) ->
ProfileOpts = dict:from_list(OptsList),
rebar_opts:merge_opts(Profile, ProfileOpts, OptsAcc);
Other ->
throw(?PRV_ERROR({profile_not_list, Profile, Other}))
end
end, Defaults, AppliedProfiles),
State#state_t{current_profiles = AppliedProfiles, opts=NewOpts}.
deduplicate(Profiles) ->
do_deduplicate(lists:reverse(Profiles), []).
do_deduplicate([], Acc) ->
Acc;
do_deduplicate([Head | Rest], Acc) ->
case lists:member(Head, Acc) of
true -> do_deduplicate(Rest, Acc);
false -> do_deduplicate(Rest, [Head | Acc])
end.
dir(#state_t{dir=Dir}) ->
Dir.
dir(State=#state_t{}, Dir) ->
State#state_t{dir=filename:absname(Dir)}.
deps_names(Deps) when is_list(Deps) ->
lists:map(fun(Dep) when is_tuple(Dep) ->
rebar_utils:to_binary(element(1, Dep));
(Dep) when is_atom(Dep) ->
rebar_utils:to_binary(Dep)
end, Deps);
deps_names(State) ->
Deps = rebar_state:get(State, deps, []),
deps_names(Deps).
current_app(#state_t{current_app=CurrentApp}) ->
CurrentApp.
current_app(State=#state_t{}, CurrentApp) ->
State#state_t{current_app=CurrentApp}.
project_apps(#state_t{project_apps=Apps}) ->
Apps.
project_apps(State=#state_t{}, NewApps) when is_list(NewApps) ->
State#state_t{project_apps=NewApps};
project_apps(State=#state_t{project_apps=Apps}, App) ->
State#state_t{project_apps=lists:keystore(rebar_app_info:name(App), 2, Apps, App)}.
deps_to_build(#state_t{deps_to_build=Apps}) ->
Apps.
deps_to_build(State=#state_t{deps_to_build=Apps}, NewApps) when is_list(NewApps) ->
State#state_t{deps_to_build=Apps++NewApps};
deps_to_build(State=#state_t{deps_to_build=Apps}, App) ->
State#state_t{deps_to_build=lists:keystore(rebar_app_info:name(App), 2, Apps, App)}.
all_deps(#state_t{all_deps=Apps}) ->
Apps.
all_deps(State=#state_t{}, NewApps) ->
State#state_t{all_deps=NewApps}.
all_checkout_deps(#state_t{all_deps=Apps}) ->
[App || App <- Apps, rebar_app_info:is_checkout(App)].
all_plugin_deps(#state_t{all_plugin_deps=Apps}) ->
Apps.
all_plugin_deps(State=#state_t{}, NewApps) ->
State#state_t{all_plugin_deps=NewApps}.
update_all_plugin_deps(State=#state_t{all_plugin_deps=Apps}, NewApps) ->
State#state_t{all_plugin_deps=Apps++NewApps}.
update_all_deps(State=#state_t{all_deps=Apps}, NewApps) ->
State#state_t{all_deps=Apps++NewApps}.
merge_all_deps(State=#state_t{all_deps=Apps}, UpdatedApps) when is_list(UpdatedApps) ->
State#state_t{all_deps=lists:ukeymerge(2, lists:keysort(2, UpdatedApps), lists:keysort(2, Apps))}.
namespace(#state_t{namespace=Namespace}) ->
Namespace.
namespace(State=#state_t{}, Namespace) ->
State#state_t{namespace=Namespace}.
-spec resources(t()) -> [{rebar_resource_v2:type(), module()}].
resources(#state_t{resources=Resources}) ->
Resources.
-spec set_resources(t(), [{rebar_resource_v2:type(), module()}]) -> t().
set_resources(State, Resources) ->
State#state_t{resources=Resources}.
-spec resources(t(), [{rebar_resource_v2:type(), module()}]) -> t().
resources(State, NewResources) ->
lists:foldl(fun(Resource, StateAcc) ->
add_resource(StateAcc, Resource)
end, State, NewResources).
-spec add_resource(t(), {rebar_resource_v2:type(), module()}) -> t().
add_resource(State=#state_t{resources=Resources}, {ResourceType, ResourceModule}) ->
_ = code:ensure_loaded(ResourceModule),
Resource = case erlang:function_exported(ResourceModule, init, 2) of
true ->
case ResourceModule:init(ResourceType, State) of
{ok, R=#resource{}} ->
R;
_ ->
warn_old_resource(ResourceModule),
rebar_resource:new(ResourceType,
ResourceModule,
#{})
end;
false ->
warn_old_resource(ResourceModule),
rebar_resource:new(ResourceType,
ResourceModule,
#{})
end,
State#state_t{resources=[Resource | Resources]}.
warn_old_resource(ResourceModule) ->
?WARN("Using custom resource ~s that implements a deprecated api. "
"It should be upgraded to rebar_resource_v2.", [ResourceModule]).
-spec compilers(t()) -> [module()].
compilers(#state_t{compilers=Compilers}) ->
Compilers.
-spec prepend_compilers(t(), [module()]) -> t().
prepend_compilers(State=#state_t{compilers=Compilers}, NewCompilers) ->
State#state_t{compilers=NewCompilers++Compilers}.
-spec append_compilers(t(), [module()]) -> t().
append_compilers(State=#state_t{compilers=Compilers}, NewCompilers) ->
State#state_t{compilers=Compilers++NewCompilers}.
@private reset all compiler modules by replacing them by a list of
-spec compilers(t(), [module()]) -> t().
compilers(State, Compilers) ->
State#state_t{compilers=Compilers}.
project_builders(#state_t{project_builders=ProjectBuilders}) ->
ProjectBuilders.
add_project_builder(State=#state_t{project_builders=ProjectBuilders}, Type, Module) ->
_ = code:ensure_loaded(Module),
case erlang:function_exported(Module, build, 1) of
true ->
State#state_t{project_builders=[{Type, Module} | ProjectBuilders]};
false ->
?WARN("Unable to add project builder for type ~s, required function ~s:build/1 not found.",
[Type, Module]),
State
end.
create_resources(Resources, State) ->
lists:foldl(fun(R, StateAcc) ->
add_resource(StateAcc, R)
end, State, Resources).
providers(#state_t{providers=Providers}) ->
Providers.
providers(State, NewProviders) ->
State#state_t{providers=NewProviders}.
allow_provider_overrides(#state_t{allow_provider_overrides=Allow}) ->
Allow.
allow_provider_overrides(State, Allow) ->
State#state_t{allow_provider_overrides=Allow}.
-spec add_provider(t(), providers:t()) -> t().
add_provider(State=#state_t{providers=Providers, allow_provider_overrides=true}, Provider) ->
State#state_t{providers=[Provider | Providers]};
add_provider(State=#state_t{providers=Providers, allow_provider_overrides=false}, Provider) ->
Name = providers:impl(Provider),
Namespace = providers:namespace(Provider),
Module = providers:module(Provider),
case lists:any(fun(P) ->
case {providers:impl(P), providers:namespace(P)} of
{Name, Namespace} ->
?DEBUG("Not adding provider ~ts ~ts from module ~ts because it already exists from module ~ts",
[atom_to_list(Namespace), atom_to_list(Name),
atom_to_list(Module), atom_to_list(providers:module(P))]),
true;
_ ->
false
end
end, Providers) of
true ->
State;
false ->
State#state_t{providers=[Provider | Providers]}
end.
-spec default_hex_repo_url_override(t()) -> binary().
default_hex_repo_url_override(State) ->
CDN = rebar_state:get(State, rebar_packages_cdn, ?DEFAULT_CDN),
rebar_utils:to_binary(CDN).
we want to be permissive with providers :
create_logic_providers(ProviderModules, State0) ->
try
lists:foldl(fun(ProviderMod, StateAcc) ->
case providers:new(ProviderMod, StateAcc) of
{error, {Mod, Error}} ->
?WARN("~ts", [Mod:format_error(Error)]),
StateAcc;
{error, Reason} ->
?WARN(Reason++"~n", []),
StateAcc;
{ok, StateAcc1} ->
StateAcc1
end
end, State0, ProviderModules)
catch
?WITH_STACKTRACE(C,T,S)
?DEBUG("~p: ~p ~p", [C, T, S]),
?CRASHDUMP("~p: ~p~n~p~n~n~p", [C, T, S, State0]),
throw({error, "Failed creating providers. Run with DIAGNOSTIC=1 for stacktrace or consult rebar3.crashdump."})
end.
to_list(#state_t{} = State) ->
Fields = record_info(fields, state_t),
Values = tl(tuple_to_list(State)),
lists:zip(Fields, [reformat(I) || I <- Values]).
reformat({K,V}) when is_list(V) ->
{K, [reformat(I) || I <- V]};
reformat({K,V}) ->
try
{K, [reformat(I) || I <- dict:to_list(V)]}
catch
error:{badrecord,dict} ->
{K,V}
end;
reformat(V) ->
try
[reformat(I) || I <- dict:to_list(V)]
catch
error:{badrecord,dict} ->
V
end.
Internal functions
|
5f06108b9e9daf4ba0e98e902b1d723d239138df5442336fe06faa7fcd057e0c | scrive/hpqtypes | Class.hs | module Database.PostgreSQL.PQTypes.SQL.Class (
SomeSQL(..)
, IsSQL(..)
, unsafeSQL
) where
import Data.String
import Foreign.C.String
import Foreign.Ptr
import Database.PostgreSQL.PQTypes.Internal.C.Types
import Database.PostgreSQL.PQTypes.ToSQL
-- | Container for SQL-like type storage.
data SomeSQL = forall sql. IsSQL sql => SomeSQL sql
-- | Class representing \"SQLness\" of a given type.
class Show sql => IsSQL sql where
-- | Convert 'sql' to libpqtypes representation and pass
-- it to supplied continuation (usually for execution).
withSQL :: sql
-> ParamAllocator -- ^ 'PGparam' allocator.
-> (Ptr PGparam -> CString -> IO r) -- ^ Continuation which takes 'sql'
-- converted to libpqtypes specific representation, ie. 'PGparam' object
-- containing query parameters and C string containing the query itself.
-> IO r
----------------------------------------
-- | Convert unsafely from 'String' to 'sql' (Note: reckless usage
-- of this function may introduce security vulnerabilities such
-- as proneness to SQL injection attacks).
unsafeSQL :: (IsSQL sql, IsString sql) => String -> sql
unsafeSQL = fromString
| null | https://raw.githubusercontent.com/scrive/hpqtypes/5b652645d5fdebbec8dbd1a68583fbcb8dfe5d93/src/Database/PostgreSQL/PQTypes/SQL/Class.hs | haskell | | Container for SQL-like type storage.
| Class representing \"SQLness\" of a given type.
| Convert 'sql' to libpqtypes representation and pass
it to supplied continuation (usually for execution).
^ 'PGparam' allocator.
^ Continuation which takes 'sql'
converted to libpqtypes specific representation, ie. 'PGparam' object
containing query parameters and C string containing the query itself.
--------------------------------------
| Convert unsafely from 'String' to 'sql' (Note: reckless usage
of this function may introduce security vulnerabilities such
as proneness to SQL injection attacks). | module Database.PostgreSQL.PQTypes.SQL.Class (
SomeSQL(..)
, IsSQL(..)
, unsafeSQL
) where
import Data.String
import Foreign.C.String
import Foreign.Ptr
import Database.PostgreSQL.PQTypes.Internal.C.Types
import Database.PostgreSQL.PQTypes.ToSQL
data SomeSQL = forall sql. IsSQL sql => SomeSQL sql
class Show sql => IsSQL sql where
withSQL :: sql
-> IO r
unsafeSQL :: (IsSQL sql, IsString sql) => String -> sql
unsafeSQL = fromString
|
f479b4062244511f2abdeaaa535670e7da9f857ec60a86f58e01cd19c78174cb | xvw/planet | hakyll.ml | open Bedrock
open Util
type metadata_key = string
type metadata = string
let render key f value = Format.asprintf "%s: %s\n" key (f value)
let render_string key value = render key id value
let may_render_with key f default = function
| None -> render_string key default
| Some value -> render key f value
;;
let may_render key f = function
| None -> ""
| Some value -> render key f value
;;
let may_render_with_format ~default f key value =
may_render_with key (fun x -> Format.asprintf "%a" f x) default value
;;
let render_if key flag = if flag then render_string key "true" else ""
let join rules = "---\n" ^ String.concat "" rules ^ "---\n"
let textarea ?(attr = "planet-qexp") =
Format.asprintf {|<textarea data-%s="%s">%s</textarea>|} attr
;;
| null | https://raw.githubusercontent.com/xvw/planet/c2a77ea66f61cc76df78b9c2ad06d114795f3053/src/glue/hakyll.ml | ocaml | open Bedrock
open Util
type metadata_key = string
type metadata = string
let render key f value = Format.asprintf "%s: %s\n" key (f value)
let render_string key value = render key id value
let may_render_with key f default = function
| None -> render_string key default
| Some value -> render key f value
;;
let may_render key f = function
| None -> ""
| Some value -> render key f value
;;
let may_render_with_format ~default f key value =
may_render_with key (fun x -> Format.asprintf "%a" f x) default value
;;
let render_if key flag = if flag then render_string key "true" else ""
let join rules = "---\n" ^ String.concat "" rules ^ "---\n"
let textarea ?(attr = "planet-qexp") =
Format.asprintf {|<textarea data-%s="%s">%s</textarea>|} attr
;;
|
|
9b0bdd5163a08d51f2b9e5f9b8df55f4a710379fc6f11eec1629c8cc1c147661 | camsaul/toucan2 | model_test.clj | (ns toucan2.model-test
(:require
[clojure.test :refer :all]
[methodical.core :as m]
[toucan2.map-backend.honeysql2 :as map.honeysql]
[toucan2.model :as model]
[toucan2.pipeline :as pipeline]
[toucan2.select :as select]
[toucan2.test :as test]
[toucan2.tools.compile :as tools.compile]))
(set! *warn-on-reflection* true)
(deftest ^:parallel primary-keys-test
(testing "default implementation"
(is (= [:id]
(model/primary-keys ::some-default-model)))))
(m/defmethod model/primary-keys ::primary-keys.returns-bare-keyword
[_model]
:name)
(m/defmethod model/primary-keys ::primary-keys.returns-vector
[_model]
[:name :id])
(m/defmethod model/primary-keys ::primary-keys.returns-invalid
[_model]
[:name nil])
(deftest ^:parallel primary-keys-wrap-results-test
(testing "primary-keys should wrap results in a vector if needed, and validate"
(is (= [:name]
(model/primary-keys ::primary-keys.returns-bare-keyword)))
(is (= [:name :id]
(model/primary-keys ::primary-keys.returns-vector)))
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
#"Bad toucan2.model/primary-keys for model .* should return keyword or sequence of keywords, got .*"
(model/primary-keys ::primary-keys.returns-invalid)))))
(m/defmethod model/table-name ::string-table-name
[_model]
"my-table")
(deftest ^:parallel ^:parallel table-name-test
(are [model expected] (= expected
(model/table-name model))
"ABC" :ABC
:abc :abc
:ns/abc :abc
:default :default
'symbol :symbol
::string-table-name :my-table))
(derive ::people.unquoted ::test/people)
(m/defmethod pipeline/transduce-query [#_query-type :default #_model ::people.unquoted #_resolved-query :default]
[rf query-type model parsed-args resolved-query]
(binding [map.honeysql/*options* {:quoted false}]
(next-method rf query-type model parsed-args resolved-query)))
(deftest ^:parallel default-honeysql-options-for-a-model-test
(testing "There should be a way to specify 'default options' for a specific model"
(is (= ["SELECT * FROM people WHERE id = ?" 1]
(tools.compile/compile
(select/select ::people.unquoted {:select [:*]
:from [[:people]]
:where [:= :id 1]}))))))
;;; [[model/default-connectable]] gets tested basically everywhere, because we define it for the models in
;;; [[toucan2.test]] and use it in almost every test namespace
(derive ::venues.namespaced ::test/venues)
(m/defmethod model/model->namespace ::venues.namespaced
[_model]
{::venues.namespaced :venue
::test/categories :category})
(deftest ^:parallel model->namespace-test
(are [model expected] (= expected
(model/model->namespace model))
::venues.namespaced {::venues.namespaced :venue, ::test/categories :category}
:venues nil
nil nil))
(deftest ^:parallel table-name->namespace-test
(are [model expected] (= expected
(model/table-name->namespace model))
::venues.namespaced {"venues" :venue, "category" :category}
:venues nil
nil nil))
(derive ::venues.namespaced.child ::venues.namespaced)
(deftest ^:parallel namespace-test
(are [model expected] (= expected
(model/namespace model))
::venues.namespaced :venue
::venues.namespaced.child :venue
:venues nil
nil nil))
(deftest ^:parallel namespaced-default-primary-keys-test
(is (= [:venue/id]
(model/primary-keys ::venues.namespaced))))
(m/defmethod model/model->namespace ::bad-model->namespace
[_model]
"my-namespace")
(deftest ^:parallel model->namespace-error-test
(testing "model->namespace :after method should validate results"
(is (thrown-with-msg?
Throwable
(re-pattern
(java.util.regex.Pattern/quote
"Assert failed: model->namespace should return a map. Got: ^java.lang.String \"my-namespace\""))
(model/model->namespace ::bad-model->namespace)))))
| null | https://raw.githubusercontent.com/camsaul/toucan2/8827187a2211edae13c0f7e654ad135d8a920591/test/toucan2/model_test.clj | clojure | [[model/default-connectable]] gets tested basically everywhere, because we define it for the models in
[[toucan2.test]] and use it in almost every test namespace | (ns toucan2.model-test
(:require
[clojure.test :refer :all]
[methodical.core :as m]
[toucan2.map-backend.honeysql2 :as map.honeysql]
[toucan2.model :as model]
[toucan2.pipeline :as pipeline]
[toucan2.select :as select]
[toucan2.test :as test]
[toucan2.tools.compile :as tools.compile]))
(set! *warn-on-reflection* true)
(deftest ^:parallel primary-keys-test
(testing "default implementation"
(is (= [:id]
(model/primary-keys ::some-default-model)))))
(m/defmethod model/primary-keys ::primary-keys.returns-bare-keyword
[_model]
:name)
(m/defmethod model/primary-keys ::primary-keys.returns-vector
[_model]
[:name :id])
(m/defmethod model/primary-keys ::primary-keys.returns-invalid
[_model]
[:name nil])
(deftest ^:parallel primary-keys-wrap-results-test
(testing "primary-keys should wrap results in a vector if needed, and validate"
(is (= [:name]
(model/primary-keys ::primary-keys.returns-bare-keyword)))
(is (= [:name :id]
(model/primary-keys ::primary-keys.returns-vector)))
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
#"Bad toucan2.model/primary-keys for model .* should return keyword or sequence of keywords, got .*"
(model/primary-keys ::primary-keys.returns-invalid)))))
(m/defmethod model/table-name ::string-table-name
[_model]
"my-table")
(deftest ^:parallel ^:parallel table-name-test
(are [model expected] (= expected
(model/table-name model))
"ABC" :ABC
:abc :abc
:ns/abc :abc
:default :default
'symbol :symbol
::string-table-name :my-table))
(derive ::people.unquoted ::test/people)
(m/defmethod pipeline/transduce-query [#_query-type :default #_model ::people.unquoted #_resolved-query :default]
[rf query-type model parsed-args resolved-query]
(binding [map.honeysql/*options* {:quoted false}]
(next-method rf query-type model parsed-args resolved-query)))
(deftest ^:parallel default-honeysql-options-for-a-model-test
(testing "There should be a way to specify 'default options' for a specific model"
(is (= ["SELECT * FROM people WHERE id = ?" 1]
(tools.compile/compile
(select/select ::people.unquoted {:select [:*]
:from [[:people]]
:where [:= :id 1]}))))))
(derive ::venues.namespaced ::test/venues)
(m/defmethod model/model->namespace ::venues.namespaced
[_model]
{::venues.namespaced :venue
::test/categories :category})
(deftest ^:parallel model->namespace-test
(are [model expected] (= expected
(model/model->namespace model))
::venues.namespaced {::venues.namespaced :venue, ::test/categories :category}
:venues nil
nil nil))
(deftest ^:parallel table-name->namespace-test
(are [model expected] (= expected
(model/table-name->namespace model))
::venues.namespaced {"venues" :venue, "category" :category}
:venues nil
nil nil))
(derive ::venues.namespaced.child ::venues.namespaced)
(deftest ^:parallel namespace-test
(are [model expected] (= expected
(model/namespace model))
::venues.namespaced :venue
::venues.namespaced.child :venue
:venues nil
nil nil))
(deftest ^:parallel namespaced-default-primary-keys-test
(is (= [:venue/id]
(model/primary-keys ::venues.namespaced))))
(m/defmethod model/model->namespace ::bad-model->namespace
[_model]
"my-namespace")
(deftest ^:parallel model->namespace-error-test
(testing "model->namespace :after method should validate results"
(is (thrown-with-msg?
Throwable
(re-pattern
(java.util.regex.Pattern/quote
"Assert failed: model->namespace should return a map. Got: ^java.lang.String \"my-namespace\""))
(model/model->namespace ::bad-model->namespace)))))
|
74c60881ca9c3b2ef8f83ffce111d9fc3c3b30cf459f8dd96afef1b6f07d5c73 | marijnh/Postmodern | connect.lisp | -*- Mode : LISP ; Syntax : Ansi - Common - Lisp ; Base : 10 ; Package : POSTMODERN ; -*-
(in-package :postmodern)
(defvar *connection-pools* (make-hash-table :test 'equal)
"Maps pool specifiers to lists of pooled connections.")
(defparameter *database* nil
"Special holding the current database. Most functions and macros operating
on a database assume this contains a connected database.")
(defclass pooled-database-connection (database-connection)
((pool-type :initarg :pool-type :accessor connection-pool-type))
(:documentation "Type for database connections that are pooled.
Stores the arguments used to create it, so different pools can be
distinguished."))
(defun connect (database-name user-name password host &key (port 5432) pooled-p
(use-ssl *default-use-ssl*)
(use-binary nil)
(service "postgres")
(application-name ""))
"Create a new database connection for the given user and the database. Port
will default to 5432, which is where most PostgreSQL servers are running. If
pooled-p is T, a connection will be taken from a pool of connections of this
type, if one is available there, and when the connection is disconnected it
will be put back into this pool instead. use-ssl can be :no, :yes, or :try,
as in open-database, and defaults to the value of *default-use-ssl*."
(cond (pooled-p
(let ((type (list database-name user-name password host port use-ssl
application-name use-binary)))
(or (get-from-pool type)
(let ((connection (cl-postgres:open-database database-name user-name
password host port
use-ssl
service application-name
use-binary)))
#-genera (change-class connection 'pooled-database-connection
:pool-type type)
#+genera (progn
(change-class connection 'pooled-database-connection)
(setf (slot-value connection 'pool-type) type))
connection))))
(t (cl-postgres:open-database database-name user-name password host port
use-ssl service application-name
use-binary))))
(defun connected-p (database)
"Returns a boolean indicating whether the given connection is still connected
to the server."
(cl-postgres:database-open-p database))
(defun connect-toplevel (database-name user-name password host
&key (port 5432) (use-ssl *default-use-ssl*) (application-name "")
use-binary)
"Bind the *database* to a new connection. Use this if you only need one
connection, or if you want a connection for debugging from the REPL."
(when (and *database* (connected-p *database*))
(restart-case (error "Top-level database already connected.")
(replace () :report "Replace it with a new connection."
(disconnect-toplevel))
(leave () :report "Leave it." (return-from connect-toplevel nil))))
(setf *database* (connect database-name user-name password host
:port port :use-ssl use-ssl :application-name application-name
:use-binary use-binary))
(values))
(defgeneric disconnect (database)
(:method ((connection database-connection))
(close-database connection))
(:documentation "Disconnects a normal database connection, or moves a pooled
connection into the pool."))
(defgeneric reconnect (database)
(:method ((database database-connection))
(reopen-database database)
(when *schema-path*
(let ((path *schema-path*))
(set-search-path path))))
(:method ((connection pooled-database-connection))
(error "Can not reconnect a pooled database."))
(:documentation "Reconnect a disconnected database connection. This is not
allowed for pooled connections ― after they are disconnected they might be in
use by some other process, and should no longer be used."))
(defun disconnect-toplevel ()
"Disconnect *database*."
(when (and *database* (connected-p *database*))
(disconnect *database*))
(setf *database* nil))
(defun call-with-connection (spec thunk)
"The functional backend to with-connection. Binds *database* to a new connection
as specified by spec, which should be a list that connect can be applied to, and
runs the zero-argument function given as second argument in the new environment.
When the function returns or throws, the new connection is disconnected."
(let ((*database* (apply #'connect spec)))
(unwind-protect (funcall thunk)
(disconnect *database*))))
(defmacro with-connection (spec &body body)
"Evaluates the body with *database* bound to a connection as specified by spec,
which should be list that connect can be applied to."
`(let ((*database* (apply #'connect ,spec)))
(unwind-protect (progn ,@body)
(disconnect *database*))))
#+postmodern-thread-safe
(defvar *pool-lock*
(bordeaux-threads:make-lock "connection-pool-lock")
"A lock to prevent multiple threads from messing with the connection
pool at the same time.")
(defmacro with-pool-lock (&body body)
"Aquire a lock for the pool when evaluating body \(if thread support
is present)."
#+postmodern-thread-safe
`(bordeaux-threads:with-lock-held (*pool-lock*) ,@body)
#-postmodern-thread-safe
`(progn ,@body))
(defun get-from-pool (type)
"Get a database connection from the specified pool, returns nil if
no connection was available."
(with-pool-lock
(pop (gethash type *connection-pools*))))
(defmethod disconnect ((connection pooled-database-connection))
"Add the connection to the corresponding pool, or drop it when the
pool is full."
(macrolet ((the-pool ()
'(gethash (connection-pool-type connection) *connection-pools* ())))
(when (database-open-p connection)
(with-pool-lock
(if (or (not *max-pool-size*) (< (length (the-pool)) *max-pool-size*))
(push connection (the-pool))
(call-next-method))))
(values)))
(defun clear-connection-pool ()
"Disconnect and remove all connections in the connection pools."
(with-pool-lock
(maphash
(lambda (type connections)
(declare (ignore type))
(dolist (conn connections)
(close-database conn)))
*connection-pools*)
(setf *connection-pools* (make-hash-table :test 'equal))
(values)))
| null | https://raw.githubusercontent.com/marijnh/Postmodern/d54e494000e1915a7046e8d825cb635555957e85/postmodern/connect.lisp | lisp | Syntax : Ansi - Common - Lisp ; Base : 10 ; Package : POSTMODERN ; -*- | (in-package :postmodern)
(defvar *connection-pools* (make-hash-table :test 'equal)
"Maps pool specifiers to lists of pooled connections.")
(defparameter *database* nil
"Special holding the current database. Most functions and macros operating
on a database assume this contains a connected database.")
(defclass pooled-database-connection (database-connection)
((pool-type :initarg :pool-type :accessor connection-pool-type))
(:documentation "Type for database connections that are pooled.
Stores the arguments used to create it, so different pools can be
distinguished."))
(defun connect (database-name user-name password host &key (port 5432) pooled-p
(use-ssl *default-use-ssl*)
(use-binary nil)
(service "postgres")
(application-name ""))
"Create a new database connection for the given user and the database. Port
will default to 5432, which is where most PostgreSQL servers are running. If
pooled-p is T, a connection will be taken from a pool of connections of this
type, if one is available there, and when the connection is disconnected it
will be put back into this pool instead. use-ssl can be :no, :yes, or :try,
as in open-database, and defaults to the value of *default-use-ssl*."
(cond (pooled-p
(let ((type (list database-name user-name password host port use-ssl
application-name use-binary)))
(or (get-from-pool type)
(let ((connection (cl-postgres:open-database database-name user-name
password host port
use-ssl
service application-name
use-binary)))
#-genera (change-class connection 'pooled-database-connection
:pool-type type)
#+genera (progn
(change-class connection 'pooled-database-connection)
(setf (slot-value connection 'pool-type) type))
connection))))
(t (cl-postgres:open-database database-name user-name password host port
use-ssl service application-name
use-binary))))
(defun connected-p (database)
"Returns a boolean indicating whether the given connection is still connected
to the server."
(cl-postgres:database-open-p database))
(defun connect-toplevel (database-name user-name password host
&key (port 5432) (use-ssl *default-use-ssl*) (application-name "")
use-binary)
"Bind the *database* to a new connection. Use this if you only need one
connection, or if you want a connection for debugging from the REPL."
(when (and *database* (connected-p *database*))
(restart-case (error "Top-level database already connected.")
(replace () :report "Replace it with a new connection."
(disconnect-toplevel))
(leave () :report "Leave it." (return-from connect-toplevel nil))))
(setf *database* (connect database-name user-name password host
:port port :use-ssl use-ssl :application-name application-name
:use-binary use-binary))
(values))
(defgeneric disconnect (database)
(:method ((connection database-connection))
(close-database connection))
(:documentation "Disconnects a normal database connection, or moves a pooled
connection into the pool."))
(defgeneric reconnect (database)
(:method ((database database-connection))
(reopen-database database)
(when *schema-path*
(let ((path *schema-path*))
(set-search-path path))))
(:method ((connection pooled-database-connection))
(error "Can not reconnect a pooled database."))
(:documentation "Reconnect a disconnected database connection. This is not
allowed for pooled connections ― after they are disconnected they might be in
use by some other process, and should no longer be used."))
(defun disconnect-toplevel ()
"Disconnect *database*."
(when (and *database* (connected-p *database*))
(disconnect *database*))
(setf *database* nil))
(defun call-with-connection (spec thunk)
"The functional backend to with-connection. Binds *database* to a new connection
as specified by spec, which should be a list that connect can be applied to, and
runs the zero-argument function given as second argument in the new environment.
When the function returns or throws, the new connection is disconnected."
(let ((*database* (apply #'connect spec)))
(unwind-protect (funcall thunk)
(disconnect *database*))))
(defmacro with-connection (spec &body body)
"Evaluates the body with *database* bound to a connection as specified by spec,
which should be list that connect can be applied to."
`(let ((*database* (apply #'connect ,spec)))
(unwind-protect (progn ,@body)
(disconnect *database*))))
#+postmodern-thread-safe
(defvar *pool-lock*
(bordeaux-threads:make-lock "connection-pool-lock")
"A lock to prevent multiple threads from messing with the connection
pool at the same time.")
(defmacro with-pool-lock (&body body)
"Aquire a lock for the pool when evaluating body \(if thread support
is present)."
#+postmodern-thread-safe
`(bordeaux-threads:with-lock-held (*pool-lock*) ,@body)
#-postmodern-thread-safe
`(progn ,@body))
(defun get-from-pool (type)
"Get a database connection from the specified pool, returns nil if
no connection was available."
(with-pool-lock
(pop (gethash type *connection-pools*))))
(defmethod disconnect ((connection pooled-database-connection))
"Add the connection to the corresponding pool, or drop it when the
pool is full."
(macrolet ((the-pool ()
'(gethash (connection-pool-type connection) *connection-pools* ())))
(when (database-open-p connection)
(with-pool-lock
(if (or (not *max-pool-size*) (< (length (the-pool)) *max-pool-size*))
(push connection (the-pool))
(call-next-method))))
(values)))
(defun clear-connection-pool ()
"Disconnect and remove all connections in the connection pools."
(with-pool-lock
(maphash
(lambda (type connections)
(declare (ignore type))
(dolist (conn connections)
(close-database conn)))
*connection-pools*)
(setf *connection-pools* (make-hash-table :test 'equal))
(values)))
|
eb467ca369bea7161380d69528f741f35975a9a8a209d4084e3490e880f511d6 | awakesecurity/grpc-mqtt | Fixture.hs | # LANGUAGE DerivingVia #
# LANGUAGE GeneralizedNewtypeDeriving #
module Test.Suite.Fixture
( Fixture (Fixture, unFixture),
testFixture,
)
where
--------------------------------------------------------------------------------
import Test.Tasty (TestName, TestTree)
import Test.Tasty.HUnit (Assertion, testCase)
--------------------------------------------------------------------------------
import Relude
--------------------------------------------------------------------------------
import Test.Suite.Config (TestConfig, withTestConfig)
--------------------------------------------------------------------------------
newtype Fixture (a :: Type) :: Type where
Fixture :: {unFixture :: TestConfig -> IO a} -> Fixture a
deriving (Functor, Applicative, Monad)
via ReaderT TestConfig IO
deriving
(MonadIO, MonadReader TestConfig)
via ReaderT TestConfig IO
testFixture :: TestName -> Fixture () -> TestTree
testFixture desc fixture =
withTestConfig \config ->
let prop :: Assertion
prop = unFixture fixture config
in testCase desc prop
| null | https://raw.githubusercontent.com/awakesecurity/grpc-mqtt/fbde6f3fe90e82260469bab922c5ebb9f0b40e95/test/Test/Suite/Fixture.hs | haskell | ------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | # LANGUAGE DerivingVia #
# LANGUAGE GeneralizedNewtypeDeriving #
module Test.Suite.Fixture
( Fixture (Fixture, unFixture),
testFixture,
)
where
import Test.Tasty (TestName, TestTree)
import Test.Tasty.HUnit (Assertion, testCase)
import Relude
import Test.Suite.Config (TestConfig, withTestConfig)
newtype Fixture (a :: Type) :: Type where
Fixture :: {unFixture :: TestConfig -> IO a} -> Fixture a
deriving (Functor, Applicative, Monad)
via ReaderT TestConfig IO
deriving
(MonadIO, MonadReader TestConfig)
via ReaderT TestConfig IO
testFixture :: TestName -> Fixture () -> TestTree
testFixture desc fixture =
withTestConfig \config ->
let prop :: Assertion
prop = unFixture fixture config
in testCase desc prop
|
bea3cc555c4d4232074c2e3ca620573267c4db2657b2d6ee88af5414acc5330c | synduce/Synduce | RootCauseAnalysis.ml | open Base
open Common
open Env
open Lang
open ProblemDefs
open Term
open Utils
module Sub = Configuration.Subconf
module G = ConfGraph
module CO = Config.Optims
let find_arg_with_subterm ~(fvar : variable) ~(sub : term) (t : term) =
let case _ t =
match t.tkind with
| TApp ({ tkind = TVar v; _ }, args) when Variable.equal v fvar ->
(match List.find args ~f:(fun t -> Matching.is_simple_subterm t ~sub) with
| Some t0 -> Some (TermSet.singleton t0)
| None -> None)
| _ -> None
in
Term.reduce ~case ~init:TermSet.empty ~join:Set.union t
;;
(** Looks for a set of applicable rules in prules to rewrite (f fargs) and return
the result of applying the possible rules.
If there is no rule that is applicable, then return an empty list.
*)
let rule_lookup
~(fvar : variable)
~(sub : term)
(ctx : env)
prules
(f : variable)
(fargs : term list)
(memory : VarSet.t ref)
: term list
=
let match_with_pat (_, rule_args, _, rhs) pat first_args to_pat_match =
match Matching.matches_pattern to_pat_match pat with
| Some bindto_map ->
let bindto_list = Map.to_alist bindto_map in
let pat_v, pat_bto = List.unzip bindto_list in
(match List.zip (rule_args @ pat_v) (first_args @ pat_bto) with
| Ok subst ->
let rhs' =
substitution (List.map ~f:(fun (v, t) -> mk_var ctx.ctx v, t) subst) rhs
in
(* Find where to obtain sub from *)
let possible_accessing_calls = find_arg_with_subterm ~fvar ~sub rhs' in
Fmt . (
pf
stdout
" Find % s( .. %a .. ) in % a - > % a@. "
fvar.vname
( pp_term ctx.ctx )
sub
( pp_term ctx.ctx )
rhs '
( list ~sep : comma ( pp_term ctx.ctx ) )
( Set.to_list possible_accessing_calls ) ) ;
pf
stdout
"Find %s(..%a..) in %a -> %a@."
fvar.vname
(pp_term ctx.ctx)
sub
(pp_term ctx.ctx)
rhs'
(list ~sep:comma (pp_term ctx.ctx))
(Set.to_list possible_accessing_calls)); *)
let can_access t =
Set.exists possible_accessing_calls ~f:(fun elt ->
Matching.is_simple_subterm ~sub:t elt)
in
(* Add the variable to obtain sub from in memory. *)
List.iter subst ~f:(fun (v, t) ->
if can_access t then memory := Set.add !memory v);
Some rhs'
| _ -> None)
| None -> None
in
let f (nt, rule_args, rule_pat, rhs) : term option =
if Variable.(nt = f)
then (
match rule_pat with
(* We have a pattern, try to match it. *)
| Some pat ->
Separate last argument and the rest . Last argument is pattern - matched .
(match List.last fargs, List.drop_last fargs with
| Some to_pat_match, Some first_args ->
let f = match_with_pat (nt, rule_args, rule_pat, rhs) pat first_args in
let cond_pat = Reduce.CondTree.of_term to_pat_match in
Reduce.(Option.map ~f:CondTree.to_term CondTree.(all_or_none (map ~f cond_pat)))
| _ -> None)
(* Pattern is empty. Simple substitution. *)
| None ->
(match List.zip rule_args fargs with
| Ok subst ->
Some (substitution (List.map ~f:(fun (v, t) -> mk_var ctx.ctx v, t) subst) rhs)
| _ -> None))
else None
in
second (List.unzip (Map.to_alist (Map.filter_map prules ~f)))
;;
(**
reduce_term reduces a term using only the lambda-calculus
*)
let rec reduce_term_with_lookup
?(projecting = false)
?(unboxing = false)
~(memory : VarSet.t ref)
~(ctx : env)
~(fvar : variable)
~(sub : term)
(t : term)
: term
=
let one_step t =
let rstep = ref false in
let case f t =
let x =
match t.tkind with
| TApp (func, args) ->
let func' = f func in
let args' = List.map ~f args in
(match Reduce.resolve_func ctx.functions ctx.ctx func' with
| FRFun (fpatterns, body) ->
(match ctx >- Analysis.subst_args fpatterns args' with
| Ok (remaining_patterns, subst) ->
(* If there are remaining patterns the application is partial. *)
(match remaining_patterns with
| [] -> Some (substitution subst body)
| rem -> Some (mk_fun ctx.ctx rem (substitution subst body)))
| Error _ -> None)
| FRPmrs pm ->
(match args' with
| [ tp ] -> Some (f (reduce_pmrs_with_lookup ~memory ~ctx ~fvar ~sub pm tp))
PMRS are defined only with one argument for now .
| FRNonT p -> Some (pmrs_ ~memory ~ctx ~fvar ~sub p (mk_app func' args'))
| FRUnknown -> Some (mk_app func' args'))
| TFun ([], body) -> Some (f body)
| TIte (c, tt, tf) ->
(match c.tkind with
(* Resolve constants *)
| TConst Constant.CFalse -> Some (f tf)
| TConst Constant.CTrue -> Some (f tt)
Distribute ite on tuples
| _ ->
(match tt.tkind, tf.tkind with
| TTup tlt, TTup tlf ->
(match List.zip tlt tlf with
| Ok zip ->
Some
(mk_tup ctx.ctx (List.map zip ~f:(fun (tt', tf') -> mk_ite c tt' tf')))
| Unequal_lengths -> None)
| _, _ -> None))
| TSel (t, i) ->
(match f t with
| { tkind = TTup tl; _ } -> Some (List.nth_exn tl i)
| _ -> None)
| TMatch (t, cases) ->
(match
List.filter_opt
(List.map
~f:(fun (p, t') ->
Option.map ~f:(fun m -> m, t') (Matching.matches_pattern t p))
cases)
with
| [] -> None
| (subst_map, rhs_t) :: _ ->
Some (substitution (VarMap.to_subst ctx.ctx subst_map) rhs_t))
| TBox t -> if unboxing then Some t else None
| TFun _ | TVar _ | TTup _ | TBin _ | TUn _ | TConst _ | TData _ -> None
in
match x with
| Some x ->
rstep := true;
Some x
| None -> None
in
( transform
~case
(if projecting then Reduce.project_irreducible_terms ctx.ctx t else t)
, !rstep )
in
Reduce.until_irreducible one_step t
and pmrs_
~(ctx : env)
~(fvar : variable)
~(sub : term)
~(memory : VarSet.t ref)
(prog : PMRS.t)
(input : term)
=
let one_step t0 =
let rstep = ref false in
let rewrite_rule tm =
match tm.tkind with
| TApp ({ tkind = TVar f; _ }, fargs) ->
(match rule_lookup ~fvar ~sub ctx prog.prules f fargs memory with
| [] -> tm (* No rule matches *)
| hd :: _ ->
Only select first match .
rstep := true;
hd)
| _ -> tm
in
let t0' = rewrite_with rewrite_rule t0 in
t0', !rstep
in
Reduce.until_irreducible one_step input
and reduce_pmrs_with_lookup
~(ctx : env)
~(fvar : variable)
~(sub : term)
~(memory : VarSet.t ref)
(prog : PMRS.t)
(input : term)
=
let f_input = mk_app (mk_var ctx.ctx prog.pmain_symb) [ input ] in
reduce_term_with_lookup
~memory
~ctx
~fvar
~sub
(pmrs_ ~ctx ~fvar ~sub ~memory prog f_input)
;;
let find_req_arg
~(ctx : env)
~(g : PMRS.t)
~(sub : term)
~(xi : variable)
(s : G.state)
(_ : Sub.t)
(input : term)
=
Fmt . (
pf
stdout
" @[REQ : on input @[%a@ ] , % s should access@;@[%a@]@]@. "
( Term.pp_term ctx.ctx )
input
xi.vname
( Term.pp_term ctx.ctx )
sub ) ;
pf
stdout
"@[REQ: on input @[%a@], %s should access@;@[%a@]@]@."
(Term.pp_term ctx.ctx)
input
xi.vname
(Term.pp_term ctx.ctx)
sub); *)
let gmax, ctx = Configuration.apply_configuration ~ctx s.st_super g in
let memory = ref VarSet.empty in
(* Populate memory with call to reduction with lookup *)
let _ = reduce_pmrs_with_lookup ~memory ~ctx ~fvar:xi ~sub gmax input in
Fmt.(pf stdout " memory : % a@. " ( list ( Variable.pp ctx.ctx ) ) ( Set.to_list ! memory ) ) ;
match Map.find s.st_super xi with
| Some arglist ->
List.filter_mapi arglist ~f:(fun i arg ->
if not (Set.are_disjoint (ctx >- Analysis.free_variables arg) !memory)
Fmt.(pf stdout " Add % i,%i.@. " xi.vid i ) ;
Some (xi.vid, i)
else None)
| None -> failwith "Not expected."
;;
(* ============================================================================================= *)
(* OTHER SUBROUTINES *)
(* ============================================================================================= *)
let analyze_witness_list
~(ctx : env)
(s : G.state)
(c : Sub.t)
(wl : unrealizability_witness list)
=
TODO not implemented
let _ = ctx, s, c, wl in
()
;;
failwith " DEBUG "
let analyze_reqs
~(ctx : env)
~(g : PMRS.t)
(s : G.state)
(c : Sub.t)
(_ : unrealizability_witness list)
(reqs : (term * variable * term) list)
: (int * int) list
=
List.dedup_and_sort
~compare:Poly.compare
(List.concat_map reqs ~f:(fun (t_input, xi_v, t_req) ->
find_req_arg ~ctx ~g ~xi:xi_v ~sub:t_req s c t_input))
;;
let analyze_witnesses
~(ctx : env)
~(g : PMRS.t)
(s : G.state)
(c : Sub.t)
(r : repair)
(wl : unrealizability_witness list)
=
match r with
| Lift ->
(* Lift repair should be handled by the single-configuration solver. *)
()
| AddRecursiveCalls reqs ->
(* Local root causing has identified missing information.
This missing information must be related to precise recursive calls or
scalar arguments.
*)
(match analyze_reqs ~g ~ctx s c wl reqs with
| _ :: _ as l ->
let new_conf =
List.fold l ~init:c ~f:(fun new_c (xi_id, arg_id) ->
Sub.apply_diff (true, xi_id, arg_id) new_c)
in
G.add_next_candidate ~origin:c s new_conf
| [] -> ())
| _ -> analyze_witness_list ~ctx s c wl
;;
| null | https://raw.githubusercontent.com/synduce/Synduce/42d970faa863365f10531b19945cbb5cfb70f134/src/confsearch/RootCauseAnalysis.ml | ocaml | * Looks for a set of applicable rules in prules to rewrite (f fargs) and return
the result of applying the possible rules.
If there is no rule that is applicable, then return an empty list.
Find where to obtain sub from
Add the variable to obtain sub from in memory.
We have a pattern, try to match it.
Pattern is empty. Simple substitution.
*
reduce_term reduces a term using only the lambda-calculus
If there are remaining patterns the application is partial.
Resolve constants
No rule matches
Populate memory with call to reduction with lookup
=============================================================================================
OTHER SUBROUTINES
=============================================================================================
Lift repair should be handled by the single-configuration solver.
Local root causing has identified missing information.
This missing information must be related to precise recursive calls or
scalar arguments.
| open Base
open Common
open Env
open Lang
open ProblemDefs
open Term
open Utils
module Sub = Configuration.Subconf
module G = ConfGraph
module CO = Config.Optims
let find_arg_with_subterm ~(fvar : variable) ~(sub : term) (t : term) =
let case _ t =
match t.tkind with
| TApp ({ tkind = TVar v; _ }, args) when Variable.equal v fvar ->
(match List.find args ~f:(fun t -> Matching.is_simple_subterm t ~sub) with
| Some t0 -> Some (TermSet.singleton t0)
| None -> None)
| _ -> None
in
Term.reduce ~case ~init:TermSet.empty ~join:Set.union t
;;
let rule_lookup
~(fvar : variable)
~(sub : term)
(ctx : env)
prules
(f : variable)
(fargs : term list)
(memory : VarSet.t ref)
: term list
=
let match_with_pat (_, rule_args, _, rhs) pat first_args to_pat_match =
match Matching.matches_pattern to_pat_match pat with
| Some bindto_map ->
let bindto_list = Map.to_alist bindto_map in
let pat_v, pat_bto = List.unzip bindto_list in
(match List.zip (rule_args @ pat_v) (first_args @ pat_bto) with
| Ok subst ->
let rhs' =
substitution (List.map ~f:(fun (v, t) -> mk_var ctx.ctx v, t) subst) rhs
in
let possible_accessing_calls = find_arg_with_subterm ~fvar ~sub rhs' in
Fmt . (
pf
stdout
" Find % s( .. %a .. ) in % a - > % a@. "
fvar.vname
( pp_term ctx.ctx )
sub
( pp_term ctx.ctx )
rhs '
( list ~sep : comma ( pp_term ctx.ctx ) )
( Set.to_list possible_accessing_calls ) ) ;
pf
stdout
"Find %s(..%a..) in %a -> %a@."
fvar.vname
(pp_term ctx.ctx)
sub
(pp_term ctx.ctx)
rhs'
(list ~sep:comma (pp_term ctx.ctx))
(Set.to_list possible_accessing_calls)); *)
let can_access t =
Set.exists possible_accessing_calls ~f:(fun elt ->
Matching.is_simple_subterm ~sub:t elt)
in
List.iter subst ~f:(fun (v, t) ->
if can_access t then memory := Set.add !memory v);
Some rhs'
| _ -> None)
| None -> None
in
let f (nt, rule_args, rule_pat, rhs) : term option =
if Variable.(nt = f)
then (
match rule_pat with
| Some pat ->
Separate last argument and the rest . Last argument is pattern - matched .
(match List.last fargs, List.drop_last fargs with
| Some to_pat_match, Some first_args ->
let f = match_with_pat (nt, rule_args, rule_pat, rhs) pat first_args in
let cond_pat = Reduce.CondTree.of_term to_pat_match in
Reduce.(Option.map ~f:CondTree.to_term CondTree.(all_or_none (map ~f cond_pat)))
| _ -> None)
| None ->
(match List.zip rule_args fargs with
| Ok subst ->
Some (substitution (List.map ~f:(fun (v, t) -> mk_var ctx.ctx v, t) subst) rhs)
| _ -> None))
else None
in
second (List.unzip (Map.to_alist (Map.filter_map prules ~f)))
;;
let rec reduce_term_with_lookup
?(projecting = false)
?(unboxing = false)
~(memory : VarSet.t ref)
~(ctx : env)
~(fvar : variable)
~(sub : term)
(t : term)
: term
=
let one_step t =
let rstep = ref false in
let case f t =
let x =
match t.tkind with
| TApp (func, args) ->
let func' = f func in
let args' = List.map ~f args in
(match Reduce.resolve_func ctx.functions ctx.ctx func' with
| FRFun (fpatterns, body) ->
(match ctx >- Analysis.subst_args fpatterns args' with
| Ok (remaining_patterns, subst) ->
(match remaining_patterns with
| [] -> Some (substitution subst body)
| rem -> Some (mk_fun ctx.ctx rem (substitution subst body)))
| Error _ -> None)
| FRPmrs pm ->
(match args' with
| [ tp ] -> Some (f (reduce_pmrs_with_lookup ~memory ~ctx ~fvar ~sub pm tp))
PMRS are defined only with one argument for now .
| FRNonT p -> Some (pmrs_ ~memory ~ctx ~fvar ~sub p (mk_app func' args'))
| FRUnknown -> Some (mk_app func' args'))
| TFun ([], body) -> Some (f body)
| TIte (c, tt, tf) ->
(match c.tkind with
| TConst Constant.CFalse -> Some (f tf)
| TConst Constant.CTrue -> Some (f tt)
Distribute ite on tuples
| _ ->
(match tt.tkind, tf.tkind with
| TTup tlt, TTup tlf ->
(match List.zip tlt tlf with
| Ok zip ->
Some
(mk_tup ctx.ctx (List.map zip ~f:(fun (tt', tf') -> mk_ite c tt' tf')))
| Unequal_lengths -> None)
| _, _ -> None))
| TSel (t, i) ->
(match f t with
| { tkind = TTup tl; _ } -> Some (List.nth_exn tl i)
| _ -> None)
| TMatch (t, cases) ->
(match
List.filter_opt
(List.map
~f:(fun (p, t') ->
Option.map ~f:(fun m -> m, t') (Matching.matches_pattern t p))
cases)
with
| [] -> None
| (subst_map, rhs_t) :: _ ->
Some (substitution (VarMap.to_subst ctx.ctx subst_map) rhs_t))
| TBox t -> if unboxing then Some t else None
| TFun _ | TVar _ | TTup _ | TBin _ | TUn _ | TConst _ | TData _ -> None
in
match x with
| Some x ->
rstep := true;
Some x
| None -> None
in
( transform
~case
(if projecting then Reduce.project_irreducible_terms ctx.ctx t else t)
, !rstep )
in
Reduce.until_irreducible one_step t
and pmrs_
~(ctx : env)
~(fvar : variable)
~(sub : term)
~(memory : VarSet.t ref)
(prog : PMRS.t)
(input : term)
=
let one_step t0 =
let rstep = ref false in
let rewrite_rule tm =
match tm.tkind with
| TApp ({ tkind = TVar f; _ }, fargs) ->
(match rule_lookup ~fvar ~sub ctx prog.prules f fargs memory with
| hd :: _ ->
Only select first match .
rstep := true;
hd)
| _ -> tm
in
let t0' = rewrite_with rewrite_rule t0 in
t0', !rstep
in
Reduce.until_irreducible one_step input
and reduce_pmrs_with_lookup
~(ctx : env)
~(fvar : variable)
~(sub : term)
~(memory : VarSet.t ref)
(prog : PMRS.t)
(input : term)
=
let f_input = mk_app (mk_var ctx.ctx prog.pmain_symb) [ input ] in
reduce_term_with_lookup
~memory
~ctx
~fvar
~sub
(pmrs_ ~ctx ~fvar ~sub ~memory prog f_input)
;;
let find_req_arg
~(ctx : env)
~(g : PMRS.t)
~(sub : term)
~(xi : variable)
(s : G.state)
(_ : Sub.t)
(input : term)
=
Fmt . (
pf
stdout
" @[REQ : on input @[%a@ ] , % s should access@;@[%a@]@]@. "
( Term.pp_term ctx.ctx )
input
xi.vname
( Term.pp_term ctx.ctx )
sub ) ;
pf
stdout
"@[REQ: on input @[%a@], %s should access@;@[%a@]@]@."
(Term.pp_term ctx.ctx)
input
xi.vname
(Term.pp_term ctx.ctx)
sub); *)
let gmax, ctx = Configuration.apply_configuration ~ctx s.st_super g in
let memory = ref VarSet.empty in
let _ = reduce_pmrs_with_lookup ~memory ~ctx ~fvar:xi ~sub gmax input in
Fmt.(pf stdout " memory : % a@. " ( list ( Variable.pp ctx.ctx ) ) ( Set.to_list ! memory ) ) ;
match Map.find s.st_super xi with
| Some arglist ->
List.filter_mapi arglist ~f:(fun i arg ->
if not (Set.are_disjoint (ctx >- Analysis.free_variables arg) !memory)
Fmt.(pf stdout " Add % i,%i.@. " xi.vid i ) ;
Some (xi.vid, i)
else None)
| None -> failwith "Not expected."
;;
let analyze_witness_list
~(ctx : env)
(s : G.state)
(c : Sub.t)
(wl : unrealizability_witness list)
=
TODO not implemented
let _ = ctx, s, c, wl in
()
;;
failwith " DEBUG "
let analyze_reqs
~(ctx : env)
~(g : PMRS.t)
(s : G.state)
(c : Sub.t)
(_ : unrealizability_witness list)
(reqs : (term * variable * term) list)
: (int * int) list
=
List.dedup_and_sort
~compare:Poly.compare
(List.concat_map reqs ~f:(fun (t_input, xi_v, t_req) ->
find_req_arg ~ctx ~g ~xi:xi_v ~sub:t_req s c t_input))
;;
let analyze_witnesses
~(ctx : env)
~(g : PMRS.t)
(s : G.state)
(c : Sub.t)
(r : repair)
(wl : unrealizability_witness list)
=
match r with
| Lift ->
()
| AddRecursiveCalls reqs ->
(match analyze_reqs ~g ~ctx s c wl reqs with
| _ :: _ as l ->
let new_conf =
List.fold l ~init:c ~f:(fun new_c (xi_id, arg_id) ->
Sub.apply_diff (true, xi_id, arg_id) new_c)
in
G.add_next_candidate ~origin:c s new_conf
| [] -> ())
| _ -> analyze_witness_list ~ctx s c wl
;;
|
b0766cd56d7dd611949f7e3c06c20480228554fb98e2de018571132a4aa9ad87 | ezyang/reflex-backpack | Basics.hs | # LANGUAGE CPP #
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
{-# LANGUAGE GADTs #-}
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RoleAnnotations #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
#ifdef USE_REFLEX_OPTIMIZER
{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
#endif
| This module provides the interface for hosting ' Reflex ' engines . This
-- should only be necessary if you're writing a binding or some other library
-- that provides a core event loop.
module Reflex.Host.Basics
( module Reflex.Host.Sig
, MonadSubscribeEvent (..)
, MonadReadEvent (..)
, MonadReflexCreateTrigger (..)
, MonadReflexHost (..)
, fireEvents
, newEventWithTriggerRef
, fireEventRef
, fireEventRefAndRead
) where
import Reflex . Class
import Reflex.Basics
import Reflex.Host.Sig
import Control.Applicative
import Control.Monad
import Control.Monad.Identity
import Control.Monad.Ref
import Control.Monad.Trans
import Control.Monad.Trans.Cont (ContT ())
import Control.Monad.Trans.Except (ExceptT ())
import Control.Monad.Trans.Reader (ReaderT ())
import Control.Monad.Trans.RWS (RWST ())
import Control.Monad.Trans.State (StateT ())
import qualified Control.Monad.Trans.State.Strict as Strict
import Control.Monad.Trans.Writer (WriterT ())
import Data.Dependent.Sum (DSum (..))
import Data.GADT.Compare
import Data.Monoid
Note : this import must come last to silence warnings from AMP
import Prelude hiding (foldl, mapM, mapM_, sequence, sequence_)
-- | Monad in which Events can be 'subscribed'. This forces all underlying
-- event sources to be initialized, so that the event will fire whenever it
-- ought to. Events must be subscribed before they are read using readEvent
class (HasTimeline t, Monad m) => MonadSubscribeEvent t m | m -> t where
-- | Subscribe to an event and set it up if needed.
--
-- This function will create a new 'EventHandle' from an 'Event'. This handle
-- may then be used via 'readEvent' in the read callback of
-- 'fireEventsAndRead'.
--
-- If the event wasn't subscribed to before (either manually or through a
-- dependent event or behavior) then this function will cause the event and
-- all dependencies of this event to be set up. For example, if the event was
-- created by 'newEventWithTrigger', then it's callback will be executed.
--
-- It's safe to call this function multiple times.
subscribeEvent :: Event t a -> m (EventHandle t a)
instance HasTimeline t => MonadSubscribeEvent t (HostFrame t) where
subscribeEvent = subscribeEventHostFrame
-- | A monad where new events feed from external sources can be created.
class (Applicative m, Monad m) => MonadReflexCreateTrigger t m | m -> t where
-- | Creates a root 'Event' (one that is not based on any other event).
--
-- When a subscriber first subscribes to an event (building another event that
-- depends on the subscription) the given callback function is run and passed
a trigger . The callback function can then set up the event source in IO .
-- After this is done, the callback function must return an accompanying
-- teardown action.
--
-- Any time between setup and teardown the trigger can be used to fire the
-- event, by passing it to 'fireEventsAndRead'.
--
-- Note: An event may be set up multiple times. So after the teardown action
-- is executed, the event may still be set up again in the future.
newEventWithTrigger :: (EventTrigger t a -> IO (IO ())) -> m (Event t a)
newFanEventWithTrigger :: GCompare k => (forall a. k a -> EventTrigger t a -> IO (IO ())) -> m (EventSelector t k)
instance HasTimeline t => MonadReflexCreateTrigger t (HostFrame t) where
newEventWithTrigger = newEventWithTriggerHostFrame
newFanEventWithTrigger = newFanEventWithTriggerHostFrame
-- | Monad that allows to read events' values.
class (HasTimeline t, Applicative m, Monad m) => MonadReadEvent t m | m -> t where
-- | Read the value of an 'Event' from an 'EventHandle' (created by calling
-- 'subscribeEvent').
--
After event propagation is done , all events can be in two states : either
-- they are firing with some value or they are not firing. In the former
case , this function returns @Just act@ , where @act@ in an action to read
-- the current value of the event. In the latter case, the function returns
@Nothing@.
--
-- This function is normally used in the calllback for 'fireEventsAndRead'.
readEvent :: EventHandle t a -> m (Maybe (m a))
| ' MonadReflexHost ' designates monads that can run reflex frames .
class ( HasTimeline t
, MonadReflexCreateTrigger t m
, MonadSubscribeEvent t m
, MonadReadEvent t (ReadPhase m)
, MonadSample (Impl t) (ReadPhase m)
, MonadHold (Impl t) (ReadPhase m)
) => MonadReflexHost t m | m -> t where
type ReadPhase m :: * -> *
-- | Propagate some events firings and read the values of events afterwards.
--
-- This function will create a new frame to fire the given events. It will
-- then update all dependent events and behaviors. After that is done, the
-- given callback is executed which allows to read the final values of events
-- and check whether they have fired in this frame or not.
--
-- All events that are given are fired at the same time.
--
-- This function is typically used in the main loop of a reflex framework
-- implementation. The main loop waits for external events to happen (such as
-- keyboard input or a mouse click) and then fires the corresponding events
-- using this function. The read callback can be used to read output events
-- and perform a corresponding response action to the external event.
fireEventsAndRead :: [DSum (EventTrigger t) Identity] -> ReadPhase m a -> m a
-- | Run a frame without any events firing.
--
-- This function should be used when you want to use 'sample' and 'hold' when
-- no events are currently firing. Using this function in that case can
-- improve performance, since the implementation can assume that no events are
-- firing when 'sample' or 'hold' are called.
--
-- This function is commonly used to set up the basic event network when the
-- application starts up.
runHostFrame :: HostFrame t a -> m a
-- | Like 'fireEventsAndRead', but without reading any events.
fireEvents :: MonadReflexHost t m => [DSum (EventTrigger t) Identity] -> m ()
fireEvents dm = fireEventsAndRead dm $ return ()
# INLINE fireEvents #
-- | Create a new event and store its trigger in an 'IORef' while it's active.
--
An event is only active between the set up ( when it 's first subscribed to )
and the teardown phases ( when noboby is subscribing the event anymore ) . This
-- function returns an Event and an 'IORef'. As long as the event is active, the
-- 'IORef' will contain 'Just' the event trigger to trigger this event. When the
-- event is not active, the 'IORef' will contain 'Nothing'. This allows event
-- sources to be more efficient, since they don't need to produce events when
-- nobody is listening.
newEventWithTriggerRef :: (MonadReflexCreateTrigger t m, MonadRef m, Ref m ~ Ref IO) => m (Event t a, Ref m (Maybe (EventTrigger t a)))
newEventWithTriggerRef = do
rt <- newRef Nothing
e <- newEventWithTrigger $ \t -> do
writeRef rt $ Just t
return $ writeRef rt Nothing
return (e, rt)
# INLINE newEventWithTriggerRef #
-- | Fire the given trigger if it is not 'Nothing'.
fireEventRef :: (MonadReflexHost t m, MonadRef m, Ref m ~ Ref IO) => Ref m (Maybe (EventTrigger t a)) -> a -> m ()
fireEventRef mtRef input = do
mt <- readRef mtRef
case mt of
Nothing -> return ()
Just trigger -> fireEvents [trigger :=> Identity input]
-- | Fire the given trigger if it is not 'Nothing', and read from the given
-- 'EventHandle'.
fireEventRefAndRead :: (MonadReflexHost t m, MonadRef m, Ref m ~ Ref IO) => Ref m (Maybe (EventTrigger t a)) -> a -> EventHandle t b -> m (Maybe b)
fireEventRefAndRead mtRef input e = do
mt <- readRef mtRef
case mt of
Nothing -> return Nothing -- Since we aren't firing the input, the output can't fire
Just trigger -> fireEventsAndRead [trigger :=> Identity input] $ do
mGetValue <- readEvent e
case mGetValue of
Nothing -> return Nothing
Just getValue -> fmap Just getValue
--------------------------------------------------------------------------------
-- Instances
--------------------------------------------------------------------------------
instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ReaderT r m) where
newEventWithTrigger = lift . newEventWithTrigger
newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ReaderT r m) where
subscribeEvent = lift . subscribeEvent
instance MonadReflexHost t m => MonadReflexHost t (ReaderT r m) where
type ReadPhase (ReaderT r m) = ReadPhase m
fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
runHostFrame = lift . runHostFrame
instance (MonadReflexCreateTrigger t m, Monoid w) => MonadReflexCreateTrigger t (WriterT w m) where
newEventWithTrigger = lift . newEventWithTrigger
newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
instance (MonadSubscribeEvent t m, Monoid w) => MonadSubscribeEvent t (WriterT w m) where
subscribeEvent = lift . subscribeEvent
instance (MonadReflexHost t m, Monoid w) => MonadReflexHost t (WriterT w m) where
type ReadPhase (WriterT w m) = ReadPhase m
fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
runHostFrame = lift . runHostFrame
instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (StateT s m) where
newEventWithTrigger = lift . newEventWithTrigger
newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
instance MonadSubscribeEvent t m => MonadSubscribeEvent t (StateT r m) where
subscribeEvent = lift . subscribeEvent
instance MonadReflexHost t m => MonadReflexHost t (StateT s m) where
type ReadPhase (StateT s m) = ReadPhase m
fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
runHostFrame = lift . runHostFrame
instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (Strict.StateT s m) where
newEventWithTrigger = lift . newEventWithTrigger
newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
instance MonadSubscribeEvent t m => MonadSubscribeEvent t (Strict.StateT r m) where
subscribeEvent = lift . subscribeEvent
instance MonadReflexHost t m => MonadReflexHost t (Strict.StateT s m) where
type ReadPhase (Strict.StateT s m) = ReadPhase m
fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
runHostFrame = lift . runHostFrame
instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ContT r m) where
newEventWithTrigger = lift . newEventWithTrigger
newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ContT r m) where
subscribeEvent = lift . subscribeEvent
instance MonadReflexHost t m => MonadReflexHost t (ContT r m) where
type ReadPhase (ContT r m) = ReadPhase m
fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
runHostFrame = lift . runHostFrame
instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ExceptT e m) where
newEventWithTrigger = lift . newEventWithTrigger
newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ExceptT r m) where
subscribeEvent = lift . subscribeEvent
instance MonadReflexHost t m => MonadReflexHost t (ExceptT e m) where
type ReadPhase (ExceptT e m) = ReadPhase m
fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
runHostFrame = lift . runHostFrame
instance (MonadReflexCreateTrigger t m, Monoid w) => MonadReflexCreateTrigger t (RWST r w s m) where
newEventWithTrigger = lift . newEventWithTrigger
newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
instance (MonadSubscribeEvent t m, Monoid w) => MonadSubscribeEvent t (RWST r w s m) where
subscribeEvent = lift . subscribeEvent
instance (MonadReflexHost t m, Monoid w) => MonadReflexHost t (RWST r w s m) where
type ReadPhase (RWST r w s m) = ReadPhase m
fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
runHostFrame = lift . runHostFrame
| null | https://raw.githubusercontent.com/ezyang/reflex-backpack/247898fde872d8909392ebe2539f4623c7449067/host/Reflex/Host/Basics.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE RankNTypes #
# OPTIONS_GHC -fplugin=Reflex.Optimizer #
should only be necessary if you're writing a binding or some other library
that provides a core event loop.
| Monad in which Events can be 'subscribed'. This forces all underlying
event sources to be initialized, so that the event will fire whenever it
ought to. Events must be subscribed before they are read using readEvent
| Subscribe to an event and set it up if needed.
This function will create a new 'EventHandle' from an 'Event'. This handle
may then be used via 'readEvent' in the read callback of
'fireEventsAndRead'.
If the event wasn't subscribed to before (either manually or through a
dependent event or behavior) then this function will cause the event and
all dependencies of this event to be set up. For example, if the event was
created by 'newEventWithTrigger', then it's callback will be executed.
It's safe to call this function multiple times.
| A monad where new events feed from external sources can be created.
| Creates a root 'Event' (one that is not based on any other event).
When a subscriber first subscribes to an event (building another event that
depends on the subscription) the given callback function is run and passed
After this is done, the callback function must return an accompanying
teardown action.
Any time between setup and teardown the trigger can be used to fire the
event, by passing it to 'fireEventsAndRead'.
Note: An event may be set up multiple times. So after the teardown action
is executed, the event may still be set up again in the future.
| Monad that allows to read events' values.
| Read the value of an 'Event' from an 'EventHandle' (created by calling
'subscribeEvent').
they are firing with some value or they are not firing. In the former
the current value of the event. In the latter case, the function returns
This function is normally used in the calllback for 'fireEventsAndRead'.
| Propagate some events firings and read the values of events afterwards.
This function will create a new frame to fire the given events. It will
then update all dependent events and behaviors. After that is done, the
given callback is executed which allows to read the final values of events
and check whether they have fired in this frame or not.
All events that are given are fired at the same time.
This function is typically used in the main loop of a reflex framework
implementation. The main loop waits for external events to happen (such as
keyboard input or a mouse click) and then fires the corresponding events
using this function. The read callback can be used to read output events
and perform a corresponding response action to the external event.
| Run a frame without any events firing.
This function should be used when you want to use 'sample' and 'hold' when
no events are currently firing. Using this function in that case can
improve performance, since the implementation can assume that no events are
firing when 'sample' or 'hold' are called.
This function is commonly used to set up the basic event network when the
application starts up.
| Like 'fireEventsAndRead', but without reading any events.
| Create a new event and store its trigger in an 'IORef' while it's active.
function returns an Event and an 'IORef'. As long as the event is active, the
'IORef' will contain 'Just' the event trigger to trigger this event. When the
event is not active, the 'IORef' will contain 'Nothing'. This allows event
sources to be more efficient, since they don't need to produce events when
nobody is listening.
| Fire the given trigger if it is not 'Nothing'.
| Fire the given trigger if it is not 'Nothing', and read from the given
'EventHandle'.
Since we aren't firing the input, the output can't fire
------------------------------------------------------------------------------
Instances
------------------------------------------------------------------------------ | # LANGUAGE CPP #
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE RoleAnnotations #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
#ifdef USE_REFLEX_OPTIMIZER
#endif
| This module provides the interface for hosting ' Reflex ' engines . This
module Reflex.Host.Basics
( module Reflex.Host.Sig
, MonadSubscribeEvent (..)
, MonadReadEvent (..)
, MonadReflexCreateTrigger (..)
, MonadReflexHost (..)
, fireEvents
, newEventWithTriggerRef
, fireEventRef
, fireEventRefAndRead
) where
import Reflex . Class
import Reflex.Basics
import Reflex.Host.Sig
import Control.Applicative
import Control.Monad
import Control.Monad.Identity
import Control.Monad.Ref
import Control.Monad.Trans
import Control.Monad.Trans.Cont (ContT ())
import Control.Monad.Trans.Except (ExceptT ())
import Control.Monad.Trans.Reader (ReaderT ())
import Control.Monad.Trans.RWS (RWST ())
import Control.Monad.Trans.State (StateT ())
import qualified Control.Monad.Trans.State.Strict as Strict
import Control.Monad.Trans.Writer (WriterT ())
import Data.Dependent.Sum (DSum (..))
import Data.GADT.Compare
import Data.Monoid
Note : this import must come last to silence warnings from AMP
import Prelude hiding (foldl, mapM, mapM_, sequence, sequence_)
class (HasTimeline t, Monad m) => MonadSubscribeEvent t m | m -> t where
subscribeEvent :: Event t a -> m (EventHandle t a)
instance HasTimeline t => MonadSubscribeEvent t (HostFrame t) where
subscribeEvent = subscribeEventHostFrame
class (Applicative m, Monad m) => MonadReflexCreateTrigger t m | m -> t where
a trigger . The callback function can then set up the event source in IO .
newEventWithTrigger :: (EventTrigger t a -> IO (IO ())) -> m (Event t a)
newFanEventWithTrigger :: GCompare k => (forall a. k a -> EventTrigger t a -> IO (IO ())) -> m (EventSelector t k)
instance HasTimeline t => MonadReflexCreateTrigger t (HostFrame t) where
newEventWithTrigger = newEventWithTriggerHostFrame
newFanEventWithTrigger = newFanEventWithTriggerHostFrame
class (HasTimeline t, Applicative m, Monad m) => MonadReadEvent t m | m -> t where
After event propagation is done , all events can be in two states : either
case , this function returns @Just act@ , where @act@ in an action to read
@Nothing@.
readEvent :: EventHandle t a -> m (Maybe (m a))
| ' MonadReflexHost ' designates monads that can run reflex frames .
class ( HasTimeline t
, MonadReflexCreateTrigger t m
, MonadSubscribeEvent t m
, MonadReadEvent t (ReadPhase m)
, MonadSample (Impl t) (ReadPhase m)
, MonadHold (Impl t) (ReadPhase m)
) => MonadReflexHost t m | m -> t where
type ReadPhase m :: * -> *
fireEventsAndRead :: [DSum (EventTrigger t) Identity] -> ReadPhase m a -> m a
runHostFrame :: HostFrame t a -> m a
fireEvents :: MonadReflexHost t m => [DSum (EventTrigger t) Identity] -> m ()
fireEvents dm = fireEventsAndRead dm $ return ()
# INLINE fireEvents #
An event is only active between the set up ( when it 's first subscribed to )
and the teardown phases ( when noboby is subscribing the event anymore ) . This
newEventWithTriggerRef :: (MonadReflexCreateTrigger t m, MonadRef m, Ref m ~ Ref IO) => m (Event t a, Ref m (Maybe (EventTrigger t a)))
newEventWithTriggerRef = do
rt <- newRef Nothing
e <- newEventWithTrigger $ \t -> do
writeRef rt $ Just t
return $ writeRef rt Nothing
return (e, rt)
# INLINE newEventWithTriggerRef #
fireEventRef :: (MonadReflexHost t m, MonadRef m, Ref m ~ Ref IO) => Ref m (Maybe (EventTrigger t a)) -> a -> m ()
fireEventRef mtRef input = do
mt <- readRef mtRef
case mt of
Nothing -> return ()
Just trigger -> fireEvents [trigger :=> Identity input]
fireEventRefAndRead :: (MonadReflexHost t m, MonadRef m, Ref m ~ Ref IO) => Ref m (Maybe (EventTrigger t a)) -> a -> EventHandle t b -> m (Maybe b)
fireEventRefAndRead mtRef input e = do
mt <- readRef mtRef
case mt of
Just trigger -> fireEventsAndRead [trigger :=> Identity input] $ do
mGetValue <- readEvent e
case mGetValue of
Nothing -> return Nothing
Just getValue -> fmap Just getValue
instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ReaderT r m) where
newEventWithTrigger = lift . newEventWithTrigger
newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ReaderT r m) where
subscribeEvent = lift . subscribeEvent
instance MonadReflexHost t m => MonadReflexHost t (ReaderT r m) where
type ReadPhase (ReaderT r m) = ReadPhase m
fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
runHostFrame = lift . runHostFrame
instance (MonadReflexCreateTrigger t m, Monoid w) => MonadReflexCreateTrigger t (WriterT w m) where
newEventWithTrigger = lift . newEventWithTrigger
newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
instance (MonadSubscribeEvent t m, Monoid w) => MonadSubscribeEvent t (WriterT w m) where
subscribeEvent = lift . subscribeEvent
instance (MonadReflexHost t m, Monoid w) => MonadReflexHost t (WriterT w m) where
type ReadPhase (WriterT w m) = ReadPhase m
fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
runHostFrame = lift . runHostFrame
instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (StateT s m) where
newEventWithTrigger = lift . newEventWithTrigger
newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
instance MonadSubscribeEvent t m => MonadSubscribeEvent t (StateT r m) where
subscribeEvent = lift . subscribeEvent
instance MonadReflexHost t m => MonadReflexHost t (StateT s m) where
type ReadPhase (StateT s m) = ReadPhase m
fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
runHostFrame = lift . runHostFrame
instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (Strict.StateT s m) where
newEventWithTrigger = lift . newEventWithTrigger
newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
instance MonadSubscribeEvent t m => MonadSubscribeEvent t (Strict.StateT r m) where
subscribeEvent = lift . subscribeEvent
instance MonadReflexHost t m => MonadReflexHost t (Strict.StateT s m) where
type ReadPhase (Strict.StateT s m) = ReadPhase m
fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
runHostFrame = lift . runHostFrame
instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ContT r m) where
newEventWithTrigger = lift . newEventWithTrigger
newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ContT r m) where
subscribeEvent = lift . subscribeEvent
instance MonadReflexHost t m => MonadReflexHost t (ContT r m) where
type ReadPhase (ContT r m) = ReadPhase m
fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
runHostFrame = lift . runHostFrame
instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ExceptT e m) where
newEventWithTrigger = lift . newEventWithTrigger
newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ExceptT r m) where
subscribeEvent = lift . subscribeEvent
instance MonadReflexHost t m => MonadReflexHost t (ExceptT e m) where
type ReadPhase (ExceptT e m) = ReadPhase m
fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
runHostFrame = lift . runHostFrame
instance (MonadReflexCreateTrigger t m, Monoid w) => MonadReflexCreateTrigger t (RWST r w s m) where
newEventWithTrigger = lift . newEventWithTrigger
newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
instance (MonadSubscribeEvent t m, Monoid w) => MonadSubscribeEvent t (RWST r w s m) where
subscribeEvent = lift . subscribeEvent
instance (MonadReflexHost t m, Monoid w) => MonadReflexHost t (RWST r w s m) where
type ReadPhase (RWST r w s m) = ReadPhase m
fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
runHostFrame = lift . runHostFrame
|
278ad23b2b252143240512672c351f20247ab20c0da8796aaf3015e146eb6ad4 | evilmartians/foundry | gen_vectors.ml | let _ =
let input_file = ref "" in
Arg.parse (Arg.align [
"-input", Arg.Set_string input_file, "Input file"
])
(fun arg -> prerr_endline ("Extraneous argument " ^ arg))
("Usage: " ^ Sys.argv.(0) ^ " [options]");
let vectors =
let chan = open_in !input_file in
let rec read_all vectors =
try
let line = input_line chan in
if line.[0] = ';' then read_all vectors
else read_all ((String.lowercase line) :: vectors)
with End_of_file -> List.rev vectors
in
read_all []
in
let code = ref "" in
let append decl =
code := !code ^ decl
in
List.iter (fun vector ->
if vector <> "-" then
append ("declare extern_weak void @_" ^ vector ^ "()\n"))
vectors;
append ("\n@__vectors__ = appending global [" ^
(string_of_int (List.length vectors)) ^
" x i32*] [\n");
List.iteri (fun index vector ->
let comma = if index = (List.length vectors) - 1 then "" else "," in
if vector = "-" then
append (" i32* null" ^ comma ^ " ; reserved\n")
else
append (" i32* bitcast(void()* @_" ^ vector ^ " to i32*)" ^ comma ^ "\n"))
vectors;
append ("], section \".vectors\"\n");
print_string !code
| null | https://raw.githubusercontent.com/evilmartians/foundry/ce947c7dcca79ab7a7ce25870e9fc0eb15e9c2bd/src/tools/gen_vectors.ml | ocaml | let _ =
let input_file = ref "" in
Arg.parse (Arg.align [
"-input", Arg.Set_string input_file, "Input file"
])
(fun arg -> prerr_endline ("Extraneous argument " ^ arg))
("Usage: " ^ Sys.argv.(0) ^ " [options]");
let vectors =
let chan = open_in !input_file in
let rec read_all vectors =
try
let line = input_line chan in
if line.[0] = ';' then read_all vectors
else read_all ((String.lowercase line) :: vectors)
with End_of_file -> List.rev vectors
in
read_all []
in
let code = ref "" in
let append decl =
code := !code ^ decl
in
List.iter (fun vector ->
if vector <> "-" then
append ("declare extern_weak void @_" ^ vector ^ "()\n"))
vectors;
append ("\n@__vectors__ = appending global [" ^
(string_of_int (List.length vectors)) ^
" x i32*] [\n");
List.iteri (fun index vector ->
let comma = if index = (List.length vectors) - 1 then "" else "," in
if vector = "-" then
append (" i32* null" ^ comma ^ " ; reserved\n")
else
append (" i32* bitcast(void()* @_" ^ vector ^ " to i32*)" ^ comma ^ "\n"))
vectors;
append ("], section \".vectors\"\n");
print_string !code
|
|
76ad9a8479ad1271d028cf0d67a930565bcc7c062bad5c34dd951a1b5d349750 | ocastalabs/CouchDB-Facebook-Authentication | couch_db.erl | -module(couch_db).
-compile(export_all).
-include("couch_db.hrl").
open_int(<<"_some_db">>, []) ->
{ok, #db{}}.
% Fixtures for various user cases
open_doc_int({db,[]},<<"org.couchdb.user:123456_non_existing_user">>,[]) ->
something_not_ok;
open_doc_int({db,[]},<<"org.couchdb.user:888888_existing_user">>,[]) ->
{ok, #doc{
deleted=false,
id=list_to_binary("org.couchdb.user:888888_existing_user"),
body={[
{<<"_id">>,<<"org.couchdb.user:888888_existing_user">>},
{<<"name">>,"888888_existing_user"},
{<<"roles">>,[]},
{<<"type">>,<<"user">>}
]}
}};
open_doc_int({db,[]},<<"org.couchdb.user:222222_prev_deleted_user">>,[]) ->
{ok, #doc{deleted=true}}.
% The expected document update for the fixture cases
update_doc({db,[]},{doc,<<"org.couchdb.user:123456_non_existing_user">>,
{[
{<<"_id">>,<<"org.couchdb.user:123456_non_existing_user">>},
{<<"fb_access_token">>,<<"MyGreatAccessToken">>},
{<<"name">>,"123456_non_existing_user"},
{<<"roles">>,[]},
{<<"type">>,<<"user">>}
]},
false},[]) ->
{ok, some_new_rev};
update_doc({db,[]},{doc,<<"org.couchdb.user:222222_prev_deleted_user">>,
{[
{<<"_id">>,<<"org.couchdb.user:222222_prev_deleted_user">>},
{<<"fb_access_token">>,<<"MySuperAccessToken">>},
{<<"name">>,"222222_prev_deleted_user"},
{<<"roles">>,[]},
{<<"type">>,<<"user">>}
]},
false},[]) ->
{ok, some_new_rev};
update_doc({db,[]},{doc,<<"org.couchdb.user:888888_existing_user">>,
{[
{<<"fb_access_token">>,<<"MyOtherGreatAccessToken">>},
{<<"type">>,<<"user">>},
{<<"roles">>,[]},
{<<"name">>,"888888_existing_user"},
{<<"_id">>,<<"org.couchdb.user:888888_existing_user">>}
]},
false},[]) ->
{ok, some_new_rev}.
| null | https://raw.githubusercontent.com/ocastalabs/CouchDB-Facebook-Authentication/b20ce4ce17796c3d7ce07e224eb3ae16a71c5e6f/mocks/couch_db.erl | erlang | Fixtures for various user cases
The expected document update for the fixture cases | -module(couch_db).
-compile(export_all).
-include("couch_db.hrl").
open_int(<<"_some_db">>, []) ->
{ok, #db{}}.
open_doc_int({db,[]},<<"org.couchdb.user:123456_non_existing_user">>,[]) ->
something_not_ok;
open_doc_int({db,[]},<<"org.couchdb.user:888888_existing_user">>,[]) ->
{ok, #doc{
deleted=false,
id=list_to_binary("org.couchdb.user:888888_existing_user"),
body={[
{<<"_id">>,<<"org.couchdb.user:888888_existing_user">>},
{<<"name">>,"888888_existing_user"},
{<<"roles">>,[]},
{<<"type">>,<<"user">>}
]}
}};
open_doc_int({db,[]},<<"org.couchdb.user:222222_prev_deleted_user">>,[]) ->
{ok, #doc{deleted=true}}.
update_doc({db,[]},{doc,<<"org.couchdb.user:123456_non_existing_user">>,
{[
{<<"_id">>,<<"org.couchdb.user:123456_non_existing_user">>},
{<<"fb_access_token">>,<<"MyGreatAccessToken">>},
{<<"name">>,"123456_non_existing_user"},
{<<"roles">>,[]},
{<<"type">>,<<"user">>}
]},
false},[]) ->
{ok, some_new_rev};
update_doc({db,[]},{doc,<<"org.couchdb.user:222222_prev_deleted_user">>,
{[
{<<"_id">>,<<"org.couchdb.user:222222_prev_deleted_user">>},
{<<"fb_access_token">>,<<"MySuperAccessToken">>},
{<<"name">>,"222222_prev_deleted_user"},
{<<"roles">>,[]},
{<<"type">>,<<"user">>}
]},
false},[]) ->
{ok, some_new_rev};
update_doc({db,[]},{doc,<<"org.couchdb.user:888888_existing_user">>,
{[
{<<"fb_access_token">>,<<"MyOtherGreatAccessToken">>},
{<<"type">>,<<"user">>},
{<<"roles">>,[]},
{<<"name">>,"888888_existing_user"},
{<<"_id">>,<<"org.couchdb.user:888888_existing_user">>}
]},
false},[]) ->
{ok, some_new_rev}.
|
18ead9392128bcec0fe85210c6df42a4ef2da6ab4dc92aa5ef2e4cd7cb37973c | sgbj/MaximaSharp | dsbmv.lisp | ;;; Compiled by f2cl version:
( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " )
;;; Using Lisp CMU Common Lisp 20d (20D Unicode)
;;;
;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
;;; (:coerce-assigns :as-needed) (:array-type ':array)
;;; (:array-slicing t) (:declare-common nil)
;;; (:float-format double-float))
(in-package :blas)
(let* ((one 1.0) (zero 0.0))
(declare (type (double-float 1.0 1.0) one)
(type (double-float 0.0 0.0) zero)
(ignorable one zero))
(defun dsbmv (uplo n k alpha a lda x incx beta y incy)
(declare (type (array double-float (*)) y x a)
(type (double-float) beta alpha)
(type (f2cl-lib:integer4) incy incx lda k n)
(type (simple-string *) uplo))
(f2cl-lib:with-multi-array-data
((uplo character uplo-%data% uplo-%offset%)
(a double-float a-%data% a-%offset%)
(x double-float x-%data% x-%offset%)
(y double-float y-%data% y-%offset%))
(prog ((i 0) (info 0) (ix 0) (iy 0) (j 0) (jx 0) (jy 0) (kplus1 0) (kx 0)
(ky 0) (l 0) (temp1 0.0) (temp2 0.0))
(declare (type (f2cl-lib:integer4) i info ix iy j jx jy kplus1 kx ky l)
(type (double-float) temp1 temp2))
(setf info 0)
(cond
((and (not (lsame uplo "U")) (not (lsame uplo "L")))
(setf info 1))
((< n 0)
(setf info 2))
((< k 0)
(setf info 3))
((< lda (f2cl-lib:int-add k 1))
(setf info 6))
((= incx 0)
(setf info 8))
((= incy 0)
(setf info 11)))
(cond
((/= info 0)
(xerbla "DSBMV " info)
(go end_label)))
(if (or (= n 0) (and (= alpha zero) (= beta one))) (go end_label))
(cond
((> incx 0)
(setf kx 1))
(t
(setf kx
(f2cl-lib:int-sub 1
(f2cl-lib:int-mul (f2cl-lib:int-sub n 1)
incx)))))
(cond
((> incy 0)
(setf ky 1))
(t
(setf ky
(f2cl-lib:int-sub 1
(f2cl-lib:int-mul (f2cl-lib:int-sub n 1)
incy)))))
(cond
((/= beta one)
(cond
((= incy 1)
(cond
((= beta zero)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
zero)
label10)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(* beta
(f2cl-lib:fref y-%data%
(i)
((1 *))
y-%offset%)))
label20)))))
(t
(setf iy ky)
(cond
((= beta zero)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
zero)
(setf iy (f2cl-lib:int-add iy incy))
label30)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(* beta
(f2cl-lib:fref y-%data%
(iy)
((1 *))
y-%offset%)))
(setf iy (f2cl-lib:int-add iy incy))
label40))))))))
(if (= alpha zero) (go end_label))
(cond
((lsame uplo "U")
(setf kplus1 (f2cl-lib:int-add k 1))
(cond
((and (= incx 1) (= incy 1))
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)))
(setf temp2 zero)
(setf l (f2cl-lib:int-sub kplus1 j))
(f2cl-lib:fdo (i
(max (the f2cl-lib:integer4 1)
(the f2cl-lib:integer4
(f2cl-lib:int-add j
(f2cl-lib:int-sub
k))))
(f2cl-lib:int-add i 1))
((> i
(f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%)
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
label50))
(setf (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
(kplus1 j)
((1 lda) (1 *))
a-%offset%))
(* alpha temp2)))
label60)))
(t
(setf jx kx)
(setf jy ky)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)))
(setf temp2 zero)
(setf ix kx)
(setf iy ky)
(setf l (f2cl-lib:int-sub kplus1 j))
(f2cl-lib:fdo (i
(max (the f2cl-lib:integer4 1)
(the f2cl-lib:integer4
(f2cl-lib:int-add j
(f2cl-lib:int-sub
k))))
(f2cl-lib:int-add i 1))
((> i
(f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%)
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
(setf ix (f2cl-lib:int-add ix incx))
(setf iy (f2cl-lib:int-add iy incy))
label70))
(setf (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
(kplus1 j)
((1 lda) (1 *))
a-%offset%))
(* alpha temp2)))
(setf jx (f2cl-lib:int-add jx incx))
(setf jy (f2cl-lib:int-add jy incy))
(cond
((> j k)
(setf kx (f2cl-lib:int-add kx incx))
(setf ky (f2cl-lib:int-add ky incy))))
label80)))))
(t
(cond
((and (= incx 1) (= incy 1))
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)))
(setf temp2 zero)
(setf (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
(1 j)
((1 lda) (1 *))
a-%offset%))))
(setf l (f2cl-lib:int-sub 1 j))
(f2cl-lib:fdo (i (f2cl-lib:int-add j 1)
(f2cl-lib:int-add i 1))
((> i
(min (the f2cl-lib:integer4 n)
(the f2cl-lib:integer4
(f2cl-lib:int-add j k))))
nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%)
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
label90))
(setf (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(* alpha temp2)))
label100)))
(t
(setf jx kx)
(setf jy ky)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)))
(setf temp2 zero)
(setf (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
(1 j)
((1 lda) (1 *))
a-%offset%))))
(setf l (f2cl-lib:int-sub 1 j))
(setf ix jx)
(setf iy jy)
(f2cl-lib:fdo (i (f2cl-lib:int-add j 1)
(f2cl-lib:int-add i 1))
((> i
(min (the f2cl-lib:integer4 n)
(the f2cl-lib:integer4
(f2cl-lib:int-add j k))))
nil)
(tagbody
(setf ix (f2cl-lib:int-add ix incx))
(setf iy (f2cl-lib:int-add iy incy))
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%)
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
label110))
(setf (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(* alpha temp2)))
(setf jx (f2cl-lib:int-add jx incx))
(setf jy (f2cl-lib:int-add jy incy))
label120))))))
(go end_label)
end_label
(return (values nil nil nil nil nil nil nil nil nil nil nil))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::dsbmv fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((simple-string) (fortran-to-lisp::integer4)
(fortran-to-lisp::integer4) (double-float)
(array double-float (*)) (fortran-to-lisp::integer4)
(array double-float (*)) (fortran-to-lisp::integer4)
(double-float) (array double-float (*))
(fortran-to-lisp::integer4))
:return-values '(nil nil nil nil nil nil nil nil nil nil nil)
:calls '(fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
| null | https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/share/lapack/blas/dsbmv.lisp | lisp | Compiled by f2cl version:
Using Lisp CMU Common Lisp 20d (20D Unicode)
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':array)
(:array-slicing t) (:declare-common nil)
(:float-format double-float)) | ( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " )
(in-package :blas)
(let* ((one 1.0) (zero 0.0))
(declare (type (double-float 1.0 1.0) one)
(type (double-float 0.0 0.0) zero)
(ignorable one zero))
(defun dsbmv (uplo n k alpha a lda x incx beta y incy)
(declare (type (array double-float (*)) y x a)
(type (double-float) beta alpha)
(type (f2cl-lib:integer4) incy incx lda k n)
(type (simple-string *) uplo))
(f2cl-lib:with-multi-array-data
((uplo character uplo-%data% uplo-%offset%)
(a double-float a-%data% a-%offset%)
(x double-float x-%data% x-%offset%)
(y double-float y-%data% y-%offset%))
(prog ((i 0) (info 0) (ix 0) (iy 0) (j 0) (jx 0) (jy 0) (kplus1 0) (kx 0)
(ky 0) (l 0) (temp1 0.0) (temp2 0.0))
(declare (type (f2cl-lib:integer4) i info ix iy j jx jy kplus1 kx ky l)
(type (double-float) temp1 temp2))
(setf info 0)
(cond
((and (not (lsame uplo "U")) (not (lsame uplo "L")))
(setf info 1))
((< n 0)
(setf info 2))
((< k 0)
(setf info 3))
((< lda (f2cl-lib:int-add k 1))
(setf info 6))
((= incx 0)
(setf info 8))
((= incy 0)
(setf info 11)))
(cond
((/= info 0)
(xerbla "DSBMV " info)
(go end_label)))
(if (or (= n 0) (and (= alpha zero) (= beta one))) (go end_label))
(cond
((> incx 0)
(setf kx 1))
(t
(setf kx
(f2cl-lib:int-sub 1
(f2cl-lib:int-mul (f2cl-lib:int-sub n 1)
incx)))))
(cond
((> incy 0)
(setf ky 1))
(t
(setf ky
(f2cl-lib:int-sub 1
(f2cl-lib:int-mul (f2cl-lib:int-sub n 1)
incy)))))
(cond
((/= beta one)
(cond
((= incy 1)
(cond
((= beta zero)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
zero)
label10)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(* beta
(f2cl-lib:fref y-%data%
(i)
((1 *))
y-%offset%)))
label20)))))
(t
(setf iy ky)
(cond
((= beta zero)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
zero)
(setf iy (f2cl-lib:int-add iy incy))
label30)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(* beta
(f2cl-lib:fref y-%data%
(iy)
((1 *))
y-%offset%)))
(setf iy (f2cl-lib:int-add iy incy))
label40))))))))
(if (= alpha zero) (go end_label))
(cond
((lsame uplo "U")
(setf kplus1 (f2cl-lib:int-add k 1))
(cond
((and (= incx 1) (= incy 1))
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)))
(setf temp2 zero)
(setf l (f2cl-lib:int-sub kplus1 j))
(f2cl-lib:fdo (i
(max (the f2cl-lib:integer4 1)
(the f2cl-lib:integer4
(f2cl-lib:int-add j
(f2cl-lib:int-sub
k))))
(f2cl-lib:int-add i 1))
((> i
(f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%)
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
label50))
(setf (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
(kplus1 j)
((1 lda) (1 *))
a-%offset%))
(* alpha temp2)))
label60)))
(t
(setf jx kx)
(setf jy ky)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)))
(setf temp2 zero)
(setf ix kx)
(setf iy ky)
(setf l (f2cl-lib:int-sub kplus1 j))
(f2cl-lib:fdo (i
(max (the f2cl-lib:integer4 1)
(the f2cl-lib:integer4
(f2cl-lib:int-add j
(f2cl-lib:int-sub
k))))
(f2cl-lib:int-add i 1))
((> i
(f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%)
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
(setf ix (f2cl-lib:int-add ix incx))
(setf iy (f2cl-lib:int-add iy incy))
label70))
(setf (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
(kplus1 j)
((1 lda) (1 *))
a-%offset%))
(* alpha temp2)))
(setf jx (f2cl-lib:int-add jx incx))
(setf jy (f2cl-lib:int-add jy incy))
(cond
((> j k)
(setf kx (f2cl-lib:int-add kx incx))
(setf ky (f2cl-lib:int-add ky incy))))
label80)))))
(t
(cond
((and (= incx 1) (= incy 1))
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)))
(setf temp2 zero)
(setf (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
(1 j)
((1 lda) (1 *))
a-%offset%))))
(setf l (f2cl-lib:int-sub 1 j))
(f2cl-lib:fdo (i (f2cl-lib:int-add j 1)
(f2cl-lib:int-add i 1))
((> i
(min (the f2cl-lib:integer4 n)
(the f2cl-lib:integer4
(f2cl-lib:int-add j k))))
nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%)
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
label90))
(setf (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(* alpha temp2)))
label100)))
(t
(setf jx kx)
(setf jy ky)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)))
(setf temp2 zero)
(setf (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
(1 j)
((1 lda) (1 *))
a-%offset%))))
(setf l (f2cl-lib:int-sub 1 j))
(setf ix jx)
(setf iy jy)
(f2cl-lib:fdo (i (f2cl-lib:int-add j 1)
(f2cl-lib:int-add i 1))
((> i
(min (the f2cl-lib:integer4 n)
(the f2cl-lib:integer4
(f2cl-lib:int-add j k))))
nil)
(tagbody
(setf ix (f2cl-lib:int-add ix incx))
(setf iy (f2cl-lib:int-add iy incy))
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%)
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
label110))
(setf (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(* alpha temp2)))
(setf jx (f2cl-lib:int-add jx incx))
(setf jy (f2cl-lib:int-add jy incy))
label120))))))
(go end_label)
end_label
(return (values nil nil nil nil nil nil nil nil nil nil nil))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::dsbmv fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((simple-string) (fortran-to-lisp::integer4)
(fortran-to-lisp::integer4) (double-float)
(array double-float (*)) (fortran-to-lisp::integer4)
(array double-float (*)) (fortran-to-lisp::integer4)
(double-float) (array double-float (*))
(fortran-to-lisp::integer4))
:return-values '(nil nil nil nil nil nil nil nil nil nil nil)
:calls '(fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
|
5da7cc6dc67e1aa0e67f705fa078eb9f0f70f4988d03904d76c862e323893c5e | wgnet/fox | fox_pub_pool_tests.erl | -module(fox_pub_pool_tests).
-include_lib("eunit/include/eunit.hrl").
-include("fox.hrl").
setup() ->
application:ensure_all_started(fox),
fox_utils:map_to_params_network(#{host => "localhost",
port => 5672,
virtual_host => <<"/">>,
username => <<"guest">>,
password => <<"guest">>}).
get_channel_test() ->
Params = setup(),
{ok, Pid} = fox_pub_pool:start_link(pool_1, Params),
?assertMatch({status, _}, erlang:process_info(Pid, status)),
?assertMatch(Pid, whereis('fox_pub_pool/pool_1')),
{ok, C1} = fox_pub_pool:get_channel(pool_1),
?assert(erlang:is_process_alive(C1)),
{ok, C2} = fox_pub_pool:get_channel(pool_1),
?assert(erlang:is_process_alive(C2)),
{ok, C3} = fox_pub_pool:get_channel(pool_1),
?assert(erlang:is_process_alive(C3)),
?assertNotEqual(C1, C2),
?assertNotEqual(C2, C3),
?assertNotEqual(C1, C3),
fox_pub_pool:stop(pool_1),
?assertNot(erlang:is_process_alive(Pid)),
?assertNot(erlang:is_process_alive(C1)),
?assertNot(erlang:is_process_alive(C2)),
?assertNot(erlang:is_process_alive(C3)),
ok.
reconnect_test() ->
Params = setup(),
{ok, Pid} = fox_pub_pool:start_link(pool_2, Params),
timer:sleep(200),
[state, Conn | _] = tuple_to_list(sys:get_state(Pid)),
?assert(is_pid(Conn)),
ok = amqp_connection:close(Conn),
timer:sleep(200),
[state, Conn2 | _] = tuple_to_list(sys:get_state(Pid)),
?assert(is_pid(Conn2)),
?assertNotEqual(Conn, Conn2),
ok = fox_pub_pool:stop(pool_2),
?assertNot(erlang:is_process_alive(Pid)),
?assertNot(erlang:is_process_alive(Conn)),
?assertNot(erlang:is_process_alive(Conn2)),
ok. | null | https://raw.githubusercontent.com/wgnet/fox/030cc35d5828db959d19e67c90456d24a2c77c8e/test/fox_pub_pool_tests.erl | erlang | -module(fox_pub_pool_tests).
-include_lib("eunit/include/eunit.hrl").
-include("fox.hrl").
setup() ->
application:ensure_all_started(fox),
fox_utils:map_to_params_network(#{host => "localhost",
port => 5672,
virtual_host => <<"/">>,
username => <<"guest">>,
password => <<"guest">>}).
get_channel_test() ->
Params = setup(),
{ok, Pid} = fox_pub_pool:start_link(pool_1, Params),
?assertMatch({status, _}, erlang:process_info(Pid, status)),
?assertMatch(Pid, whereis('fox_pub_pool/pool_1')),
{ok, C1} = fox_pub_pool:get_channel(pool_1),
?assert(erlang:is_process_alive(C1)),
{ok, C2} = fox_pub_pool:get_channel(pool_1),
?assert(erlang:is_process_alive(C2)),
{ok, C3} = fox_pub_pool:get_channel(pool_1),
?assert(erlang:is_process_alive(C3)),
?assertNotEqual(C1, C2),
?assertNotEqual(C2, C3),
?assertNotEqual(C1, C3),
fox_pub_pool:stop(pool_1),
?assertNot(erlang:is_process_alive(Pid)),
?assertNot(erlang:is_process_alive(C1)),
?assertNot(erlang:is_process_alive(C2)),
?assertNot(erlang:is_process_alive(C3)),
ok.
reconnect_test() ->
Params = setup(),
{ok, Pid} = fox_pub_pool:start_link(pool_2, Params),
timer:sleep(200),
[state, Conn | _] = tuple_to_list(sys:get_state(Pid)),
?assert(is_pid(Conn)),
ok = amqp_connection:close(Conn),
timer:sleep(200),
[state, Conn2 | _] = tuple_to_list(sys:get_state(Pid)),
?assert(is_pid(Conn2)),
?assertNotEqual(Conn, Conn2),
ok = fox_pub_pool:stop(pool_2),
?assertNot(erlang:is_process_alive(Pid)),
?assertNot(erlang:is_process_alive(Conn)),
?assertNot(erlang:is_process_alive(Conn2)),
ok. |
|
bcaa14bd5b273a1dac184585087bbec99b4457f838e5affe80d301c942daea16 | lathe/punctaffy-for-racket | monoid.rkt | #lang parendown racket/base
; monoid.rkt
;
; A dictionary-passing implementation of the monoid type class for
; Racket, using Racket's generic methods so that it's more
; straightforward to define dictiaonries that are comparable by
; `equal?`.
Copyright 2017 - 2018 , 2022 The Lathe Authors
;
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
;
; -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.
(require #/only-in racket/contract/base -> any any/c)
(require #/only-in racket/generic define-generics)
(require #/only-in lathe-comforts expect)
(require #/only-in lathe-comforts/struct struct-easy)
(require punctaffy/private/shim)
(init-shim)
(provide gen:monoid monoid? monoid/c monoid-empty monoid-append)
(provide #/rename-out [make-monoid-trivial monoid-trivial])
(define-generics monoid
(monoid-empty monoid)
(monoid-append monoid prefix suffix))
This monoid has only one segment , namely the empty list .
(struct-easy (monoid-trivial)
#:equal
#:other
#:constructor-name make-monoid-trivial
#:methods gen:monoid
[
(define (monoid-empty this)
(expect this (monoid-trivial)
(error "Expected this to be a monoid-trivial")
null))
(define/own-contract (monoid-append this prefix suffix)
(-> any/c null? null? any)
(expect this (monoid-trivial)
(error "Expected this to be a monoid-trivial")
null))
])
| null | https://raw.githubusercontent.com/lathe/punctaffy-for-racket/47cf41144735645428818ba0f99711f10816c059/punctaffy-lib/private/experimental/monoid.rkt | racket | monoid.rkt
A dictionary-passing implementation of the monoid type class for
Racket, using Racket's generic methods so that it's more
straightforward to define dictiaonries that are comparable by
`equal?`.
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
either express or implied. See the License for the specific
language governing permissions and limitations under the License. | #lang parendown racket/base
Copyright 2017 - 2018 , 2022 The Lathe Authors
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND ,
(require #/only-in racket/contract/base -> any any/c)
(require #/only-in racket/generic define-generics)
(require #/only-in lathe-comforts expect)
(require #/only-in lathe-comforts/struct struct-easy)
(require punctaffy/private/shim)
(init-shim)
(provide gen:monoid monoid? monoid/c monoid-empty monoid-append)
(provide #/rename-out [make-monoid-trivial monoid-trivial])
(define-generics monoid
(monoid-empty monoid)
(monoid-append monoid prefix suffix))
This monoid has only one segment , namely the empty list .
(struct-easy (monoid-trivial)
#:equal
#:other
#:constructor-name make-monoid-trivial
#:methods gen:monoid
[
(define (monoid-empty this)
(expect this (monoid-trivial)
(error "Expected this to be a monoid-trivial")
null))
(define/own-contract (monoid-append this prefix suffix)
(-> any/c null? null? any)
(expect this (monoid-trivial)
(error "Expected this to be a monoid-trivial")
null))
])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.