_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 |
|---|---|---|---|---|---|---|---|---|
9a01fd3cd40fbf3fc3db50870eff52f62159955cd120bbf310857c57328204f6 | facebook/flow | saved_state_scm_fetcher.mli |
* Copyright ( c ) Meta Platforms , Inc. and 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) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
include Saved_state_fetcher.FETCHER
val output_filename : Options.t -> (string, string) result Lwt.t
| null | https://raw.githubusercontent.com/facebook/flow/1ccfa98b476a9a19ae151e16ce50fb04e8442ccd/src/services/saved_state/fetcher/saved_state_scm_fetcher.mli | ocaml |
* Copyright ( c ) Meta Platforms , Inc. and 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) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
include Saved_state_fetcher.FETCHER
val output_filename : Options.t -> (string, string) result Lwt.t
| |
98c1e55e17ade124b8b4fda9f62bec4754c255e9dbb63d1caab587780c7004cd | spectrum-finance/cardano-dex-sdk-haskell | KeeperConfig.hs | module DatumKeeper.Config.KeeperConfig where
import GHC.Natural
data DatumKeeperConfig = DatumKeeperConfig
{ host :: String
, port :: Natural
} | null | https://raw.githubusercontent.com/spectrum-finance/cardano-dex-sdk-haskell/86aebebc3c193f5838634375da2488a8577baa93/datum-keeper-client/src/DatumKeeper/Config/KeeperConfig.hs | haskell | module DatumKeeper.Config.KeeperConfig where
import GHC.Natural
data DatumKeeperConfig = DatumKeeperConfig
{ host :: String
, port :: Natural
} | |
409e874687a6b345034644c8391467dd4f98c6ecba337a5686e4d6a6016e5bc7 | maximedenes/native-coq | index.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Filename
open Lexing
open Printf
open Cdglobals
type loc = int
type entry_type =
| Library
| Module
| Definition
| Inductive
| Constructor
| Lemma
| Record
| Projection
| Instance
| Class
| Method
| Variable
| Axiom
| TacticDefinition
| Abbreviation
| Notation
| Section
type index_entry =
| Def of string * entry_type
| Ref of coq_module * string * entry_type
| Mod of coq_module * string
let current_type : entry_type ref = ref Library
let current_library = ref ""
(** refers to the file being parsed *)
(** [deftable] stores only definitions and is used to interpolate idents
inside comments, which are not globalized otherwise. *)
let deftable = Hashtbl.create 97
(** [reftable] stores references and definitions *)
let reftable = Hashtbl.create 97
let full_ident sp id =
if sp <> "<>" then
if id <> "<>" then
sp ^ "." ^ id
else sp
else if id <> "<>"
then id
else ""
let add_def loc1 loc2 ty sp id =
for loc = loc1 to loc2 do
Hashtbl.add reftable (!current_library, loc) (Def (full_ident sp id, ty))
done;
Hashtbl.add deftable id (Def (full_ident sp id, ty))
let add_ref m loc m' sp id ty =
if Hashtbl.mem reftable (m, loc) then ()
else Hashtbl.add reftable (m, loc) (Ref (m', full_ident sp id, ty));
let idx = if id = "<>" then m' else id in
if Hashtbl.mem deftable idx then ()
else Hashtbl.add deftable idx (Ref (m', full_ident sp id, ty))
let add_mod m loc m' id =
Hashtbl.add reftable (m, loc) (Mod (m', id));
Hashtbl.add deftable m (Mod (m', id))
let find m l = Hashtbl.find reftable (m, l)
let find_string m s = Hashtbl.find deftable s
(*s Manipulating path prefixes *)
type stack = string list
let rec string_of_stack st =
match st with
| [] -> ""
| x::[] -> x
| x::tl -> (string_of_stack tl) ^ "." ^ x
let empty_stack = []
let module_stack = ref empty_stack
let section_stack = ref empty_stack
let init_stack () =
module_stack := empty_stack; section_stack := empty_stack
let push st p = st := p::!st
let pop st =
match !st with
| [] -> ()
| _::tl -> st := tl
let head st =
match st with
| [] -> ""
| x::_ -> x
let begin_module m = push module_stack m
let begin_section s = push section_stack s
let end_block id =
(** determines if it ends a module or a section and pops the stack *)
if ((String.compare (head !module_stack) id ) == 0) then
pop module_stack
else if ((String.compare (head !section_stack) id) == 0) then
pop section_stack
else
()
let make_fullid id =
(** prepends the current module path to an id *)
let path = string_of_stack !module_stack in
if String.length path > 0 then
path ^ "." ^ id
else
id
Coq modules
let split_sp s =
try
let i = String.rindex s '.' in
String.sub s 0 i, String.sub s (i + 1) (String.length s - i - 1)
with
Not_found -> "", s
let modules = Hashtbl.create 97
let local_modules = Hashtbl.create 97
let add_module m =
let _,id = split_sp m in
Hashtbl.add modules id m;
Hashtbl.add local_modules m ()
type module_kind = Local | External of string | Unknown
let external_libraries = ref []
let add_external_library logicalpath url =
external_libraries := (logicalpath,url) :: !external_libraries
let find_external_library logicalpath =
let rec aux = function
| [] -> raise Not_found
| (l,u)::rest ->
if String.length logicalpath > String.length l &
String.sub logicalpath 0 (String.length l + 1) = l ^"."
then u
else aux rest
in aux !external_libraries
let init_coqlib_library () = add_external_library "Coq" !coqlib
let find_module m =
if Hashtbl.mem local_modules m then
Local
else
try External (Filename.concat (find_external_library m) m)
with Not_found -> Unknown
(* Building indexes *)
type 'a index = {
idx_name : string;
idx_entries : (char * (string * 'a) list) list;
idx_size : int }
let map f i =
{ i with idx_entries =
List.map
(fun (c,l) -> (c, List.map (fun (s,x) -> (s,f s x)) l))
i.idx_entries }
let compare_entries (s1,_) (s2,_) = Alpha.compare_string s1 s2
let sort_entries el =
let t = Hashtbl.create 97 in
List.iter
(fun c -> Hashtbl.add t c [])
['A'; 'B'; 'C'; 'D'; 'E'; 'F'; 'G'; 'H'; 'I'; 'J'; 'K'; 'L'; 'M'; 'N';
'O'; 'P'; 'Q'; 'R'; 'S'; 'T'; 'U'; 'V'; 'W'; 'X'; 'Y'; 'Z'; '_'; '*'];
List.iter
(fun ((s,_) as e) ->
let c = Alpha.norm_char s.[0] in
let c,l =
try c,Hashtbl.find t c with Not_found -> '*',Hashtbl.find t '*' in
Hashtbl.replace t c (e :: l))
el;
let res = ref [] in
Hashtbl.iter (fun c l -> res := (c, List.sort compare_entries l) :: !res) t;
List.sort (fun (c1,_) (c2,_) -> Alpha.compare_char c1 c2) !res
let display_letter c = if c = '*' then "other" else String.make 1 c
let index_size = List.fold_left (fun s (_,l) -> s + List.length l) 0
let hashtbl_elements h = Hashtbl.fold (fun x y l -> (x,y)::l) h []
let type_name = function
| Library ->
let ln = !lib_name in
if ln <> "" then String.lowercase ln else "library"
| Module -> "module"
| Definition -> "definition"
| Inductive -> "inductive"
| Constructor -> "constructor"
| Lemma -> "lemma"
| Record -> "record"
| Projection -> "projection"
| Instance -> "instance"
| Class -> "class"
| Method -> "method"
| Variable -> "variable"
| Axiom -> "axiom"
| TacticDefinition -> "tactic"
| Abbreviation -> "abbreviation"
| Notation -> "notation"
| Section -> "section"
let prepare_entry s = function
| Notation ->
(* We decode the encoding done in Dumpglob.cook_notation of coqtop *)
(* Encoded notations have the form section:sc:x_'++'_x where: *)
(* - the section, if any, ends with a "." *)
(* - the scope can be empty *)
(* - tokens are separated with "_" *)
(* - non-terminal symbols are conventionally represented by "x" *)
(* - terminals are enclosed within simple quotes *)
(* - existing simple quotes (that necessarily are parts of *)
(* terminals) are doubled *)
(* (as a consequence, when a terminal contains "_" or "x", these *)
(* necessarily appear enclosed within non-doubled simple quotes) *)
- non - printable characters < 32 are left encoded so that they
(* are human-readable in index files *)
(* Example: "x ' %x _% y %'x %'_' z" is encoded as *)
(* "x_''''_'%x'_'_%'_x_'%''x'_'%''_'''_x" *)
let err () = eprintf "Invalid notation in globalization file\n"; exit 1 in
let h = try String.index_from s 0 ':' with _ -> err () in
let i = try String.index_from s (h+1) ':' with _ -> err () in
let sc = String.sub s (h+1) (i-h-1) in
let ntn = String.make (String.length s - i) ' ' in
let k = ref 0 in
let j = ref (i+1) in
let quoted = ref false in
let l = String.length s - 1 in
while !j <= l do
if not !quoted then begin
(match s.[!j] with
| '_' -> ntn.[!k] <- ' '; incr k
| 'x' -> ntn.[!k] <- '_'; incr k
| '\'' -> quoted := true
| _ -> assert false)
end
else
if s.[!j] = '\'' then
if (!j = l || s.[!j+1] = '_') then quoted := false
else (incr j; ntn.[!k] <- s.[!j]; incr k)
else begin
ntn.[!k] <- s.[!j];
incr k
end;
incr j
done;
let ntn = String.sub ntn 0 !k in
if sc = "" then ntn else ntn ^ " (" ^ sc ^ ")"
| _ ->
s
let all_entries () =
let gl = ref [] in
let add_g s m t = gl := (s,(m,t)) :: !gl in
let bt = Hashtbl.create 11 in
let add_bt t s m =
let l = try Hashtbl.find bt t with Not_found -> [] in
Hashtbl.replace bt t ((s,m) :: l)
in
let classify m e = match e with
| Def (s,t) -> add_g s m t; add_bt t s m
| Ref _ | Mod _ -> ()
in
Hashtbl.iter classify deftable;
Hashtbl.iter (fun id m -> add_g id m Library; add_bt Library id m) modules;
{ idx_name = "global";
idx_entries = sort_entries !gl;
idx_size = List.length !gl },
Hashtbl.fold (fun t e l -> (t, { idx_name = type_name t;
idx_entries = sort_entries e;
idx_size = List.length e }) :: l) bt []
let type_of_string = function
| "def" | "coe" | "subclass" | "canonstruc" | "fix" | "cofix"
| "ex" | "scheme" -> Definition
| "prf" | "thm" -> Lemma
| "ind" | "coind" -> Inductive
| "constr" -> Constructor
| "rec" | "corec" -> Record
| "proj" -> Projection
| "class" -> Class
| "meth" -> Method
| "inst" -> Instance
| "var" -> Variable
| "defax" | "prfax" | "ax" -> Axiom
| "syndef" -> Abbreviation
| "not" -> Notation
| "lib" -> Library
| "mod" | "modtype" -> Module
| "tac" -> TacticDefinition
| "sec" -> Section
| s -> raise (Invalid_argument ("type_of_string:" ^ s))
let ill_formed_glob_file f =
eprintf "Warning: ill-formed file %s (links will not be available)\n" f
let outdated_glob_file f =
eprintf "Warning: %s not consistent with corresponding .v file (links will not be available)\n" f
let correct_file vfile f c =
let s = input_line c in
if String.length s < 7 || String.sub s 0 7 <> "DIGEST " then
(ill_formed_glob_file f; false)
else
let s = String.sub s 7 (String.length s - 7) in
match vfile, s with
| None, "NO" -> true
| Some _, "NO" -> ill_formed_glob_file f; false
| None, _ -> ill_formed_glob_file f; false
| Some vfile, s ->
s = Digest.to_hex (Digest.file vfile) || (outdated_glob_file f; false)
let read_glob vfile f =
let c = open_in f in
if correct_file vfile f c then
let cur_mod = ref "" in
try
while true do
let s = input_line c in
let n = String.length s in
if n > 0 then begin
match s.[0] with
| 'F' ->
cur_mod := String.sub s 1 (n - 1);
current_library := !cur_mod
| 'R' ->
(try
Scanf.sscanf s "R%d:%d %s %s %s %s"
(fun loc1 loc2 lib_dp sp id ty ->
for loc=loc1 to loc2 do
add_ref !cur_mod loc lib_dp sp id (type_of_string ty)
done)
with _ -> ())
| _ ->
try Scanf.sscanf s "not %d %s %s"
(fun loc sp id -> add_def loc loc (type_of_string "not") sp id)
with Scanf.Scan_failure _ ->
try Scanf.sscanf s "%s %d:%d %s %s"
(fun ty loc1 loc2 sp id ->
add_def loc1 loc2 (type_of_string ty) sp id)
with Scanf.Scan_failure _ -> ()
end
done; assert false
with End_of_file ->
close_in c
| null | https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/tools/coqdoc/index.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* refers to the file being parsed
* [deftable] stores only definitions and is used to interpolate idents
inside comments, which are not globalized otherwise.
* [reftable] stores references and definitions
s Manipulating path prefixes
* determines if it ends a module or a section and pops the stack
* prepends the current module path to an id
Building indexes
We decode the encoding done in Dumpglob.cook_notation of coqtop
Encoded notations have the form section:sc:x_'++'_x where:
- the section, if any, ends with a "."
- the scope can be empty
- tokens are separated with "_"
- non-terminal symbols are conventionally represented by "x"
- terminals are enclosed within simple quotes
- existing simple quotes (that necessarily are parts of
terminals) are doubled
(as a consequence, when a terminal contains "_" or "x", these
necessarily appear enclosed within non-doubled simple quotes)
are human-readable in index files
Example: "x ' %x _% y %'x %'_' z" is encoded as
"x_''''_'%x'_'_%'_x_'%''x'_'%''_'''_x" | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Filename
open Lexing
open Printf
open Cdglobals
type loc = int
type entry_type =
| Library
| Module
| Definition
| Inductive
| Constructor
| Lemma
| Record
| Projection
| Instance
| Class
| Method
| Variable
| Axiom
| TacticDefinition
| Abbreviation
| Notation
| Section
type index_entry =
| Def of string * entry_type
| Ref of coq_module * string * entry_type
| Mod of coq_module * string
let current_type : entry_type ref = ref Library
let current_library = ref ""
let deftable = Hashtbl.create 97
let reftable = Hashtbl.create 97
let full_ident sp id =
if sp <> "<>" then
if id <> "<>" then
sp ^ "." ^ id
else sp
else if id <> "<>"
then id
else ""
let add_def loc1 loc2 ty sp id =
for loc = loc1 to loc2 do
Hashtbl.add reftable (!current_library, loc) (Def (full_ident sp id, ty))
done;
Hashtbl.add deftable id (Def (full_ident sp id, ty))
let add_ref m loc m' sp id ty =
if Hashtbl.mem reftable (m, loc) then ()
else Hashtbl.add reftable (m, loc) (Ref (m', full_ident sp id, ty));
let idx = if id = "<>" then m' else id in
if Hashtbl.mem deftable idx then ()
else Hashtbl.add deftable idx (Ref (m', full_ident sp id, ty))
let add_mod m loc m' id =
Hashtbl.add reftable (m, loc) (Mod (m', id));
Hashtbl.add deftable m (Mod (m', id))
let find m l = Hashtbl.find reftable (m, l)
let find_string m s = Hashtbl.find deftable s
type stack = string list
let rec string_of_stack st =
match st with
| [] -> ""
| x::[] -> x
| x::tl -> (string_of_stack tl) ^ "." ^ x
let empty_stack = []
let module_stack = ref empty_stack
let section_stack = ref empty_stack
let init_stack () =
module_stack := empty_stack; section_stack := empty_stack
let push st p = st := p::!st
let pop st =
match !st with
| [] -> ()
| _::tl -> st := tl
let head st =
match st with
| [] -> ""
| x::_ -> x
let begin_module m = push module_stack m
let begin_section s = push section_stack s
let end_block id =
if ((String.compare (head !module_stack) id ) == 0) then
pop module_stack
else if ((String.compare (head !section_stack) id) == 0) then
pop section_stack
else
()
let make_fullid id =
let path = string_of_stack !module_stack in
if String.length path > 0 then
path ^ "." ^ id
else
id
Coq modules
let split_sp s =
try
let i = String.rindex s '.' in
String.sub s 0 i, String.sub s (i + 1) (String.length s - i - 1)
with
Not_found -> "", s
let modules = Hashtbl.create 97
let local_modules = Hashtbl.create 97
let add_module m =
let _,id = split_sp m in
Hashtbl.add modules id m;
Hashtbl.add local_modules m ()
type module_kind = Local | External of string | Unknown
let external_libraries = ref []
let add_external_library logicalpath url =
external_libraries := (logicalpath,url) :: !external_libraries
let find_external_library logicalpath =
let rec aux = function
| [] -> raise Not_found
| (l,u)::rest ->
if String.length logicalpath > String.length l &
String.sub logicalpath 0 (String.length l + 1) = l ^"."
then u
else aux rest
in aux !external_libraries
let init_coqlib_library () = add_external_library "Coq" !coqlib
let find_module m =
if Hashtbl.mem local_modules m then
Local
else
try External (Filename.concat (find_external_library m) m)
with Not_found -> Unknown
type 'a index = {
idx_name : string;
idx_entries : (char * (string * 'a) list) list;
idx_size : int }
let map f i =
{ i with idx_entries =
List.map
(fun (c,l) -> (c, List.map (fun (s,x) -> (s,f s x)) l))
i.idx_entries }
let compare_entries (s1,_) (s2,_) = Alpha.compare_string s1 s2
let sort_entries el =
let t = Hashtbl.create 97 in
List.iter
(fun c -> Hashtbl.add t c [])
['A'; 'B'; 'C'; 'D'; 'E'; 'F'; 'G'; 'H'; 'I'; 'J'; 'K'; 'L'; 'M'; 'N';
'O'; 'P'; 'Q'; 'R'; 'S'; 'T'; 'U'; 'V'; 'W'; 'X'; 'Y'; 'Z'; '_'; '*'];
List.iter
(fun ((s,_) as e) ->
let c = Alpha.norm_char s.[0] in
let c,l =
try c,Hashtbl.find t c with Not_found -> '*',Hashtbl.find t '*' in
Hashtbl.replace t c (e :: l))
el;
let res = ref [] in
Hashtbl.iter (fun c l -> res := (c, List.sort compare_entries l) :: !res) t;
List.sort (fun (c1,_) (c2,_) -> Alpha.compare_char c1 c2) !res
let display_letter c = if c = '*' then "other" else String.make 1 c
let index_size = List.fold_left (fun s (_,l) -> s + List.length l) 0
let hashtbl_elements h = Hashtbl.fold (fun x y l -> (x,y)::l) h []
let type_name = function
| Library ->
let ln = !lib_name in
if ln <> "" then String.lowercase ln else "library"
| Module -> "module"
| Definition -> "definition"
| Inductive -> "inductive"
| Constructor -> "constructor"
| Lemma -> "lemma"
| Record -> "record"
| Projection -> "projection"
| Instance -> "instance"
| Class -> "class"
| Method -> "method"
| Variable -> "variable"
| Axiom -> "axiom"
| TacticDefinition -> "tactic"
| Abbreviation -> "abbreviation"
| Notation -> "notation"
| Section -> "section"
let prepare_entry s = function
| Notation ->
- non - printable characters < 32 are left encoded so that they
let err () = eprintf "Invalid notation in globalization file\n"; exit 1 in
let h = try String.index_from s 0 ':' with _ -> err () in
let i = try String.index_from s (h+1) ':' with _ -> err () in
let sc = String.sub s (h+1) (i-h-1) in
let ntn = String.make (String.length s - i) ' ' in
let k = ref 0 in
let j = ref (i+1) in
let quoted = ref false in
let l = String.length s - 1 in
while !j <= l do
if not !quoted then begin
(match s.[!j] with
| '_' -> ntn.[!k] <- ' '; incr k
| 'x' -> ntn.[!k] <- '_'; incr k
| '\'' -> quoted := true
| _ -> assert false)
end
else
if s.[!j] = '\'' then
if (!j = l || s.[!j+1] = '_') then quoted := false
else (incr j; ntn.[!k] <- s.[!j]; incr k)
else begin
ntn.[!k] <- s.[!j];
incr k
end;
incr j
done;
let ntn = String.sub ntn 0 !k in
if sc = "" then ntn else ntn ^ " (" ^ sc ^ ")"
| _ ->
s
let all_entries () =
let gl = ref [] in
let add_g s m t = gl := (s,(m,t)) :: !gl in
let bt = Hashtbl.create 11 in
let add_bt t s m =
let l = try Hashtbl.find bt t with Not_found -> [] in
Hashtbl.replace bt t ((s,m) :: l)
in
let classify m e = match e with
| Def (s,t) -> add_g s m t; add_bt t s m
| Ref _ | Mod _ -> ()
in
Hashtbl.iter classify deftable;
Hashtbl.iter (fun id m -> add_g id m Library; add_bt Library id m) modules;
{ idx_name = "global";
idx_entries = sort_entries !gl;
idx_size = List.length !gl },
Hashtbl.fold (fun t e l -> (t, { idx_name = type_name t;
idx_entries = sort_entries e;
idx_size = List.length e }) :: l) bt []
let type_of_string = function
| "def" | "coe" | "subclass" | "canonstruc" | "fix" | "cofix"
| "ex" | "scheme" -> Definition
| "prf" | "thm" -> Lemma
| "ind" | "coind" -> Inductive
| "constr" -> Constructor
| "rec" | "corec" -> Record
| "proj" -> Projection
| "class" -> Class
| "meth" -> Method
| "inst" -> Instance
| "var" -> Variable
| "defax" | "prfax" | "ax" -> Axiom
| "syndef" -> Abbreviation
| "not" -> Notation
| "lib" -> Library
| "mod" | "modtype" -> Module
| "tac" -> TacticDefinition
| "sec" -> Section
| s -> raise (Invalid_argument ("type_of_string:" ^ s))
let ill_formed_glob_file f =
eprintf "Warning: ill-formed file %s (links will not be available)\n" f
let outdated_glob_file f =
eprintf "Warning: %s not consistent with corresponding .v file (links will not be available)\n" f
let correct_file vfile f c =
let s = input_line c in
if String.length s < 7 || String.sub s 0 7 <> "DIGEST " then
(ill_formed_glob_file f; false)
else
let s = String.sub s 7 (String.length s - 7) in
match vfile, s with
| None, "NO" -> true
| Some _, "NO" -> ill_formed_glob_file f; false
| None, _ -> ill_formed_glob_file f; false
| Some vfile, s ->
s = Digest.to_hex (Digest.file vfile) || (outdated_glob_file f; false)
let read_glob vfile f =
let c = open_in f in
if correct_file vfile f c then
let cur_mod = ref "" in
try
while true do
let s = input_line c in
let n = String.length s in
if n > 0 then begin
match s.[0] with
| 'F' ->
cur_mod := String.sub s 1 (n - 1);
current_library := !cur_mod
| 'R' ->
(try
Scanf.sscanf s "R%d:%d %s %s %s %s"
(fun loc1 loc2 lib_dp sp id ty ->
for loc=loc1 to loc2 do
add_ref !cur_mod loc lib_dp sp id (type_of_string ty)
done)
with _ -> ())
| _ ->
try Scanf.sscanf s "not %d %s %s"
(fun loc sp id -> add_def loc loc (type_of_string "not") sp id)
with Scanf.Scan_failure _ ->
try Scanf.sscanf s "%s %d:%d %s %s"
(fun ty loc1 loc2 sp id ->
add_def loc1 loc2 (type_of_string ty) sp id)
with Scanf.Scan_failure _ -> ()
end
done; assert false
with End_of_file ->
close_in c
|
a5ccb7ae8d7a5b8cd626da411e24356629289a1ef6ca7d68665c071e378005cd | camlp5/camlp5 | asttypes.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
Auxiliary a.s.t . types used by parsetree and typedtree .
type constant =
Const_int of int
| Const_char of char
| Const_string of string * string option
| Const_float of string
| Const_int32 of int32
| Const_int64 of int64
| Const_nativeint of nativeint
type rec_flag = Nonrecursive | Recursive
type direction_flag = Upto | Downto
(* Order matters, used in polymorphic comparison *)
type private_flag = Private | Public
type mutable_flag = Immutable | Mutable
type virtual_flag = Virtual | Concrete
type override_flag = Override | Fresh
type closed_flag = Closed | Open
type label = string
type arg_label =
Nolabel
| Labelled of string (* label:T -> ... *)
| Optional of string (* ?label:T -> ... *)
type 'a loc = 'a Location.loc = {
txt : 'a;
loc : Location.t;
}
type variance =
| Covariant
| Contravariant
| Invariant
| null | https://raw.githubusercontent.com/camlp5/camlp5/15e03f56f55b2856dafe7dd3ca232799069f5dda/ocaml_stuff/4.03.1/parsing/asttypes.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Order matters, used in polymorphic comparison
label:T -> ...
?label:T -> ... | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
Auxiliary a.s.t . types used by parsetree and typedtree .
type constant =
Const_int of int
| Const_char of char
| Const_string of string * string option
| Const_float of string
| Const_int32 of int32
| Const_int64 of int64
| Const_nativeint of nativeint
type rec_flag = Nonrecursive | Recursive
type direction_flag = Upto | Downto
type private_flag = Private | Public
type mutable_flag = Immutable | Mutable
type virtual_flag = Virtual | Concrete
type override_flag = Override | Fresh
type closed_flag = Closed | Open
type label = string
type arg_label =
Nolabel
type 'a loc = 'a Location.loc = {
txt : 'a;
loc : Location.t;
}
type variance =
| Covariant
| Contravariant
| Invariant
|
a00fd0f958f1cb5086d20add8e78f25e5d3530ccf9c017967aca2ef64333e97a | JoelSanchez/ventas | api.cljs | (ns ventas.plugins.menu.api
(:require
[re-frame.core :as rf]))
(rf/reg-event-fx
::autocompletions.get
(fn [_ [_ options]]
{:ws-request (merge {:name :ventas.plugins.menu.core/autocompletions.get}
options)}))
(rf/reg-event-fx
::routes.get-name
(fn [_ [_ options]]
{:ws-request (merge {:name :ventas.plugins.menu.core/routes.get-name}
options)}))
(rf/reg-event-fx
::menus.get
(fn [_ [_ options]]
{:ws-request (merge {:name :ventas.plugins.menu.core/menu.get}
options)})) | null | https://raw.githubusercontent.com/JoelSanchez/ventas/dc8fc8ff9f63dfc8558ecdaacfc4983903b8e9a1/src/cljs/ventas/plugins/menu/api.cljs | clojure | (ns ventas.plugins.menu.api
(:require
[re-frame.core :as rf]))
(rf/reg-event-fx
::autocompletions.get
(fn [_ [_ options]]
{:ws-request (merge {:name :ventas.plugins.menu.core/autocompletions.get}
options)}))
(rf/reg-event-fx
::routes.get-name
(fn [_ [_ options]]
{:ws-request (merge {:name :ventas.plugins.menu.core/routes.get-name}
options)}))
(rf/reg-event-fx
::menus.get
(fn [_ [_ options]]
{:ws-request (merge {:name :ventas.plugins.menu.core/menu.get}
options)})) | |
d7c3c105f05afcb3d6bd122ebec048ab959c3fb46e5de9a87b852091f0ea9e36 | staples-sparx/kits | firehose.clj | (ns kits.firehose
"Infinite lazy seqs that can be globally turned on/off.
Originally used for memory profiling."
(:refer-clojure :exclude [cycle repeat]))
(defonce off? (atom false))
(defonce sleep-millis (atom 100))
(defn repeat [x]
(lazy-seq
(if @off?
nil
(do
(when (> @sleep-millis 0)
(Thread/sleep @sleep-millis))
(cons x (repeat x))))))
(defn cycle [coll]
(lazy-seq
(when-let [s (if @off?
nil
(seq coll))]
(do
(when (> @sleep-millis 0)
(Thread/sleep @sleep-millis))
(concat s (cycle s))))))
(defn on! []
(reset! off? false))
(defn off! []
(reset! off? true))
| null | https://raw.githubusercontent.com/staples-sparx/kits/66ae99bce83e8fd1248cc5c0da1f23673f221073/src/clojure/kits/firehose.clj | clojure | (ns kits.firehose
"Infinite lazy seqs that can be globally turned on/off.
Originally used for memory profiling."
(:refer-clojure :exclude [cycle repeat]))
(defonce off? (atom false))
(defonce sleep-millis (atom 100))
(defn repeat [x]
(lazy-seq
(if @off?
nil
(do
(when (> @sleep-millis 0)
(Thread/sleep @sleep-millis))
(cons x (repeat x))))))
(defn cycle [coll]
(lazy-seq
(when-let [s (if @off?
nil
(seq coll))]
(do
(when (> @sleep-millis 0)
(Thread/sleep @sleep-millis))
(concat s (cycle s))))))
(defn on! []
(reset! off? false))
(defn off! []
(reset! off? true))
| |
07734fa7032273687ab4e5bb10daaeca573370e6d5e4716dabc6ca27d1d56dc8 | reasonml-old/BetterErrors | func_no_arg_call.ml | let asd () = 5;;
print_int asd;;
(* err bc func with 0 arg need to be appended () *)
let asd () = 5;;
print_int (asd ());;
| null | https://raw.githubusercontent.com/reasonml-old/BetterErrors/d439b92bfe377689c38fded5d8aa2b151133f25d/errs/func_no_arg_call.ml | ocaml | err bc func with 0 arg need to be appended () | let asd () = 5;;
print_int asd;;
let asd () = 5;;
print_int (asd ());;
|
ee17f791679fcc69eb259cb4b791ff0be248b4dafbbfc12539185dc42f593e74 | thheller/shadow-cljs | fs_watch.clj | (ns shadow.cljs.devtools.server.fs-watch
(:require [shadow.build.api :as cljs]
[clojure.core.async :as async :refer (alt!! thread >!!)]
[shadow.cljs.devtools.server.util :as util]
[shadow.cljs.devtools.server.system-bus :as system-bus]
[clojure.java.io :as io]
[clojure.string :as str]
[shadow.build.resource :as rc])
(:import (shadow.util FileWatcher)
(java.io File)))
(defn service? [x]
(and (map? x)
(::service x)))
(defn poll-changes [{:keys [dir ^FileWatcher watcher]}]
(let [changes (.pollForChanges watcher)]
(when (seq changes)
(->> changes
(map (fn [[name event]]
{:dir dir
:name (rc/normalize-name name)
:ext (when-let [x (str/last-index-of name ".")]
(subs name (inc x)))
:file (io/file dir name)
:event event}))
;; ignore empty files
(remove (fn [{:keys [event ^File file] :as x}]
(and (not= event :del)
(zero? (.length file)))))
))))
(defn watch-loop
[{:keys [loop-wait] :or {loop-wait 500}} watch-dirs control publish-fn]
(loop []
(alt!!
control
([_]
:terminated)
(async/timeout loop-wait)
([_]
(let [fs-updates
(->> watch-dirs
(mapcat poll-changes)
(into []))]
(when (seq fs-updates)
(publish-fn fs-updates))
(recur)))))
;; shut down watchers when loop ends
(doseq [{:keys [^FileWatcher watcher]} watch-dirs]
(.close watcher))
::shutdown-complete)
(defn start [config directories file-exts publish-fn]
{:pre [(every? #(instance? File %) directories)
(coll? file-exts)
(every? string? file-exts)]}
(let [control
(async/chan)
watch-dirs
(->> directories
(map (fn [^File dir]
{:dir dir
:watcher (FileWatcher/create dir (vec file-exts))}))
(into []))]
{::service true
:control control
:watch-dirs watch-dirs
:thread (thread (watch-loop config watch-dirs control publish-fn))}))
(defn stop [{:keys [control thread] :as svc}]
{:pre [(service? svc)]}
(async/close! control)
(async/<!! thread))
| null | https://raw.githubusercontent.com/thheller/shadow-cljs/f7e5b47bc2cb0b7aeac895e8febfc61c31d1652f/src/main/shadow/cljs/devtools/server/fs_watch.clj | clojure | ignore empty files
shut down watchers when loop ends | (ns shadow.cljs.devtools.server.fs-watch
(:require [shadow.build.api :as cljs]
[clojure.core.async :as async :refer (alt!! thread >!!)]
[shadow.cljs.devtools.server.util :as util]
[shadow.cljs.devtools.server.system-bus :as system-bus]
[clojure.java.io :as io]
[clojure.string :as str]
[shadow.build.resource :as rc])
(:import (shadow.util FileWatcher)
(java.io File)))
(defn service? [x]
(and (map? x)
(::service x)))
(defn poll-changes [{:keys [dir ^FileWatcher watcher]}]
(let [changes (.pollForChanges watcher)]
(when (seq changes)
(->> changes
(map (fn [[name event]]
{:dir dir
:name (rc/normalize-name name)
:ext (when-let [x (str/last-index-of name ".")]
(subs name (inc x)))
:file (io/file dir name)
:event event}))
(remove (fn [{:keys [event ^File file] :as x}]
(and (not= event :del)
(zero? (.length file)))))
))))
(defn watch-loop
[{:keys [loop-wait] :or {loop-wait 500}} watch-dirs control publish-fn]
(loop []
(alt!!
control
([_]
:terminated)
(async/timeout loop-wait)
([_]
(let [fs-updates
(->> watch-dirs
(mapcat poll-changes)
(into []))]
(when (seq fs-updates)
(publish-fn fs-updates))
(recur)))))
(doseq [{:keys [^FileWatcher watcher]} watch-dirs]
(.close watcher))
::shutdown-complete)
(defn start [config directories file-exts publish-fn]
{:pre [(every? #(instance? File %) directories)
(coll? file-exts)
(every? string? file-exts)]}
(let [control
(async/chan)
watch-dirs
(->> directories
(map (fn [^File dir]
{:dir dir
:watcher (FileWatcher/create dir (vec file-exts))}))
(into []))]
{::service true
:control control
:watch-dirs watch-dirs
:thread (thread (watch-loop config watch-dirs control publish-fn))}))
(defn stop [{:keys [control thread] :as svc}]
{:pre [(service? svc)]}
(async/close! control)
(async/<!! thread))
|
0f3c2667e6815c5cc8aa85a72f246363a1f3c31eb8abc90927d985ccd92c7de7 | ecavallo/ptt | eval.ml | module Syn = Syntax
module D = Domain
exception Eval_failed of string
let eval_dim r (env : D.env) =
match r with
| Syn.DVar i ->
begin
match List.nth env i with
| D.TopLevel _ -> raise (Eval_failed "Not a dimension term")
| D.Dim s -> s
| D.Tm _ -> raise (Eval_failed "Not a dimension term")
end
| Syn.Const o -> D.Const o
let rec do_clos size clo a =
match clo with
| D.ConstClos t -> t
| D.Clos {term; env} -> eval term (a :: env) size
| D.Pseudo {var; term; ends} ->
begin
match a with
| D.TopLevel _ -> raise (Eval_failed "Applied psuedo-closure to term")
| D.Dim (D.DVar i) -> D.instantiate i var term
| D.Dim (D.Const o) -> List.nth ends o
| D.Tm _ -> raise (Eval_failed "Applied psuedo-closure to term")
end
and do_clos2 size (D.Clos2 {term; env}) a1 a2 =
eval term (a2 :: a1 :: env) size
and do_clos3 size (D.Clos3 {term; env}) t1 t2 t3 =
eval term (D.Tm t3 :: D.Tm t2 :: D.Tm t1 :: env) size
and do_closN size (D.ClosN {term; env}) tN =
eval term (List.rev_append (List.map (fun t -> D.Tm t) tN) env) size
and do_clos_extent size (D.ClosN {term; env}) tN t r =
eval term (D.Dim r :: D.Tm t :: List.rev_append (List.map (fun t -> D.Tm t) tN) env) size
and do_consts size clo width =
match clo with
| D.ConstClos t ->
List.init width (fun _ -> t)
| D.Clos {term; env} ->
List.init width (fun o -> eval term (D.Dim (D.Const o) :: env) size)
| D.Pseudo {ends; _} -> ends
and do_rec size tp zero suc n =
match n with
| D.Zero -> zero
| D.Suc n -> do_clos2 size suc (D.Tm n) (D.Tm (do_rec size tp zero suc n))
| D.Neutral {term; _} ->
let final_tp = do_clos size tp (D.Tm n) in
D.Neutral {tp = final_tp; term = D.(NRec (tp, zero, suc) @: term)}
| _ -> raise (Eval_failed "Not a number")
and do_list_rec size mot nil cons l =
match l with
| D.Nil -> nil
| D.Cons (a, l) ->
do_clos3 size cons a l (do_list_rec size mot nil cons l)
| D.Neutral {term; tp} ->
let dom = do_list_tp tp in
let final_tp = do_clos size mot (D.Tm l) in
D.Neutral {tp = final_tp; term = D.(ListRec (dom, mot, nil, cons) @: term)}
| _ -> raise (Eval_failed "Not a list")
and do_if size mot tt ff b =
match b with
| D.True -> tt
| D.False -> ff
| D.Neutral {term; _} ->
let final_tp = do_clos size mot (D.Tm b) in
D.Neutral {tp = final_tp; term = D.(If (mot, tt, ff) @: term)}
| _ -> raise (Eval_failed "Not a boolean")
and do_case size mot inl inr co =
match co with
| D.Inl t -> do_clos size inl (D.Tm t)
| D.Inr t -> do_clos size inr (D.Tm t)
| D.Neutral {term; tp} ->
let left = do_coprod_left tp in
let right = do_coprod_right tp in
let final_tp = do_clos size mot (D.Tm co) in
D.Neutral {tp = final_tp; term = D.(Case (left, right, mot, inl, inr) @: term)}
| _ -> raise (Eval_failed "Not a coproduct")
and do_abort size mot vd =
match vd with
| D.Neutral {term; _} ->
let final_tp = do_clos size mot (D.Tm vd) in
D.Neutral {tp = final_tp; term = D.(Abort mot @: term)}
| _ -> raise (Eval_failed "Not a void")
and do_fst p =
match p with
| D.Pair (p1, _) -> p1
| D.Neutral {tp; term} ->
D.Neutral {tp = do_sg_dom tp; term = D.(Fst @: term)}
| _ -> raise (Eval_failed "Couldn't fst argument in do_fst")
and do_snd size p =
match p with
| D.Pair (_, p2) -> p2
| D.Neutral {tp; term} ->
let fst = do_fst p in
D.Neutral {tp = do_sg_cod size tp fst; term = D.(Snd @: term)}
| _ -> raise (Eval_failed "Couldn't snd argument in do_snd")
and do_bapp size t r =
match t with
| D.BLam bclo -> do_clos size bclo (D.Dim r)
| D.Neutral {tp; term} ->
begin
match r with
| D.DVar _ ->
let dst = do_bridge_cod size tp r in
D.Neutral {tp = dst; term = D.(BApp r @: term)}
| Const o ->
do_bridge_endpoint size tp term o
end
| _ -> raise (Eval_failed "Not a bridge or neutral in bapp")
and do_j size mot refl eq =
match eq with
| D.Refl t -> do_clos size refl (D.Tm t)
| D.Neutral {tp; term = term} ->
let dom = do_id_tp tp in
let left = do_id_left tp in
let right = do_id_right tp in
D.Neutral
{tp = do_clos3 size mot left right eq;
term = D.(J (mot, refl, dom, left, right) @: term)}
| _ -> raise (Eval_failed "Not a refl or neutral in do_j")
and do_ap size f a =
match f with
| D.Lam clos -> do_clos size clos (D.Tm a)
| D.Neutral {tp; term} ->
let src = do_pi_dom tp in
let dst = do_pi_cod size tp a in
D.Neutral {tp = dst; term = D.(Ap (D.Normal {tp = src; term = a}) @: term)}
| _ -> raise (Eval_failed "Not a function in do_ap")
and do_ungel size ends mot gel case =
begin
match gel with
| D.Engel (_, _, t) -> do_clos size case (D.Tm t)
| D.Neutral {tp; term} ->
let rel = do_gel_rel size tp ends in
let bri = do_gel_bridge size tp ends in
let final_tp =
do_clos size mot (D.Tm (D.BLam (D.Pseudo {var = size; term = gel; ends}))) in
D.Neutral {tp = final_tp; term = D.(Ungel (ends, rel, bri, mot, size, case) @: term)}
| _ -> raise (Eval_failed "Not a gel or neutral in do_ungel")
end
and do_uncodisc t =
match t with
| D.Encodisc t -> t
| D.Neutral {tp; term} ->
D.Neutral {tp = do_codisc_tp tp; term = D.(Uncodisc @: term)}
| _ -> raise (Eval_failed "Couldn't uncodisc argument in do_uncodisc")
and do_unglobe t =
match t with
| D.Englobe t -> t
| D.Neutral {tp; term} ->
D.Neutral {tp = do_global_tp tp; term = D.(Unglobe @: term)}
| _ -> raise (Eval_failed "Couldn't unglobe argument in do_unglobe")
and do_letdisc size m mot case d =
match d with
| D.Endisc t -> do_clos size case (D.Tm t)
| D.Neutral {tp; term} ->
let inner_tp = do_disc_tp tp in
D.Neutral {tp = do_clos size mot (D.Tm d); term = D.(Letdisc (m, inner_tp, mot, case) @: term)}
| _ -> raise (Eval_failed "Not an endisc or neutral in do_letdisc")
and do_letdiscbridge size m ends mot case d =
match d with
| D.Endisc t -> do_clos size case (D.Tm t)
| D.Neutral {tp; term} ->
let inner_tp = do_disc_tp tp in
let final_tp =
do_clos size mot (D.Tm (D.BLam (D.Pseudo {var = size; term = d; ends}))) in
D.Neutral {tp = final_tp; term = D.(Letdiscbridge (m, inner_tp, ends, mot, case, size) @: term)}
| _ -> raise (Eval_failed "Not an endisc or neutral in do_letdiscbridge")
and do_list_tp tp =
match tp with
| D.List tp -> tp
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi ListTp @: term)}
| _ -> raise (Eval_failed "Not something that can become a list type")
and do_coprod_left tp =
match tp with
| D.Coprod (t, _) -> t
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi CoprodLeft @: term)}
| _ -> raise (Eval_failed "Not something that can become a coproduct type")
and do_coprod_right tp =
match tp with
| D.Coprod (_, t) -> t
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi CoprodRight @: term)}
| _ -> raise (Eval_failed "Not something that can become a coproduct type")
and do_id_tp tp =
match tp with
| D.Id (tp, _, _) -> tp
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi IdTp @: term)}
| _ -> raise (Eval_failed "Not something that can become a identity type")
and do_id_left tp =
match tp with
| D.Id (_, l, _) -> l
| D.Neutral {tp; term} ->
D.Neutral {tp = D.(Neutral {tp; term = Quasi IdTp @: term}); term = D.(Quasi IdLeft @: term)}
| _ -> raise (Eval_failed "Not something that can become a identity type")
and do_id_right tp =
match tp with
| D.Id (_, _, r) -> r
| D.Neutral {tp; term} ->
D.Neutral {tp = D.(Neutral {tp; term = Quasi IdTp @: term}); term = D.(Quasi IdRight @: term)}
| _ -> raise (Eval_failed "Not something that can become a identity type")
and do_bridge_cod size tp s =
match tp with
| D.Bridge (clos, _) ->
do_clos size clos (D.Dim s)
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi (BridgeCod s) @: term)}
| _ -> raise (Eval_failed "Not something that can be come a bridge type")
and do_bridge_endpoint size tp ne o =
match tp with
| D.Bridge (_, ts) ->
begin
match List.nth ts o with
| Some t -> t
| None ->
let dst = do_bridge_cod size tp (D.Const o) in
D.Neutral {tp = dst; term = D.(BApp (Const o) @: ne)}
end
| D.Neutral {tp; term} ->
D.Neutral
{tp = D.Neutral {tp; term = D.(Quasi (BridgeCod (D.Const o)) @: term)};
term = D.(Quasi (BridgeEndpoint (term, o)) @: term)}
| _ -> raise (Eval_failed "Not something that can be come a bridge type")
and do_pi_dom f =
match f with
| D.Pi (_, tp, _) -> tp
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi PiDom @: term)}
| _ -> raise (Eval_failed "Not something that can become a pi type")
and do_pi_cod size f a =
match f with
| D.Pi (_, _, dst) -> do_clos size dst (D.Tm a)
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi (PiCod a) @: term)}
| _ -> raise (Eval_failed "Not something that can become a pi type")
and do_sg_dom f =
match f with
| D.Sg (tp, _) -> tp
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi SgDom @: term)}
| _ -> raise (Eval_failed "Not something that can become a sigma type")
and do_sg_cod size f a =
match f with
| D.Sg (_,dst) -> do_clos size dst (D.Tm a)
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi (SgCod a) @: term)}
| _ -> raise (Eval_failed "Not something that can become a sigma type")
and do_gel_rel size f end_tms =
match f with
| D.Gel (_, _, rel) -> do_closN size rel end_tms
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi (GelRel end_tms) @: term)}
| _ -> raise (Eval_failed "Not something that can become a gel type")
and do_gel_bridge size f end_tms =
match f with
| D.Gel (_, end_tps, rel) ->
D.Bridge
(D.Pseudo {var = size; term = D.Gel (size, end_tps, rel); ends = end_tps},
List.map Option.some end_tms)
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi (GelBridge end_tms) @: term)}
| _ -> raise (Eval_failed "Not something that can become a gel type")
and do_codisc_tp f =
match f with
| D.Codisc tp -> tp
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi CodiscTp @: term)}
| _ -> raise (Eval_failed "Not something that can become a discrete type")
and do_global_tp f =
match f with
| D.Global tp -> tp
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi GlobalTp @: term)}
| _ -> raise (Eval_failed "Not something that can become a global type")
and do_disc_tp f =
match f with
| D.Disc tp -> tp
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi DiscTp @: term)}
| _ -> raise (Eval_failed "Not something that can become a discrete type")
and eval t (env : D.env) size =
match t with
| Syn.Var i ->
begin
match List.nth env i with
| D.TopLevel t -> t
| D.Tm t -> t
| D.Dim _-> raise (Eval_failed "Not a term variable")
end
| Syn.Let (def, body) -> eval body (D.Tm (eval def env size) :: env) size
| Syn.Check (term, _) -> eval term env size
| Syn.Unit -> D.Unit
| Syn.Triv -> D.Triv
| Syn.Nat -> D.Nat
| Syn.List t -> D.List (eval t env size)
| Syn.Zero -> D.Zero
| Syn.Suc t -> D.Suc (eval t env size)
| Syn.NRec (tp, zero, suc, n) ->
do_rec size
(Clos {term = tp; env})
(eval zero env size)
(Clos2 {term = suc; env})
(eval n env size)
| Syn.Nil -> D.Nil
| Syn.Cons (a, t) -> D.Cons (eval a env size, eval t env size)
| Syn.ListRec (mot, nil, cons, l) ->
do_list_rec size
(Clos {term = mot; env})
(eval nil env size)
(Clos3 {term = cons; env})
(eval l env size)
| Syn.Bool -> D.Bool
| Syn.True -> D.True
| Syn.False -> D.False
| Syn.If (mot, tt, ff, b) ->
do_if size
(Clos {term = mot; env})
(eval tt env size)
(eval ff env size)
(eval b env size)
| Syn.Coprod (t1, t2) -> D.Coprod (eval t1 env size, eval t2 env size)
| Syn.Inl t -> D.Inl (eval t env size)
| Syn.Inr t -> D.Inr (eval t env size)
| Syn.Case (mot, inl, inr, co) ->
do_case size
(Clos {term = mot; env})
(Clos {term = inl; env})
(Clos {term = inr; env})
(eval co env size)
| Syn.Void -> D.Void
| Syn.Abort (mot, vd) ->
do_abort size (Clos {term = mot; env}) (eval vd env size)
| Syn.Pi (m, src, dest) ->
D.Pi (m, eval src env size, (Clos {term = dest; env}))
| Syn.Lam t -> D.Lam (Clos {term = t; env})
| Syn.Ap (t1, t2) -> do_ap size (eval t1 env size) (eval t2 env size)
| Syn.Uni i -> D.Uni i
| Syn.Sg (t1, t2) -> D.Sg (eval t1 env size, (Clos {term = t2; env}))
| Syn.Pair (t1, t2) -> D.Pair (eval t1 env size, eval t2 env size)
| Syn.Fst t -> do_fst (eval t env size)
| Syn.Snd t -> do_snd size (eval t env size)
| Syn.Bridge (dest, ts) ->
D.Bridge (Clos {term = dest; env}, List.map (Option.map (fun t -> eval t env size)) ts)
| Syn.BApp (t,r) ->
let r' = eval_dim r env in
do_bapp size (eval t env size) r'
| Syn.BLam t -> D.BLam (Clos {term = t; env})
| Syn.Refl t -> D.Refl (eval t env size)
| Syn.Id (tp, left, right) -> D.Id (eval tp env size, eval left env size, eval right env size)
| Syn.J (mot, refl, eq) ->
do_j size (D.Clos3 {term = mot; env}) (D.Clos {term = refl; env}) (eval eq env size)
| Syn.Extent (r, dom, mot, ctx, endcase, varcase) ->
let r' = eval_dim r env in
let ctx' = eval ctx env size in
begin
match r' with
| D.DVar i ->
let final_tp = eval mot (D.Tm ctx' :: D.Dim r' :: env) size in
let ext =
D.Ext
{var = i;
dom = D.Clos {term = dom; env};
mot = D.Clos2 {term = mot; env};
ctx = ctx';
endcase = List.map (fun t -> D.Clos {term = t; env}) endcase;
varcase = D.ClosN {term = varcase; env}}
in
D.Neutral {tp = final_tp; term = D.root ext}
| D.Const o ->
eval (List.nth endcase o) (D.Tm ctx' :: env) size
end
| Syn.Gel (r, endtps, rel) ->
begin
let r' = eval_dim r env in
match r' with
| D.DVar i -> D.Gel (i, List.map (fun t -> eval t env size) endtps, D.ClosN {term = rel; env})
| D.Const o -> eval (List.nth endtps o) env size
end
| Syn.Engel (i, ts, t) ->
begin
let r' = eval_dim (Syn.DVar i) env in
match r' with
| D.DVar i' -> D.Engel (i', List.map (fun t -> eval t env size) ts, eval t env size)
| Const o -> eval (List.nth ts o) env size
end
| Syn.Ungel (width, mot, gel, case) ->
do_ungel
size
(do_consts size (D.Clos {term = gel; env}) width)
(D.Clos {term = mot; env})
(eval gel (D.Dim (D.DVar size) :: env) (size + 1))
(D.Clos {term = case; env})
| Syn.Codisc t -> D.Codisc (eval t env size)
| Syn.Encodisc t -> D.Encodisc (eval t env size)
| Syn.Uncodisc t -> do_uncodisc (eval t env size)
| Syn.Global t -> D.Global (eval t env size)
| Syn.Englobe t -> D.Englobe (eval t env size)
| Syn.Unglobe t -> do_unglobe (eval t env size)
| Syn.Disc t -> D.Disc (eval t env size)
| Syn.Endisc t -> D.Endisc (eval t env size)
| Syn.Letdisc (m, mot, case, d) ->
do_letdisc
size
m
(D.Clos {term = mot; env})
(D.Clos {term = case; env})
(eval d env size)
| Syn.Letdiscbridge (m, width, mot, case, d) ->
do_letdiscbridge
size
m
(do_consts size (D.Clos {term = d; env}) width)
(D.Clos {term = mot; env})
(D.Clos {term = case; env})
(eval d (D.Dim (D.DVar size) :: env) (size + 1))
| null | https://raw.githubusercontent.com/ecavallo/ptt/1234c3b645e1b99307c7a44cad87ffff382528f9/src/lib/eval.ml | ocaml | module Syn = Syntax
module D = Domain
exception Eval_failed of string
let eval_dim r (env : D.env) =
match r with
| Syn.DVar i ->
begin
match List.nth env i with
| D.TopLevel _ -> raise (Eval_failed "Not a dimension term")
| D.Dim s -> s
| D.Tm _ -> raise (Eval_failed "Not a dimension term")
end
| Syn.Const o -> D.Const o
let rec do_clos size clo a =
match clo with
| D.ConstClos t -> t
| D.Clos {term; env} -> eval term (a :: env) size
| D.Pseudo {var; term; ends} ->
begin
match a with
| D.TopLevel _ -> raise (Eval_failed "Applied psuedo-closure to term")
| D.Dim (D.DVar i) -> D.instantiate i var term
| D.Dim (D.Const o) -> List.nth ends o
| D.Tm _ -> raise (Eval_failed "Applied psuedo-closure to term")
end
and do_clos2 size (D.Clos2 {term; env}) a1 a2 =
eval term (a2 :: a1 :: env) size
and do_clos3 size (D.Clos3 {term; env}) t1 t2 t3 =
eval term (D.Tm t3 :: D.Tm t2 :: D.Tm t1 :: env) size
and do_closN size (D.ClosN {term; env}) tN =
eval term (List.rev_append (List.map (fun t -> D.Tm t) tN) env) size
and do_clos_extent size (D.ClosN {term; env}) tN t r =
eval term (D.Dim r :: D.Tm t :: List.rev_append (List.map (fun t -> D.Tm t) tN) env) size
and do_consts size clo width =
match clo with
| D.ConstClos t ->
List.init width (fun _ -> t)
| D.Clos {term; env} ->
List.init width (fun o -> eval term (D.Dim (D.Const o) :: env) size)
| D.Pseudo {ends; _} -> ends
and do_rec size tp zero suc n =
match n with
| D.Zero -> zero
| D.Suc n -> do_clos2 size suc (D.Tm n) (D.Tm (do_rec size tp zero suc n))
| D.Neutral {term; _} ->
let final_tp = do_clos size tp (D.Tm n) in
D.Neutral {tp = final_tp; term = D.(NRec (tp, zero, suc) @: term)}
| _ -> raise (Eval_failed "Not a number")
and do_list_rec size mot nil cons l =
match l with
| D.Nil -> nil
| D.Cons (a, l) ->
do_clos3 size cons a l (do_list_rec size mot nil cons l)
| D.Neutral {term; tp} ->
let dom = do_list_tp tp in
let final_tp = do_clos size mot (D.Tm l) in
D.Neutral {tp = final_tp; term = D.(ListRec (dom, mot, nil, cons) @: term)}
| _ -> raise (Eval_failed "Not a list")
and do_if size mot tt ff b =
match b with
| D.True -> tt
| D.False -> ff
| D.Neutral {term; _} ->
let final_tp = do_clos size mot (D.Tm b) in
D.Neutral {tp = final_tp; term = D.(If (mot, tt, ff) @: term)}
| _ -> raise (Eval_failed "Not a boolean")
and do_case size mot inl inr co =
match co with
| D.Inl t -> do_clos size inl (D.Tm t)
| D.Inr t -> do_clos size inr (D.Tm t)
| D.Neutral {term; tp} ->
let left = do_coprod_left tp in
let right = do_coprod_right tp in
let final_tp = do_clos size mot (D.Tm co) in
D.Neutral {tp = final_tp; term = D.(Case (left, right, mot, inl, inr) @: term)}
| _ -> raise (Eval_failed "Not a coproduct")
and do_abort size mot vd =
match vd with
| D.Neutral {term; _} ->
let final_tp = do_clos size mot (D.Tm vd) in
D.Neutral {tp = final_tp; term = D.(Abort mot @: term)}
| _ -> raise (Eval_failed "Not a void")
and do_fst p =
match p with
| D.Pair (p1, _) -> p1
| D.Neutral {tp; term} ->
D.Neutral {tp = do_sg_dom tp; term = D.(Fst @: term)}
| _ -> raise (Eval_failed "Couldn't fst argument in do_fst")
and do_snd size p =
match p with
| D.Pair (_, p2) -> p2
| D.Neutral {tp; term} ->
let fst = do_fst p in
D.Neutral {tp = do_sg_cod size tp fst; term = D.(Snd @: term)}
| _ -> raise (Eval_failed "Couldn't snd argument in do_snd")
and do_bapp size t r =
match t with
| D.BLam bclo -> do_clos size bclo (D.Dim r)
| D.Neutral {tp; term} ->
begin
match r with
| D.DVar _ ->
let dst = do_bridge_cod size tp r in
D.Neutral {tp = dst; term = D.(BApp r @: term)}
| Const o ->
do_bridge_endpoint size tp term o
end
| _ -> raise (Eval_failed "Not a bridge or neutral in bapp")
and do_j size mot refl eq =
match eq with
| D.Refl t -> do_clos size refl (D.Tm t)
| D.Neutral {tp; term = term} ->
let dom = do_id_tp tp in
let left = do_id_left tp in
let right = do_id_right tp in
D.Neutral
{tp = do_clos3 size mot left right eq;
term = D.(J (mot, refl, dom, left, right) @: term)}
| _ -> raise (Eval_failed "Not a refl or neutral in do_j")
and do_ap size f a =
match f with
| D.Lam clos -> do_clos size clos (D.Tm a)
| D.Neutral {tp; term} ->
let src = do_pi_dom tp in
let dst = do_pi_cod size tp a in
D.Neutral {tp = dst; term = D.(Ap (D.Normal {tp = src; term = a}) @: term)}
| _ -> raise (Eval_failed "Not a function in do_ap")
and do_ungel size ends mot gel case =
begin
match gel with
| D.Engel (_, _, t) -> do_clos size case (D.Tm t)
| D.Neutral {tp; term} ->
let rel = do_gel_rel size tp ends in
let bri = do_gel_bridge size tp ends in
let final_tp =
do_clos size mot (D.Tm (D.BLam (D.Pseudo {var = size; term = gel; ends}))) in
D.Neutral {tp = final_tp; term = D.(Ungel (ends, rel, bri, mot, size, case) @: term)}
| _ -> raise (Eval_failed "Not a gel or neutral in do_ungel")
end
and do_uncodisc t =
match t with
| D.Encodisc t -> t
| D.Neutral {tp; term} ->
D.Neutral {tp = do_codisc_tp tp; term = D.(Uncodisc @: term)}
| _ -> raise (Eval_failed "Couldn't uncodisc argument in do_uncodisc")
and do_unglobe t =
match t with
| D.Englobe t -> t
| D.Neutral {tp; term} ->
D.Neutral {tp = do_global_tp tp; term = D.(Unglobe @: term)}
| _ -> raise (Eval_failed "Couldn't unglobe argument in do_unglobe")
and do_letdisc size m mot case d =
match d with
| D.Endisc t -> do_clos size case (D.Tm t)
| D.Neutral {tp; term} ->
let inner_tp = do_disc_tp tp in
D.Neutral {tp = do_clos size mot (D.Tm d); term = D.(Letdisc (m, inner_tp, mot, case) @: term)}
| _ -> raise (Eval_failed "Not an endisc or neutral in do_letdisc")
and do_letdiscbridge size m ends mot case d =
match d with
| D.Endisc t -> do_clos size case (D.Tm t)
| D.Neutral {tp; term} ->
let inner_tp = do_disc_tp tp in
let final_tp =
do_clos size mot (D.Tm (D.BLam (D.Pseudo {var = size; term = d; ends}))) in
D.Neutral {tp = final_tp; term = D.(Letdiscbridge (m, inner_tp, ends, mot, case, size) @: term)}
| _ -> raise (Eval_failed "Not an endisc or neutral in do_letdiscbridge")
and do_list_tp tp =
match tp with
| D.List tp -> tp
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi ListTp @: term)}
| _ -> raise (Eval_failed "Not something that can become a list type")
and do_coprod_left tp =
match tp with
| D.Coprod (t, _) -> t
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi CoprodLeft @: term)}
| _ -> raise (Eval_failed "Not something that can become a coproduct type")
and do_coprod_right tp =
match tp with
| D.Coprod (_, t) -> t
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi CoprodRight @: term)}
| _ -> raise (Eval_failed "Not something that can become a coproduct type")
and do_id_tp tp =
match tp with
| D.Id (tp, _, _) -> tp
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi IdTp @: term)}
| _ -> raise (Eval_failed "Not something that can become a identity type")
and do_id_left tp =
match tp with
| D.Id (_, l, _) -> l
| D.Neutral {tp; term} ->
D.Neutral {tp = D.(Neutral {tp; term = Quasi IdTp @: term}); term = D.(Quasi IdLeft @: term)}
| _ -> raise (Eval_failed "Not something that can become a identity type")
and do_id_right tp =
match tp with
| D.Id (_, _, r) -> r
| D.Neutral {tp; term} ->
D.Neutral {tp = D.(Neutral {tp; term = Quasi IdTp @: term}); term = D.(Quasi IdRight @: term)}
| _ -> raise (Eval_failed "Not something that can become a identity type")
and do_bridge_cod size tp s =
match tp with
| D.Bridge (clos, _) ->
do_clos size clos (D.Dim s)
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi (BridgeCod s) @: term)}
| _ -> raise (Eval_failed "Not something that can be come a bridge type")
and do_bridge_endpoint size tp ne o =
match tp with
| D.Bridge (_, ts) ->
begin
match List.nth ts o with
| Some t -> t
| None ->
let dst = do_bridge_cod size tp (D.Const o) in
D.Neutral {tp = dst; term = D.(BApp (Const o) @: ne)}
end
| D.Neutral {tp; term} ->
D.Neutral
{tp = D.Neutral {tp; term = D.(Quasi (BridgeCod (D.Const o)) @: term)};
term = D.(Quasi (BridgeEndpoint (term, o)) @: term)}
| _ -> raise (Eval_failed "Not something that can be come a bridge type")
and do_pi_dom f =
match f with
| D.Pi (_, tp, _) -> tp
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi PiDom @: term)}
| _ -> raise (Eval_failed "Not something that can become a pi type")
and do_pi_cod size f a =
match f with
| D.Pi (_, _, dst) -> do_clos size dst (D.Tm a)
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi (PiCod a) @: term)}
| _ -> raise (Eval_failed "Not something that can become a pi type")
and do_sg_dom f =
match f with
| D.Sg (tp, _) -> tp
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi SgDom @: term)}
| _ -> raise (Eval_failed "Not something that can become a sigma type")
and do_sg_cod size f a =
match f with
| D.Sg (_,dst) -> do_clos size dst (D.Tm a)
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi (SgCod a) @: term)}
| _ -> raise (Eval_failed "Not something that can become a sigma type")
and do_gel_rel size f end_tms =
match f with
| D.Gel (_, _, rel) -> do_closN size rel end_tms
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi (GelRel end_tms) @: term)}
| _ -> raise (Eval_failed "Not something that can become a gel type")
and do_gel_bridge size f end_tms =
match f with
| D.Gel (_, end_tps, rel) ->
D.Bridge
(D.Pseudo {var = size; term = D.Gel (size, end_tps, rel); ends = end_tps},
List.map Option.some end_tms)
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi (GelBridge end_tms) @: term)}
| _ -> raise (Eval_failed "Not something that can become a gel type")
and do_codisc_tp f =
match f with
| D.Codisc tp -> tp
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi CodiscTp @: term)}
| _ -> raise (Eval_failed "Not something that can become a discrete type")
and do_global_tp f =
match f with
| D.Global tp -> tp
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi GlobalTp @: term)}
| _ -> raise (Eval_failed "Not something that can become a global type")
and do_disc_tp f =
match f with
| D.Disc tp -> tp
| D.Neutral {tp; term} ->
D.Neutral {tp; term = D.(Quasi DiscTp @: term)}
| _ -> raise (Eval_failed "Not something that can become a discrete type")
and eval t (env : D.env) size =
match t with
| Syn.Var i ->
begin
match List.nth env i with
| D.TopLevel t -> t
| D.Tm t -> t
| D.Dim _-> raise (Eval_failed "Not a term variable")
end
| Syn.Let (def, body) -> eval body (D.Tm (eval def env size) :: env) size
| Syn.Check (term, _) -> eval term env size
| Syn.Unit -> D.Unit
| Syn.Triv -> D.Triv
| Syn.Nat -> D.Nat
| Syn.List t -> D.List (eval t env size)
| Syn.Zero -> D.Zero
| Syn.Suc t -> D.Suc (eval t env size)
| Syn.NRec (tp, zero, suc, n) ->
do_rec size
(Clos {term = tp; env})
(eval zero env size)
(Clos2 {term = suc; env})
(eval n env size)
| Syn.Nil -> D.Nil
| Syn.Cons (a, t) -> D.Cons (eval a env size, eval t env size)
| Syn.ListRec (mot, nil, cons, l) ->
do_list_rec size
(Clos {term = mot; env})
(eval nil env size)
(Clos3 {term = cons; env})
(eval l env size)
| Syn.Bool -> D.Bool
| Syn.True -> D.True
| Syn.False -> D.False
| Syn.If (mot, tt, ff, b) ->
do_if size
(Clos {term = mot; env})
(eval tt env size)
(eval ff env size)
(eval b env size)
| Syn.Coprod (t1, t2) -> D.Coprod (eval t1 env size, eval t2 env size)
| Syn.Inl t -> D.Inl (eval t env size)
| Syn.Inr t -> D.Inr (eval t env size)
| Syn.Case (mot, inl, inr, co) ->
do_case size
(Clos {term = mot; env})
(Clos {term = inl; env})
(Clos {term = inr; env})
(eval co env size)
| Syn.Void -> D.Void
| Syn.Abort (mot, vd) ->
do_abort size (Clos {term = mot; env}) (eval vd env size)
| Syn.Pi (m, src, dest) ->
D.Pi (m, eval src env size, (Clos {term = dest; env}))
| Syn.Lam t -> D.Lam (Clos {term = t; env})
| Syn.Ap (t1, t2) -> do_ap size (eval t1 env size) (eval t2 env size)
| Syn.Uni i -> D.Uni i
| Syn.Sg (t1, t2) -> D.Sg (eval t1 env size, (Clos {term = t2; env}))
| Syn.Pair (t1, t2) -> D.Pair (eval t1 env size, eval t2 env size)
| Syn.Fst t -> do_fst (eval t env size)
| Syn.Snd t -> do_snd size (eval t env size)
| Syn.Bridge (dest, ts) ->
D.Bridge (Clos {term = dest; env}, List.map (Option.map (fun t -> eval t env size)) ts)
| Syn.BApp (t,r) ->
let r' = eval_dim r env in
do_bapp size (eval t env size) r'
| Syn.BLam t -> D.BLam (Clos {term = t; env})
| Syn.Refl t -> D.Refl (eval t env size)
| Syn.Id (tp, left, right) -> D.Id (eval tp env size, eval left env size, eval right env size)
| Syn.J (mot, refl, eq) ->
do_j size (D.Clos3 {term = mot; env}) (D.Clos {term = refl; env}) (eval eq env size)
| Syn.Extent (r, dom, mot, ctx, endcase, varcase) ->
let r' = eval_dim r env in
let ctx' = eval ctx env size in
begin
match r' with
| D.DVar i ->
let final_tp = eval mot (D.Tm ctx' :: D.Dim r' :: env) size in
let ext =
D.Ext
{var = i;
dom = D.Clos {term = dom; env};
mot = D.Clos2 {term = mot; env};
ctx = ctx';
endcase = List.map (fun t -> D.Clos {term = t; env}) endcase;
varcase = D.ClosN {term = varcase; env}}
in
D.Neutral {tp = final_tp; term = D.root ext}
| D.Const o ->
eval (List.nth endcase o) (D.Tm ctx' :: env) size
end
| Syn.Gel (r, endtps, rel) ->
begin
let r' = eval_dim r env in
match r' with
| D.DVar i -> D.Gel (i, List.map (fun t -> eval t env size) endtps, D.ClosN {term = rel; env})
| D.Const o -> eval (List.nth endtps o) env size
end
| Syn.Engel (i, ts, t) ->
begin
let r' = eval_dim (Syn.DVar i) env in
match r' with
| D.DVar i' -> D.Engel (i', List.map (fun t -> eval t env size) ts, eval t env size)
| Const o -> eval (List.nth ts o) env size
end
| Syn.Ungel (width, mot, gel, case) ->
do_ungel
size
(do_consts size (D.Clos {term = gel; env}) width)
(D.Clos {term = mot; env})
(eval gel (D.Dim (D.DVar size) :: env) (size + 1))
(D.Clos {term = case; env})
| Syn.Codisc t -> D.Codisc (eval t env size)
| Syn.Encodisc t -> D.Encodisc (eval t env size)
| Syn.Uncodisc t -> do_uncodisc (eval t env size)
| Syn.Global t -> D.Global (eval t env size)
| Syn.Englobe t -> D.Englobe (eval t env size)
| Syn.Unglobe t -> do_unglobe (eval t env size)
| Syn.Disc t -> D.Disc (eval t env size)
| Syn.Endisc t -> D.Endisc (eval t env size)
| Syn.Letdisc (m, mot, case, d) ->
do_letdisc
size
m
(D.Clos {term = mot; env})
(D.Clos {term = case; env})
(eval d env size)
| Syn.Letdiscbridge (m, width, mot, case, d) ->
do_letdiscbridge
size
m
(do_consts size (D.Clos {term = d; env}) width)
(D.Clos {term = mot; env})
(D.Clos {term = case; env})
(eval d (D.Dim (D.DVar size) :: env) (size + 1))
| |
612c3917a9458af479e7f21e0c51853bede3797dbf20912a2b123a5db421a75a | cardmagic/lucash | libscsh.scm | ;;; This file is part of scsh.
(define (return-from-vm n)
(with-continuation (if #t #f) (lambda () n)))
(define (startup user-context)
(lambda (args)
(start-new-session user-context
(current-input-port)
(current-output-port)
(current-error-port)
args
#t) ;batch?
(with-interaction-environment
(user-environment)
(lambda ()
(return-from-vm 0)))))
(define (s48-command command-string)
(let* ((in (make-string-input-port command-string))
(s-exp (read in)))
(if (and (not (eof-object? s-exp))
(eof-object? (read in)))
(call-with-values
(lambda ()
(call-with-current-continuation
(lambda (k)
(with-handler
(lambda (cond more)
; (display "error is "(current-error-port))
; (display cond (current-error-port))
; (newline (current-error-port))
(k cond))
(lambda ()
(eval s-exp (user-command-environment)))))))
(lambda args
(cond ((null? args)
; (display "null as result"
; (current-error-port)))
((null? (cdr args))
; (display "evaluated to:" (current-error-port))
; (display (car args)(current-error-port))
; (newline (current-error-port))
(car args))
(else
(display "multiple return values in s48-command"
(current-error-port))
))))
(display "s48-command got not exactly one s-exp"
(current-error-port)))))
TODO write a procedure to be called time by time to let the
;; administrative threads run
;; must be called from a running command processor
(define (dump-libscsh-image filename)
(dump-scsh-program (startup (user-context)) filename))
(define-exported-binding "s48-command" s48-command)
| null | https://raw.githubusercontent.com/cardmagic/lucash/0452d410430d12140c14948f7f583624f819cdad/reference/scsh-0.6.6/scsh/libscsh.scm | scheme | This file is part of scsh.
batch?
(display "error is "(current-error-port))
(display cond (current-error-port))
(newline (current-error-port))
(display "null as result"
(current-error-port)))
(display "evaluated to:" (current-error-port))
(display (car args)(current-error-port))
(newline (current-error-port))
administrative threads run
must be called from a running command processor |
(define (return-from-vm n)
(with-continuation (if #t #f) (lambda () n)))
(define (startup user-context)
(lambda (args)
(start-new-session user-context
(current-input-port)
(current-output-port)
(current-error-port)
args
(with-interaction-environment
(user-environment)
(lambda ()
(return-from-vm 0)))))
(define (s48-command command-string)
(let* ((in (make-string-input-port command-string))
(s-exp (read in)))
(if (and (not (eof-object? s-exp))
(eof-object? (read in)))
(call-with-values
(lambda ()
(call-with-current-continuation
(lambda (k)
(with-handler
(lambda (cond more)
(k cond))
(lambda ()
(eval s-exp (user-command-environment)))))))
(lambda args
(cond ((null? args)
((null? (cdr args))
(car args))
(else
(display "multiple return values in s48-command"
(current-error-port))
))))
(display "s48-command got not exactly one s-exp"
(current-error-port)))))
TODO write a procedure to be called time by time to let the
(define (dump-libscsh-image filename)
(dump-scsh-program (startup (user-context)) filename))
(define-exported-binding "s48-command" s48-command)
|
4a2989b94a6419ddd69591c2aefa3a278f35d13d6b94e5f638effc1aa07d74ed | sarabander/p2pu-sicp | 3.51.scm |
(define (show x)
(display-line x)
x)
(define x
(stream-map
show
(stream-enumerate-interval 0 10)))
0
(stream-ref x 5)
1
2
3
4
5
(stream-ref x 7)
6
7
| null | https://raw.githubusercontent.com/sarabander/p2pu-sicp/fbc49b67dac717da1487629fb2d7a7d86dfdbe32/3.5/3.51.scm | scheme |
(define (show x)
(display-line x)
x)
(define x
(stream-map
show
(stream-enumerate-interval 0 10)))
0
(stream-ref x 5)
1
2
3
4
5
(stream-ref x 7)
6
7
| |
c8386b1f9f70ff2ff0bc54ab77a2a1c14b9f224c88755f3d036cea389fc62550 | charlescearl/DeepRacket | test-cudann.rkt | #lang racket/base
(require
rackunit
rackunit/text-ui
ffi/unsafe
"lib-cudann.rkt")
;; define a test case
(define handle-tests
(test-suite
"Tests for cudann"
(test-case
"Check handle creation"
(let* ([block (malloc 'atomic-interior 8)]
[hndlptr (cast block _pointer _cudnnHandle_t-pointer)]
[res (cudnnCreate hndlptr)])
(check-equal? res 'success "Handle Creation")
(let ([hndl (ptr-ref hndlptr _cudnnHandle_t)])
(check-equal? (cudnnDestroy hndl) 'success "Handle Release")
)))
(test-case
"Check creation of a float array"
(let* ([array-ptr (malloc 'atomic-interior 8)]
[res (cudaMalloc array-ptr 4096)])
(check-equal? res 'success "Array Creation")
(check-equal? (cudaFree (ptr-ref array-ptr _pointer)) 'success "Array Release")
))
(test-case
"Check creation of tensor descriptor"
(let* ([desc-ptr (malloc 'atomic-interior (ctype-sizeof _cudnnTensorDescriptor_t))]
[res (cudnnCreateTensorDescriptor (cast desc-ptr _pointer _cudnnTensorDescriptor_t-ptr))]
)
(print res)
(check-equal? res 'success "Tensor Descriptor Creation")
))
))
(define initialize-from-array-tests
(test-suite
"Test initialization of float array"
(test-case
"Check the initialization of the float array"
(check-equal? "a" "a"))))
| null | https://raw.githubusercontent.com/charlescearl/DeepRacket/767560aab5c56c03e951e005b5b983b435afe7eb/test-cudann.rkt | racket | define a test case | #lang racket/base
(require
rackunit
rackunit/text-ui
ffi/unsafe
"lib-cudann.rkt")
(define handle-tests
(test-suite
"Tests for cudann"
(test-case
"Check handle creation"
(let* ([block (malloc 'atomic-interior 8)]
[hndlptr (cast block _pointer _cudnnHandle_t-pointer)]
[res (cudnnCreate hndlptr)])
(check-equal? res 'success "Handle Creation")
(let ([hndl (ptr-ref hndlptr _cudnnHandle_t)])
(check-equal? (cudnnDestroy hndl) 'success "Handle Release")
)))
(test-case
"Check creation of a float array"
(let* ([array-ptr (malloc 'atomic-interior 8)]
[res (cudaMalloc array-ptr 4096)])
(check-equal? res 'success "Array Creation")
(check-equal? (cudaFree (ptr-ref array-ptr _pointer)) 'success "Array Release")
))
(test-case
"Check creation of tensor descriptor"
(let* ([desc-ptr (malloc 'atomic-interior (ctype-sizeof _cudnnTensorDescriptor_t))]
[res (cudnnCreateTensorDescriptor (cast desc-ptr _pointer _cudnnTensorDescriptor_t-ptr))]
)
(print res)
(check-equal? res 'success "Tensor Descriptor Creation")
))
))
(define initialize-from-array-tests
(test-suite
"Test initialization of float array"
(test-case
"Check the initialization of the float array"
(check-equal? "a" "a"))))
|
1c4d5640c47365ea13e5df9c434c7106a8f9d45fe9e2944c30e99577a37e4a1b | dongcarl/guix | mpi.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2014 , 2015 , 2018 , 2019 < >
Copyright © 2014 , 2015 , 2016 , 2017 , 2018 , 2019 , 2020 , 2021 < >
Copyright © 2014 < >
Copyright © 2016 < >
Copyright © 2017 < >
Copyright © 2017 < >
Copyright © 2018–2021 < >
Copyright © 2018 < >
Copyright © 2019 < >
;;;
;;; 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 mpi)
#:use-module (guix packages)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix download)
#:use-module (guix utils)
#:use-module (guix deprecation)
#:use-module (guix build-system gnu)
#:use-module (guix build-system python)
#:use-module (gnu packages)
#:use-module (gnu packages base)
#:use-module (gnu packages compression)
#:use-module (gnu packages fabric-management)
#:use-module (gnu packages gcc)
#:use-module (gnu packages java)
#:use-module (gnu packages libevent)
#:use-module (gnu packages linux)
#:use-module (gnu packages pciutils)
#:use-module (gnu packages xorg)
#:use-module (gnu packages gtk)
#:use-module (gnu packages xml)
#:use-module (gnu packages perl)
#:use-module (gnu packages ncurses)
#:use-module (gnu packages parallel)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages valgrind)
#:use-module (srfi srfi-1)
#:use-module (ice-9 match))
(define-public hwloc-1
;; Note: For now we keep 1.x as the default because many packages have yet
;; to migrate to 2.0.
(package
(name "hwloc")
(version "1.11.12")
(source (origin
(method url-fetch)
(uri (string-append "-mpi.org/software/hwloc/v"
(version-major+minor version)
"/downloads/hwloc-" version ".tar.bz2"))
(sha256
(base32
"0za1b9lvrm3rhn0lrxja5f64r0aq1qs4m0pxn1ji2mbi8ndppyyx"))))
(properties
;; Tell the 'generic-html' updater to monitor this URL for updates.
`((release-monitoring-url
. "-lb.open-mpi.org/software/hwloc/current")))
(build-system gnu-build-system)
' lstopo ' & co. , depends on Cairo , libx11 , etc .
"lib" ;small closure
400 + section 3 man pages
"debug"))
(inputs
`(("libx11" ,libx11)
("cairo" ,cairo)
("ncurses" ,ncurses)
("expat" ,expat)
,@(if (not (string-prefix? "armhf"
(or (%current-target-system)
(%current-system))))
`(("numactl" ,numactl))
'())))
(propagated-inputs
hwloc.pc lists it in ' Requires.private ' .
`(("libpciaccess" ,libpciaccess)))
(native-inputs
`(("pkg-config" ,pkg-config)))
(arguments
`(#:configure-flags '("--localstatedir=/var")
#:phases
(modify-phases %standard-phases
(add-before 'check 'skip-linux-libnuma-test
(lambda _
;; Arrange to skip 'tests/linux-libnuma', which fails on some
;; machines: <-mpi/hwloc/issues/213>.
(substitute* "tests/linux-libnuma.c"
(("numa_available\\(\\)")
"-1"))
#t))
(add-after 'install 'refine-libnuma
;; Give -L arguments for libraries to avoid propagation
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "lib"))
(numa (assoc-ref inputs "numactl")))
(substitute* (map (lambda (f) (string-append out "/" f))
'("lib/pkgconfig/hwloc.pc" "lib/libhwloc.la"))
(("-lnuma" lib)
(string-append "-L" numa "/lib " lib))))))
(add-after 'install 'avoid-circular-references
(lambda* (#:key outputs #:allow-other-keys)
(let ((lib (assoc-ref outputs "lib")))
;; Suppress the 'prefix=' and 'exec_prefix=' lines so that the
;; "lib" output doesn't refer to "out".
(substitute* (string-append lib "/lib/pkgconfig/hwloc.pc")
(("^.*prefix=.*$")
""))
#t)))
(add-after 'install 'move-man3-pages
(lambda* (#:key outputs #:allow-other-keys)
Move section 3 man pages to the " doc " output .
(let ((out (assoc-ref outputs "out"))
(doc (assoc-ref outputs "doc")))
(copy-recursively (string-append out "/share/man/man3")
(string-append doc "/share/man/man3"))
(delete-file-recursively (string-append out "/share/man/man3"))
#t))))))
(home-page "-mpi.org/projects/hwloc/")
(synopsis "Abstraction of hardware architectures")
(description
"hwloc provides a portable abstraction (across OS,
versions, architectures, ...) of the hierarchical topology of modern
architectures, including NUMA memory nodes, sockets, shared caches, cores and
simultaneous multithreading. It also gathers various attributes such as cache
and memory information. It primarily aims at helping high-performance
computing applications with gathering information about the hardware so as to
exploit it accordingly and efficiently.
hwloc may display the topology in multiple convenient formats. It also offers
a powerful programming interface to gather information about the hardware,
bind processes, and much more.")
(license license:bsd-3)))
(define-public hwloc-2
Note : 2.x is n't the default yet , see above .
(package
(inherit hwloc-1)
(version "2.5.0")
(source (origin
(method url-fetch)
(uri (string-append "-mpi.org/release/hwloc/v"
(version-major+minor version)
"/hwloc-" version ".tar.bz2"))
(sha256
(base32
"1j2j9wn39a8v91r23xncm1rzls6rjkgkvdvqghbdsnq8ps491kx9"))))
;; libnuma is no longer needed.
(inputs (alist-delete "numactl" (package-inputs hwloc-1)))
(arguments
(substitute-keyword-arguments (package-arguments hwloc-1)
((#:phases phases)
`(modify-phases ,phases
(replace 'skip-linux-libnuma-test
(lambda _
;; Arrange to skip 'tests/hwloc/linux-libnuma', which fails on
;; some machines: <-mpi/hwloc/issues/213>.
(substitute* "tests/hwloc/linux-libnuma.c"
(("numa_available\\(\\)")
"-1"))
#t))
(add-before 'check 'skip-test-that-fails-on-qemu
(lambda _
Skip test that fails on emulated hardware due to QEMU bug :
;; <>.
(substitute* "tests/hwloc/hwloc_get_last_cpu_location.c"
(("hwloc_topology_init" all)
(string-append "exit (77);\n" all)))
#t))))))))
(define-deprecated hwloc-2.0 hwloc-2)
(define-public hwloc
;; The latest stable series of hwloc.
hwloc-2)
(define-public openmpi
(package
(name "openmpi")
(version "4.1.1")
(source
(origin
(method url-fetch)
(uri (string-append "-mpi.org/software/ompi/v"
(version-major+minor version)
"/downloads/openmpi-" version ".tar.bz2"))
(sha256
(base32 "1nkwq123vvmggcay48snm9qqmrh0bdzpln0l1jnp26niidvplkz2"))
(patches (search-patches "openmpi-mtl-priorities.patch"))))
(properties
;; Tell the 'generic-html' updater to monitor this URL for updates.
`((release-monitoring-url
. "-mpi.org/software/ompi/current")))
(build-system gnu-build-system)
(inputs
`(("hwloc" ,hwloc-2 "lib")
("gfortran" ,gfortran)
("libfabric" ,libfabric)
("libevent" ,libevent)
("opensm" ,opensm)
,@(if (and (not (%current-target-system))
(member (%current-system) (package-supported-systems psm)))
`(("psm" ,psm))
'())
,@(if (and (not (%current-target-system))
(member (%current-system) (package-supported-systems psm2)))
`(("psm2" ,psm2))
'())
,@(if (and (not (%current-target-system))
(member (%current-system) (package-supported-systems ucx)))
`(("ucx" ,ucx))
'())
("rdma-core" ,rdma-core)
("valgrind" ,valgrind)
("slurm" ,slurm))) ;for PMI support (launching via "srun")
(native-inputs
`(("pkg-config" ,pkg-config)
("perl" ,perl)))
(outputs '("out" "debug"))
(arguments
`(#:configure-flags `("--enable-mpi-ext=affinity" ;cr doesn't work
"--enable-memchecker"
"--with-sge"
"--with-valgrind"
"--with-hwloc=external"
"--with-libevent"
;; Help 'orterun' and 'mpirun' find their tools
;; under $prefix by default.
"--enable-mpirun-prefix-by-default"
;; InfiniBand support
"--enable-openib-control-hdr-padding"
"--enable-openib-dynamic-sl"
"--enable-openib-udcm"
"--enable-openib-rdmacm"
"--enable-openib-rdmacm-ibaddr"
Enable support for SLURM 's Process Manager
Interface ( PMI ) .
,(string-append "--with-pmi="
(assoc-ref %build-inputs "slurm")))
#:phases (modify-phases %standard-phases
;; opensm is needed for InfiniBand support.
(add-after 'unpack 'find-opensm-headers
(lambda* (#:key inputs #:allow-other-keys)
(setenv "C_INCLUDE_PATH"
(string-append (assoc-ref inputs "opensm")
"/include/infiniband"))
(setenv "CPLUS_INCLUDE_PATH"
(string-append (assoc-ref inputs "opensm")
"/include/infiniband"))
#t))
(add-before 'build 'remove-absolute
(lambda _
Remove compiler absolute file names ( OPAL_FC_ABSOLUTE
;; etc.) to reduce the closure size. See
;; <-devel/2017-07/msg00388.html>
;; and
;; <-archive.com///msg31397.html>.
(substitute* '("orte/tools/orte-info/param.c"
"oshmem/tools/oshmem_info/param.c"
"ompi/tools/ompi_info/param.c")
(("_ABSOLUTE") ""))
;; Avoid valgrind (which pulls in gdb etc.).
(substitute*
'("./ompi/mca/io/romio321/src/io_romio321_component.c")
(("MCA_io_romio321_COMPLETE_CONFIGURE_FLAGS")
"\"[elided to reduce closure]\""))
#t))
(add-before 'build 'scrub-timestamps ;reproducibility
(lambda _
(substitute* '("ompi/tools/ompi_info/param.c"
"orte/tools/orte-info/param.c"
"oshmem/tools/oshmem_info/param.c")
((".*(Built|Configured) on.*") ""))
#t))
(add-after 'install 'remove-logs ;reproducibility
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(for-each delete-file (find-files out "config.log"))
#t))))))
(home-page "-mpi.org")
(synopsis "MPI-3 implementation")
(description
"The Open MPI Project is an MPI-3 implementation that is developed and
maintained by a consortium of academic, research, and industry partners. Open
MPI is therefore able to combine the expertise, technologies, and resources
from all across the High Performance Computing community in order to build the
best MPI library available. Open MPI offers advantages for system and
software vendors, application developers and computer science researchers.")
;; See file
(license license:bsd-2)))
;; TODO: javadoc files contain timestamps.
(define-public java-openmpi
(package/inherit openmpi
(name "java-openmpi")
(inputs
`(("openmpi" ,openmpi)
,@(package-inputs openmpi)))
(native-inputs
`(("jdk" ,openjdk11 "jdk")
("zip" ,(@ (gnu packages compression) zip))
,@(package-native-inputs openmpi)))
(outputs '("out"))
(arguments
`(#:modules ((guix build gnu-build-system)
((guix build ant-build-system) #:prefix ant:)
(guix build utils))
#:imported-modules ((guix build ant-build-system)
(guix build syscalls)
,@%gnu-build-system-modules)
,@(substitute-keyword-arguments (package-arguments openmpi)
((#:configure-flags flags)
`(cons "--enable-mpi-java" ,flags))
((#:make-flags flags ''())
`(append '("-C" "ompi/mpi/java")
,flags))
((#:phases phases)
`(modify-phases ,phases
We could provide the location of the in the configure
;; flags, but since the configure flags are embedded in the
;; info binaries that would leave a reference to the JDK in
;; the "out" output. To avoid this we set JAVA_HOME.
(add-after 'unpack 'set-JAVA_HOME
(lambda* (#:key inputs #:allow-other-keys)
(setenv "JAVA_HOME" (assoc-ref inputs "jdk"))
#t))
(add-after 'unpack 'link-with-existing-mpi-libraries
(lambda* (#:key inputs #:allow-other-keys)
(substitute* "ompi/mpi/java/c/Makefile.in"
(("\\$\\(top_builddir\\)/ompi/lib@OMPI_LIBMPI_NAME@.la")
(string-append (assoc-ref inputs "openmpi") "/lib/libmpi.la")))
#t))
(add-after 'install 'strip-jar-timestamps
(assoc-ref ant:%standard-phases 'strip-jar-timestamps)))))))
(synopsis "Java bindings for MPI")))
(define-public openmpi-thread-multiple
(package/inherit openmpi
(name "openmpi-thread-multiple")
(arguments
(substitute-keyword-arguments (package-arguments openmpi)
((#:configure-flags flags)
`(cons "--enable-mpi-thread-multiple" ,flags))))
(description " This version of Open@tie{}MPI has an implementation of
@code{MPI_Init_thread} that provides @code{MPI_THREAD_MULTIPLE}. This won't
work correctly with all transports (such as @code{openib}), and the
performance is generally worse than the vanilla @code{openmpi} package, which
only provides @code{MPI_THREAD_FUNNELED}.")))
Build phase to be used for packages that execute MPI code .
(define-public %openmpi-setup
'(lambda _
;; By default, running the test suite would fail because 'ssh' could not
be found in $ PATH . Define this variable to placate Open MPI without
;; adding a dependency on OpenSSH (the agent isn't used anyway.)
(setenv "OMPI_MCA_plm_rsh_agent" (which "false"))
;; Allow oversubscription in case there are less physical cores available
;; in the build environment than the package wants while testing.
(setenv "OMPI_MCA_rmaps_base_mapping_policy" "core:OVERSUBSCRIBE")
UCX sometimes outputs uninteresting warnings such as :
;;
mpool.c:38 UCX WARN object 0x7ffff44fffc0 was not returned to mpool ucp_am_bufs
;;
;; These in turn leads to failures of test suites that capture and
compare stdout , such as that of ' hdf5 - parallel - openmpi ' . Thus , tell
UCX to not emit those warnings .
(setenv "UCX_LOG_LEVEL" "error")
#t))
(define-public python-mpi4py
(package
(name "python-mpi4py")
(version "3.0.3")
(source
(origin
(method url-fetch)
(uri (pypi-uri "mpi4py" version))
(sha256
(base32 "07ssbhssv27rrjx1c5vd3vsr31vay5d8xcf4zh9yblcyidn72b81"))))
(build-system python-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'build 'mpi-setup
,%openmpi-setup)
(add-before 'check 'pre-check
(lambda _
;; Skip BaseTestSpawn class (causes error 'ompi_dpm_dyn_init()
failed -- > Returned " Unreachable " ' in chroot environment ) .
(substitute* "test/test_spawn.py"
(("unittest.skipMPI\\('openmpi\\(<3.0.0\\)'\\)")
"unittest.skipMPI('openmpi')"))
#t)))))
(inputs
`(("openmpi" ,openmpi)))
(home-page "/")
(synopsis "Python bindings for the Message Passing Interface standard")
(description "MPI for Python (mpi4py) provides bindings of the Message
Passing Interface (MPI) standard for the Python programming language, allowing
any Python program to exploit multiple processors.
mpi4py is constructed on top of the MPI-1/MPI-2 specification and provides an
object oriented interface which closely follows MPI-2 C++ bindings. It
supports point-to-point and collective communications of any picklable Python
object as well as optimized communications of Python objects (such as NumPy
arrays) that expose a buffer interface.")
(license license:bsd-3)))
(define-public mpich
(package
(name "mpich")
(version "3.3.2")
(source (origin
(method url-fetch)
(uri (string-append "/"
version "/mpich-" version ".tar.gz"))
(sha256
(base32
"1farz5zfx4cd0c3a0wb9pgfypzw0xxql1j1294z1sxslga1ziyjb"))))
(build-system gnu-build-system)
(inputs
`(("zlib" ,zlib)
("hwloc" ,hwloc-2 "lib")
("slurm" ,slurm)
,@(if (and (not (%current-target-system))
(member (%current-system) (package-supported-systems ucx)))
`(("ucx" ,ucx))
'())))
(native-inputs
`(("perl" ,perl)
("which" ,which)
("gfortran" ,gfortran)))
(outputs '("out" "debug"))
(arguments
`(#:configure-flags
(list "--disable-silent-rules" ;let's see what's happening
"--enable-debuginfo"
Default to " ch4 " , as will be the case in 3.4 . It also works
;; around issues when running test suites of packages that use
MPICH : < #15 > .
"--with-device=ch4:ucx" ; --with-device=ch4:ofi segfaults in tests
(string-append "--with-hwloc-prefix="
(assoc-ref %build-inputs "hwloc"))
,@(if (assoc "ucx" (package-inputs this-package))
`((string-append "--with-ucx="
(assoc-ref %build-inputs "ucx")))
'()))
#:phases (modify-phases %standard-phases
(add-after 'unpack 'patch-sources
(lambda _
(substitute* "./maint/gen_subcfg_m4"
(("/usr/bin/env") (which "env")))
(substitute* "src/glue/romio/all_romio_symbols"
(("/usr/bin/env") (which "env")))
(substitute* (find-files "." "buildiface")
(("/usr/bin/env") (which "env")))
(substitute* "maint/extracterrmsgs"
(("/usr/bin/env") (which "env")))
(substitute* (find-files "." "f77tof90")
(("/usr/bin/env") (which "env")))
(substitute* (find-files "." "\\.sh$")
(("/bin/sh") (which "sh")))
#t))
(add-before 'configure 'fix-makefile
(lambda _
;; Remove "@hwloclib@" from 'pmpi_convenience_libs'.
;; This fixes "No rule to make target '-lhwloc', needed
;; by 'lib/libmpi.la'".
(substitute* "Makefile.in"
(("^pmpi_convenience_libs = (.*) @hwloclib@ (.*)$" _
before after)
(string-append "pmpi_convenience_libs = "
before " " after)))
#t)))))
(home-page "/")
(synopsis "Implementation of the Message Passing Interface (MPI)")
(description
"MPICH is a high-performance and portable implementation of the Message
Passing Interface (MPI) standard (MPI-1, MPI-2 and MPI-3). MPICH provides an
MPI implementation that efficiently supports different computation and
communication platforms including commodity clusters, high-speed networks (10
Gigabit Ethernet, InfiniBand, Myrinet, Quadrics), and proprietary high-end
computing systems (Blue Gene, Cray). It enables research in MPI through a
modular framework for other derived implementations.")
(license license:bsd-2)))
| null | https://raw.githubusercontent.com/dongcarl/guix/d2b30db788f1743f9f8738cb1de977b77748567f/gnu/packages/mpi.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.
Note: For now we keep 1.x as the default because many packages have yet
to migrate to 2.0.
Tell the 'generic-html' updater to monitor this URL for updates.
small closure
Arrange to skip 'tests/linux-libnuma', which fails on some
machines: <-mpi/hwloc/issues/213>.
Give -L arguments for libraries to avoid propagation
Suppress the 'prefix=' and 'exec_prefix=' lines so that the
"lib" output doesn't refer to "out".
libnuma is no longer needed.
Arrange to skip 'tests/hwloc/linux-libnuma', which fails on
some machines: <-mpi/hwloc/issues/213>.
<>.
The latest stable series of hwloc.
Tell the 'generic-html' updater to monitor this URL for updates.
for PMI support (launching via "srun")
cr doesn't work
Help 'orterun' and 'mpirun' find their tools
under $prefix by default.
InfiniBand support
opensm is needed for InfiniBand support.
etc.) to reduce the closure size. See
<-devel/2017-07/msg00388.html>
and
<-archive.com///msg31397.html>.
Avoid valgrind (which pulls in gdb etc.).
reproducibility
reproducibility
See file
TODO: javadoc files contain timestamps.
flags, but since the configure flags are embedded in the
info binaries that would leave a reference to the JDK in
the "out" output. To avoid this we set JAVA_HOME.
By default, running the test suite would fail because 'ssh' could not
adding a dependency on OpenSSH (the agent isn't used anyway.)
Allow oversubscription in case there are less physical cores available
in the build environment than the package wants while testing.
These in turn leads to failures of test suites that capture and
Skip BaseTestSpawn class (causes error 'ompi_dpm_dyn_init()
let's see what's happening
around issues when running test suites of packages that use
--with-device=ch4:ofi segfaults in tests
Remove "@hwloclib@" from 'pmpi_convenience_libs'.
This fixes "No rule to make target '-lhwloc', needed
by 'lib/libmpi.la'". | Copyright © 2014 , 2015 , 2018 , 2019 < >
Copyright © 2014 , 2015 , 2016 , 2017 , 2018 , 2019 , 2020 , 2021 < >
Copyright © 2014 < >
Copyright © 2016 < >
Copyright © 2017 < >
Copyright © 2017 < >
Copyright © 2018–2021 < >
Copyright © 2018 < >
Copyright © 2019 < >
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 mpi)
#:use-module (guix packages)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix download)
#:use-module (guix utils)
#:use-module (guix deprecation)
#:use-module (guix build-system gnu)
#:use-module (guix build-system python)
#:use-module (gnu packages)
#:use-module (gnu packages base)
#:use-module (gnu packages compression)
#:use-module (gnu packages fabric-management)
#:use-module (gnu packages gcc)
#:use-module (gnu packages java)
#:use-module (gnu packages libevent)
#:use-module (gnu packages linux)
#:use-module (gnu packages pciutils)
#:use-module (gnu packages xorg)
#:use-module (gnu packages gtk)
#:use-module (gnu packages xml)
#:use-module (gnu packages perl)
#:use-module (gnu packages ncurses)
#:use-module (gnu packages parallel)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages valgrind)
#:use-module (srfi srfi-1)
#:use-module (ice-9 match))
(define-public hwloc-1
(package
(name "hwloc")
(version "1.11.12")
(source (origin
(method url-fetch)
(uri (string-append "-mpi.org/software/hwloc/v"
(version-major+minor version)
"/downloads/hwloc-" version ".tar.bz2"))
(sha256
(base32
"0za1b9lvrm3rhn0lrxja5f64r0aq1qs4m0pxn1ji2mbi8ndppyyx"))))
(properties
`((release-monitoring-url
. "-lb.open-mpi.org/software/hwloc/current")))
(build-system gnu-build-system)
' lstopo ' & co. , depends on Cairo , libx11 , etc .
400 + section 3 man pages
"debug"))
(inputs
`(("libx11" ,libx11)
("cairo" ,cairo)
("ncurses" ,ncurses)
("expat" ,expat)
,@(if (not (string-prefix? "armhf"
(or (%current-target-system)
(%current-system))))
`(("numactl" ,numactl))
'())))
(propagated-inputs
hwloc.pc lists it in ' Requires.private ' .
`(("libpciaccess" ,libpciaccess)))
(native-inputs
`(("pkg-config" ,pkg-config)))
(arguments
`(#:configure-flags '("--localstatedir=/var")
#:phases
(modify-phases %standard-phases
(add-before 'check 'skip-linux-libnuma-test
(lambda _
(substitute* "tests/linux-libnuma.c"
(("numa_available\\(\\)")
"-1"))
#t))
(add-after 'install 'refine-libnuma
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "lib"))
(numa (assoc-ref inputs "numactl")))
(substitute* (map (lambda (f) (string-append out "/" f))
'("lib/pkgconfig/hwloc.pc" "lib/libhwloc.la"))
(("-lnuma" lib)
(string-append "-L" numa "/lib " lib))))))
(add-after 'install 'avoid-circular-references
(lambda* (#:key outputs #:allow-other-keys)
(let ((lib (assoc-ref outputs "lib")))
(substitute* (string-append lib "/lib/pkgconfig/hwloc.pc")
(("^.*prefix=.*$")
""))
#t)))
(add-after 'install 'move-man3-pages
(lambda* (#:key outputs #:allow-other-keys)
Move section 3 man pages to the " doc " output .
(let ((out (assoc-ref outputs "out"))
(doc (assoc-ref outputs "doc")))
(copy-recursively (string-append out "/share/man/man3")
(string-append doc "/share/man/man3"))
(delete-file-recursively (string-append out "/share/man/man3"))
#t))))))
(home-page "-mpi.org/projects/hwloc/")
(synopsis "Abstraction of hardware architectures")
(description
"hwloc provides a portable abstraction (across OS,
versions, architectures, ...) of the hierarchical topology of modern
architectures, including NUMA memory nodes, sockets, shared caches, cores and
simultaneous multithreading. It also gathers various attributes such as cache
and memory information. It primarily aims at helping high-performance
computing applications with gathering information about the hardware so as to
exploit it accordingly and efficiently.
hwloc may display the topology in multiple convenient formats. It also offers
a powerful programming interface to gather information about the hardware,
bind processes, and much more.")
(license license:bsd-3)))
(define-public hwloc-2
Note : 2.x is n't the default yet , see above .
(package
(inherit hwloc-1)
(version "2.5.0")
(source (origin
(method url-fetch)
(uri (string-append "-mpi.org/release/hwloc/v"
(version-major+minor version)
"/hwloc-" version ".tar.bz2"))
(sha256
(base32
"1j2j9wn39a8v91r23xncm1rzls6rjkgkvdvqghbdsnq8ps491kx9"))))
(inputs (alist-delete "numactl" (package-inputs hwloc-1)))
(arguments
(substitute-keyword-arguments (package-arguments hwloc-1)
((#:phases phases)
`(modify-phases ,phases
(replace 'skip-linux-libnuma-test
(lambda _
(substitute* "tests/hwloc/linux-libnuma.c"
(("numa_available\\(\\)")
"-1"))
#t))
(add-before 'check 'skip-test-that-fails-on-qemu
(lambda _
Skip test that fails on emulated hardware due to QEMU bug :
(substitute* "tests/hwloc/hwloc_get_last_cpu_location.c"
(("hwloc_topology_init" all)
(string-append "exit (77);\n" all)))
#t))))))))
(define-deprecated hwloc-2.0 hwloc-2)
(define-public hwloc
hwloc-2)
(define-public openmpi
(package
(name "openmpi")
(version "4.1.1")
(source
(origin
(method url-fetch)
(uri (string-append "-mpi.org/software/ompi/v"
(version-major+minor version)
"/downloads/openmpi-" version ".tar.bz2"))
(sha256
(base32 "1nkwq123vvmggcay48snm9qqmrh0bdzpln0l1jnp26niidvplkz2"))
(patches (search-patches "openmpi-mtl-priorities.patch"))))
(properties
`((release-monitoring-url
. "-mpi.org/software/ompi/current")))
(build-system gnu-build-system)
(inputs
`(("hwloc" ,hwloc-2 "lib")
("gfortran" ,gfortran)
("libfabric" ,libfabric)
("libevent" ,libevent)
("opensm" ,opensm)
,@(if (and (not (%current-target-system))
(member (%current-system) (package-supported-systems psm)))
`(("psm" ,psm))
'())
,@(if (and (not (%current-target-system))
(member (%current-system) (package-supported-systems psm2)))
`(("psm2" ,psm2))
'())
,@(if (and (not (%current-target-system))
(member (%current-system) (package-supported-systems ucx)))
`(("ucx" ,ucx))
'())
("rdma-core" ,rdma-core)
("valgrind" ,valgrind)
(native-inputs
`(("pkg-config" ,pkg-config)
("perl" ,perl)))
(outputs '("out" "debug"))
(arguments
"--enable-memchecker"
"--with-sge"
"--with-valgrind"
"--with-hwloc=external"
"--with-libevent"
"--enable-mpirun-prefix-by-default"
"--enable-openib-control-hdr-padding"
"--enable-openib-dynamic-sl"
"--enable-openib-udcm"
"--enable-openib-rdmacm"
"--enable-openib-rdmacm-ibaddr"
Enable support for SLURM 's Process Manager
Interface ( PMI ) .
,(string-append "--with-pmi="
(assoc-ref %build-inputs "slurm")))
#:phases (modify-phases %standard-phases
(add-after 'unpack 'find-opensm-headers
(lambda* (#:key inputs #:allow-other-keys)
(setenv "C_INCLUDE_PATH"
(string-append (assoc-ref inputs "opensm")
"/include/infiniband"))
(setenv "CPLUS_INCLUDE_PATH"
(string-append (assoc-ref inputs "opensm")
"/include/infiniband"))
#t))
(add-before 'build 'remove-absolute
(lambda _
Remove compiler absolute file names ( OPAL_FC_ABSOLUTE
(substitute* '("orte/tools/orte-info/param.c"
"oshmem/tools/oshmem_info/param.c"
"ompi/tools/ompi_info/param.c")
(("_ABSOLUTE") ""))
(substitute*
'("./ompi/mca/io/romio321/src/io_romio321_component.c")
(("MCA_io_romio321_COMPLETE_CONFIGURE_FLAGS")
"\"[elided to reduce closure]\""))
#t))
(lambda _
(substitute* '("ompi/tools/ompi_info/param.c"
"orte/tools/orte-info/param.c"
"oshmem/tools/oshmem_info/param.c")
((".*(Built|Configured) on.*") ""))
#t))
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(for-each delete-file (find-files out "config.log"))
#t))))))
(home-page "-mpi.org")
(synopsis "MPI-3 implementation")
(description
"The Open MPI Project is an MPI-3 implementation that is developed and
maintained by a consortium of academic, research, and industry partners. Open
MPI is therefore able to combine the expertise, technologies, and resources
from all across the High Performance Computing community in order to build the
best MPI library available. Open MPI offers advantages for system and
software vendors, application developers and computer science researchers.")
(license license:bsd-2)))
(define-public java-openmpi
(package/inherit openmpi
(name "java-openmpi")
(inputs
`(("openmpi" ,openmpi)
,@(package-inputs openmpi)))
(native-inputs
`(("jdk" ,openjdk11 "jdk")
("zip" ,(@ (gnu packages compression) zip))
,@(package-native-inputs openmpi)))
(outputs '("out"))
(arguments
`(#:modules ((guix build gnu-build-system)
((guix build ant-build-system) #:prefix ant:)
(guix build utils))
#:imported-modules ((guix build ant-build-system)
(guix build syscalls)
,@%gnu-build-system-modules)
,@(substitute-keyword-arguments (package-arguments openmpi)
((#:configure-flags flags)
`(cons "--enable-mpi-java" ,flags))
((#:make-flags flags ''())
`(append '("-C" "ompi/mpi/java")
,flags))
((#:phases phases)
`(modify-phases ,phases
We could provide the location of the in the configure
(add-after 'unpack 'set-JAVA_HOME
(lambda* (#:key inputs #:allow-other-keys)
(setenv "JAVA_HOME" (assoc-ref inputs "jdk"))
#t))
(add-after 'unpack 'link-with-existing-mpi-libraries
(lambda* (#:key inputs #:allow-other-keys)
(substitute* "ompi/mpi/java/c/Makefile.in"
(("\\$\\(top_builddir\\)/ompi/lib@OMPI_LIBMPI_NAME@.la")
(string-append (assoc-ref inputs "openmpi") "/lib/libmpi.la")))
#t))
(add-after 'install 'strip-jar-timestamps
(assoc-ref ant:%standard-phases 'strip-jar-timestamps)))))))
(synopsis "Java bindings for MPI")))
(define-public openmpi-thread-multiple
(package/inherit openmpi
(name "openmpi-thread-multiple")
(arguments
(substitute-keyword-arguments (package-arguments openmpi)
((#:configure-flags flags)
`(cons "--enable-mpi-thread-multiple" ,flags))))
(description " This version of Open@tie{}MPI has an implementation of
@code{MPI_Init_thread} that provides @code{MPI_THREAD_MULTIPLE}. This won't
work correctly with all transports (such as @code{openib}), and the
performance is generally worse than the vanilla @code{openmpi} package, which
only provides @code{MPI_THREAD_FUNNELED}.")))
Build phase to be used for packages that execute MPI code .
(define-public %openmpi-setup
'(lambda _
be found in $ PATH . Define this variable to placate Open MPI without
(setenv "OMPI_MCA_plm_rsh_agent" (which "false"))
(setenv "OMPI_MCA_rmaps_base_mapping_policy" "core:OVERSUBSCRIBE")
UCX sometimes outputs uninteresting warnings such as :
mpool.c:38 UCX WARN object 0x7ffff44fffc0 was not returned to mpool ucp_am_bufs
compare stdout , such as that of ' hdf5 - parallel - openmpi ' . Thus , tell
UCX to not emit those warnings .
(setenv "UCX_LOG_LEVEL" "error")
#t))
(define-public python-mpi4py
(package
(name "python-mpi4py")
(version "3.0.3")
(source
(origin
(method url-fetch)
(uri (pypi-uri "mpi4py" version))
(sha256
(base32 "07ssbhssv27rrjx1c5vd3vsr31vay5d8xcf4zh9yblcyidn72b81"))))
(build-system python-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'build 'mpi-setup
,%openmpi-setup)
(add-before 'check 'pre-check
(lambda _
failed -- > Returned " Unreachable " ' in chroot environment ) .
(substitute* "test/test_spawn.py"
(("unittest.skipMPI\\('openmpi\\(<3.0.0\\)'\\)")
"unittest.skipMPI('openmpi')"))
#t)))))
(inputs
`(("openmpi" ,openmpi)))
(home-page "/")
(synopsis "Python bindings for the Message Passing Interface standard")
(description "MPI for Python (mpi4py) provides bindings of the Message
Passing Interface (MPI) standard for the Python programming language, allowing
any Python program to exploit multiple processors.
mpi4py is constructed on top of the MPI-1/MPI-2 specification and provides an
object oriented interface which closely follows MPI-2 C++ bindings. It
supports point-to-point and collective communications of any picklable Python
object as well as optimized communications of Python objects (such as NumPy
arrays) that expose a buffer interface.")
(license license:bsd-3)))
(define-public mpich
(package
(name "mpich")
(version "3.3.2")
(source (origin
(method url-fetch)
(uri (string-append "/"
version "/mpich-" version ".tar.gz"))
(sha256
(base32
"1farz5zfx4cd0c3a0wb9pgfypzw0xxql1j1294z1sxslga1ziyjb"))))
(build-system gnu-build-system)
(inputs
`(("zlib" ,zlib)
("hwloc" ,hwloc-2 "lib")
("slurm" ,slurm)
,@(if (and (not (%current-target-system))
(member (%current-system) (package-supported-systems ucx)))
`(("ucx" ,ucx))
'())))
(native-inputs
`(("perl" ,perl)
("which" ,which)
("gfortran" ,gfortran)))
(outputs '("out" "debug"))
(arguments
`(#:configure-flags
"--enable-debuginfo"
Default to " ch4 " , as will be the case in 3.4 . It also works
MPICH : < #15 > .
(string-append "--with-hwloc-prefix="
(assoc-ref %build-inputs "hwloc"))
,@(if (assoc "ucx" (package-inputs this-package))
`((string-append "--with-ucx="
(assoc-ref %build-inputs "ucx")))
'()))
#:phases (modify-phases %standard-phases
(add-after 'unpack 'patch-sources
(lambda _
(substitute* "./maint/gen_subcfg_m4"
(("/usr/bin/env") (which "env")))
(substitute* "src/glue/romio/all_romio_symbols"
(("/usr/bin/env") (which "env")))
(substitute* (find-files "." "buildiface")
(("/usr/bin/env") (which "env")))
(substitute* "maint/extracterrmsgs"
(("/usr/bin/env") (which "env")))
(substitute* (find-files "." "f77tof90")
(("/usr/bin/env") (which "env")))
(substitute* (find-files "." "\\.sh$")
(("/bin/sh") (which "sh")))
#t))
(add-before 'configure 'fix-makefile
(lambda _
(substitute* "Makefile.in"
(("^pmpi_convenience_libs = (.*) @hwloclib@ (.*)$" _
before after)
(string-append "pmpi_convenience_libs = "
before " " after)))
#t)))))
(home-page "/")
(synopsis "Implementation of the Message Passing Interface (MPI)")
(description
"MPICH is a high-performance and portable implementation of the Message
Passing Interface (MPI) standard (MPI-1, MPI-2 and MPI-3). MPICH provides an
MPI implementation that efficiently supports different computation and
communication platforms including commodity clusters, high-speed networks (10
Gigabit Ethernet, InfiniBand, Myrinet, Quadrics), and proprietary high-end
computing systems (Blue Gene, Cray). It enables research in MPI through a
modular framework for other derived implementations.")
(license license:bsd-2)))
|
b2294c696a1b3d5644e0d68493ebe8bc82c04977fa6c129894db8a3c7bac3870 | strictly-lang/compiler | Root.hs | module Compiler.Types.Root (compileRoot) where
import Compiler.Types
import Compiler.Types.Model.Base (compileModel)
import Compiler.Types.Style.Base (compileStyle)
import Compiler.Types.View.Base (compileView)
import Compiler.Util (indent, propertyChainToString, slashToCamelCase, slashToDash)
import Control.Monad.State
import Data.List (intercalate, isPrefixOf, partition)
import Types
propertiesScope = [DotNotation "this", DotNotation "properties"]
mountedBool = "this._mounted"
parent = "this.shadowRoot"
startState :: String -> AppState
startState componentPath = (componentPath, 0, [])
compileRoot :: String -> [Root] -> String
compileRoot componentPath ast =
let (result, (_, _, imports)) = runState (compileRoot' componentPath ast ast []) (startState componentPath)
in indent
( concat
( [ [ Ln ("import \"" ++ path ++ "\";"),
Br
]
| Import (path, _) <- imports
]
)
++ result
)
compileRoot' :: String -> [Root] -> [Root] -> VariableStack -> AppStateMonad [Indent]
compileRoot' componentPath [] ast variableStack = do return []
compileRoot' componentPath ((RootImport (Import (path, imports))) : ns) ast variableStack = do
next <- compileRoot' componentPath ns ast ([([importVariable], [DotNotation importVariable]) | importVariable <- imports] ++ variableStack)
return
( [ Ln ("import { " ++ intercalate ", " imports ++ " } from \"" ++ path ++ "\";"),
Br
]
++ next
)
compileRoot' componentPath ((View children) : ns) ast variableStack = do
let scope = [DotNotation "this", DotNotation "_el"]
variableStack' = getModelScopeVariableStack ast ++ variableStack
styleContents = [compileStyle style | Style style <- ast]
modelJs <- getModelFactories ast variableStack
childrenResult <- compileView (styleContents ++ children) (Context (scope, (["props"], propertiesScope) : variableStack')) parent []
next <- compileRoot' componentPath ns ast variableStack
return
( [ Ln ("class " ++ slashToCamelCase componentPath ++ " extends HTMLElement {"),
Br,
Ind
( [ Ln "constructor() {",
Br,
Ind
[ Ln "super();",
Br,
Ln (mountedBool ++ " = false;"),
Br,
Ln (propertyChainToString propertiesScope ++ " = {};"),
Br
],
Ln "}",
Br,
Br
]
++ modelJs
++ [ Br,
Ln "connectedCallback() {",
Br,
Ind
( [ Ln (mountedBool ++ " = true;"),
Br,
Ln (propertyChainToString scope ++ " = {};"),
Br,
Ln "this.attachShadow({mode: 'open'});",
Br
]
++ compileCreate childrenResult
),
Ln "}",
Br,
Br
]
++ walkDependencies (filter (not . ((\value -> value `elem` map snd variableStack') . fst)) (compileUpdate childrenResult))
),
Ln "}",
Br,
Br,
Ln ("customElements.define(\"" ++ slashToDash componentPath ++ "\", " ++ slashToCamelCase componentPath ++ ");"),
Br
]
++ next
)
compileRoot' componentPath ((Model _ _) : ns) ast variableStack = compileRoot' componentPath ns ast variableStack
compileRoot' componentPath ((Style styleContents) : ns) ast variableStack = do compileRoot' componentPath ns ast variableStack
getModelFactories :: [Root] -> VariableStack -> AppStateMonad [Indent]
getModelFactories [] _ = do return []
getModelFactories (model@(Model _ _) : rest) variableStack = do
result <- compileModel model variableStack
nextResult <- getModelFactories rest variableStack
return (result ++ nextResult)
getModelFactories (_ : rest) variableStack = getModelFactories rest variableStack
splitBy :: (Foldable t, Eq a) => a -> t a -> [[a]]
splitBy delimiter = foldr f [[]]
where
f c l@(x : xs)
| c == delimiter = [] : l
| otherwise = (c : x) : xs
getModelScopeVariableStack :: [Root] -> [([PublicVariableName], InternalVariableName)]
getModelScopeVariableStack [] = []
getModelScopeVariableStack ((Model name _) : restRoot) = ([name], [DotNotation "this", DotNotation name]) : getModelScopeVariableStack restRoot
getModelScopeVariableStack (currentRoot : restRoot) = getModelScopeVariableStack restRoot
walkDependencies :: UpdateCallbacks -> [Indent]
walkDependencies [] = []
walkDependencies (((internalName, updateCallback) : updateCallbacks))
| isProps =
let setterName = internalNameToSetterName internalName
(matchedUpdateCallbacks, unmatchedUpdateCallbacks) = partition ((setterName ==) . internalNameToSetterName . fst) updateCallbacks
in getSetter setterName (updateCallback : map snd matchedUpdateCallbacks) ++ walkDependencies unmatchedUpdateCallbacks
| otherwise = walkDependencies updateCallbacks
where
isProps = propertiesScope `isPrefixOf` internalName
internalNameToSetterName :: InternalVariableName -> String
internalNameToSetterName internalName
| propertiesScope `isPrefixOf` internalName =
let DotNotation setterName = head (drop (length propertiesScope) internalName)
in setterName
| otherwise = error ("There is an observer missing for " ++ propertyChainToString internalName)
getSetter :: String -> [[Indent]] -> [Indent]
getSetter name updateCallback =
[ Ln ("set " ++ name ++ "(value) {"),
Br,
Ind
[ Ln (propertyChainToString (propertiesScope ++ [DotNotation name]) ++ " = value;"),
Br,
Ln ("if (" ++ mountedBool ++ ") {"),
Br,
Ind (concat updateCallback),
Br,
Ln "}",
Br
],
Ln "}",
Br,
Br
] | null | https://raw.githubusercontent.com/strictly-lang/compiler/dc47868e35a6de1e0acabb642a630b2e96bb43fd/src-lib/Compiler/Types/Root.hs | haskell | module Compiler.Types.Root (compileRoot) where
import Compiler.Types
import Compiler.Types.Model.Base (compileModel)
import Compiler.Types.Style.Base (compileStyle)
import Compiler.Types.View.Base (compileView)
import Compiler.Util (indent, propertyChainToString, slashToCamelCase, slashToDash)
import Control.Monad.State
import Data.List (intercalate, isPrefixOf, partition)
import Types
propertiesScope = [DotNotation "this", DotNotation "properties"]
mountedBool = "this._mounted"
parent = "this.shadowRoot"
startState :: String -> AppState
startState componentPath = (componentPath, 0, [])
compileRoot :: String -> [Root] -> String
compileRoot componentPath ast =
let (result, (_, _, imports)) = runState (compileRoot' componentPath ast ast []) (startState componentPath)
in indent
( concat
( [ [ Ln ("import \"" ++ path ++ "\";"),
Br
]
| Import (path, _) <- imports
]
)
++ result
)
compileRoot' :: String -> [Root] -> [Root] -> VariableStack -> AppStateMonad [Indent]
compileRoot' componentPath [] ast variableStack = do return []
compileRoot' componentPath ((RootImport (Import (path, imports))) : ns) ast variableStack = do
next <- compileRoot' componentPath ns ast ([([importVariable], [DotNotation importVariable]) | importVariable <- imports] ++ variableStack)
return
( [ Ln ("import { " ++ intercalate ", " imports ++ " } from \"" ++ path ++ "\";"),
Br
]
++ next
)
compileRoot' componentPath ((View children) : ns) ast variableStack = do
let scope = [DotNotation "this", DotNotation "_el"]
variableStack' = getModelScopeVariableStack ast ++ variableStack
styleContents = [compileStyle style | Style style <- ast]
modelJs <- getModelFactories ast variableStack
childrenResult <- compileView (styleContents ++ children) (Context (scope, (["props"], propertiesScope) : variableStack')) parent []
next <- compileRoot' componentPath ns ast variableStack
return
( [ Ln ("class " ++ slashToCamelCase componentPath ++ " extends HTMLElement {"),
Br,
Ind
( [ Ln "constructor() {",
Br,
Ind
[ Ln "super();",
Br,
Ln (mountedBool ++ " = false;"),
Br,
Ln (propertyChainToString propertiesScope ++ " = {};"),
Br
],
Ln "}",
Br,
Br
]
++ modelJs
++ [ Br,
Ln "connectedCallback() {",
Br,
Ind
( [ Ln (mountedBool ++ " = true;"),
Br,
Ln (propertyChainToString scope ++ " = {};"),
Br,
Ln "this.attachShadow({mode: 'open'});",
Br
]
++ compileCreate childrenResult
),
Ln "}",
Br,
Br
]
++ walkDependencies (filter (not . ((\value -> value `elem` map snd variableStack') . fst)) (compileUpdate childrenResult))
),
Ln "}",
Br,
Br,
Ln ("customElements.define(\"" ++ slashToDash componentPath ++ "\", " ++ slashToCamelCase componentPath ++ ");"),
Br
]
++ next
)
compileRoot' componentPath ((Model _ _) : ns) ast variableStack = compileRoot' componentPath ns ast variableStack
compileRoot' componentPath ((Style styleContents) : ns) ast variableStack = do compileRoot' componentPath ns ast variableStack
getModelFactories :: [Root] -> VariableStack -> AppStateMonad [Indent]
getModelFactories [] _ = do return []
getModelFactories (model@(Model _ _) : rest) variableStack = do
result <- compileModel model variableStack
nextResult <- getModelFactories rest variableStack
return (result ++ nextResult)
getModelFactories (_ : rest) variableStack = getModelFactories rest variableStack
splitBy :: (Foldable t, Eq a) => a -> t a -> [[a]]
splitBy delimiter = foldr f [[]]
where
f c l@(x : xs)
| c == delimiter = [] : l
| otherwise = (c : x) : xs
getModelScopeVariableStack :: [Root] -> [([PublicVariableName], InternalVariableName)]
getModelScopeVariableStack [] = []
getModelScopeVariableStack ((Model name _) : restRoot) = ([name], [DotNotation "this", DotNotation name]) : getModelScopeVariableStack restRoot
getModelScopeVariableStack (currentRoot : restRoot) = getModelScopeVariableStack restRoot
walkDependencies :: UpdateCallbacks -> [Indent]
walkDependencies [] = []
walkDependencies (((internalName, updateCallback) : updateCallbacks))
| isProps =
let setterName = internalNameToSetterName internalName
(matchedUpdateCallbacks, unmatchedUpdateCallbacks) = partition ((setterName ==) . internalNameToSetterName . fst) updateCallbacks
in getSetter setterName (updateCallback : map snd matchedUpdateCallbacks) ++ walkDependencies unmatchedUpdateCallbacks
| otherwise = walkDependencies updateCallbacks
where
isProps = propertiesScope `isPrefixOf` internalName
internalNameToSetterName :: InternalVariableName -> String
internalNameToSetterName internalName
| propertiesScope `isPrefixOf` internalName =
let DotNotation setterName = head (drop (length propertiesScope) internalName)
in setterName
| otherwise = error ("There is an observer missing for " ++ propertyChainToString internalName)
getSetter :: String -> [[Indent]] -> [Indent]
getSetter name updateCallback =
[ Ln ("set " ++ name ++ "(value) {"),
Br,
Ind
[ Ln (propertyChainToString (propertiesScope ++ [DotNotation name]) ++ " = value;"),
Br,
Ln ("if (" ++ mountedBool ++ ") {"),
Br,
Ind (concat updateCallback),
Br,
Ln "}",
Br
],
Ln "}",
Br,
Br
] | |
15adb449fe3b28275b28d9ad4a064679082260b07a24f4fb9c4f7d43cf7e7239 | functionally/mantis-oracle | PAB.hs | -----------------------------------------------------------------------------
--
-- Module : $Headers
Copyright : ( c ) 2021
License : MIT
--
Maintainer : < >
-- Stability : Experimental
Portability : Portable
--
| application backend simulation for oracle contracts .
--
-----------------------------------------------------------------------------
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RankNTypes #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeApplications #
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module Mantra.Oracle.PAB (
-- * Types
TheContracts(..)
-- * Action
, runPAB
) where
import Control.Monad (forM_, void, when)
import Control.Monad.Freer (Eff, Member, type (~>), interpret)
import Control.Monad.Freer.Error (Error)
import Control.Monad.Freer.Extras.Log (LogMsg)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Aeson (FromJSON, Result(..), ToJSON, fromJSON)
import Data.Default (def)
import Data.Monoid (Last(..))
import Data.OpenApi.Schema (ToSchema(..))
import Data.Text (Text, pack)
import Data.Text.Prettyprint.Doc (Pretty(..), viaShow)
import GHC.Generics (Generic)
import Ledger (pubKeyHash, txId)
import Ledger.Constraints (mustPayToPubKey)
import Ledger.Value (AssetClass(..), TokenName, singleton)
import Mantra.Orphans ()
import Plutus.Contract (Contract, ContractInstanceId, Empty, awaitTxConfirmed, mapError, ownPubKey, submitTx, tell)
import Plutus.PAB.Effects.Contract (ContractEffect(..))
import Plutus.PAB.Effects.Contract.Builtin (Builtin, HasDefinitions(..), SomeBuiltin(..), contractHandler, endpointsToSchemas, handleBuiltin)
import Plutus.PAB.Monitoring.PABLogMsg (PABMultiAgentMsg)
import Plutus.PAB.Simulator (SimulatorEffectHandlers)
import Plutus.PAB.Types (PABError(..))
import PlutusTx (Data(B))
import Wallet.Emulator.Types (Wallet(..), walletPubKey)
import Wallet.Types (ContractInstanceId(..))
import qualified Mantra.Oracle.Client as O (ClientSchema, runOracleClient)
import qualified Mantra.Oracle.Controller as O (OracleSchema, runOracleController, writeOracle)
import qualified Mantra.Oracle.Types as O (Oracle, Parameters(..), makeOracle)
import qualified Plutus.Contracts.Currency as C (CurrencyError, OneShotCurrency, currencySymbol, mintContract)
import qualified Plutus.PAB.Simulator as S (Simulation, activateContract, logString, mkSimulatorHandlers, runSimulationWith, waitForState, waitUntilFinished)
import qualified Plutus.PAB.Webserver.Server as P (startServerDebug)
-- | Contract specifications.
data TheContracts =
Init TokenName TokenName TokenName Integer Integer [(Wallet, Integer, FilePath)] -- ^ Initializer with control token name, datum token name, fee token name, fee amount, lovelace amount, and wallets with initial fee tokens and CID path.
| TheController O.Oracle -- ^ Controller.
| TheClient O.Oracle -- ^ Client.
deriving (Eq, FromJSON, Generic, Show, ToJSON)
instance ToSchema TheContracts where
declareNamedSchema = error "Schema not declared." -- FIXME: Implement this!
instance Pretty TheContracts where
pretty = viaShow
instance HasDefinitions TheContracts where
getDefinitions = []
getSchema = \case
Init{} -> endpointsToSchemas @Empty
TheController _ -> endpointsToSchemas @O.OracleSchema
TheClient _ -> endpointsToSchemas @O.ClientSchema
getContract = \case
Init controlName datumName feeName feeAmount lovelaceAmount wallets -> SomeBuiltin $ initContract controlName datumName feeName feeAmount lovelaceAmount wallets
TheController oracle -> SomeBuiltin $ O.runOracleController oracle
TheClient oracle -> SomeBuiltin $ O.runOracleClient oracle
| Run the application backend . The first wallet controls the oracle .
runPAB :: TokenName -- ^ Name for the control token.
-> TokenName -- ^ Name for the datum token.
-> TokenName -- ^ Name for the fee token.
-> Integer -- ^ The fee amount.
-> Integer -- ^ The lovelace ammount.
-> [(Wallet, Integer, FilePath)] -- ^ Wallets, their initial fee token amount, and the paths to their Contract ID (CID) files.
-> IO () -- ^ Action for running the PAB.
runPAB controlName datumName feeName feeAmount lovelaceAmount wallets =
void . S.runSimulationWith handlers
$ do
let
(w1, _, f1) = head wallets
S.logString @(Builtin TheContracts) "Starting Oracle PAB webserver. Press enter to exit."
shutdown <- P.startServerDebug
cidInit <-
S.activateContract w1
$ Init controlName datumName feeName feeAmount lovelaceAmount wallets
oracle <- waitForLast cidInit
void $ S.waitUntilFinished cidInit
cidOracle <- S.activateContract w1 $ TheController oracle
liftIO . writeFile f1 . show $ unContractInstanceId cidOracle
forM_ wallets
$ \(w, _, f) ->
when (w /= w1)
$ do
cid <- S.activateContract w $ TheClient oracle
liftIO . writeFile f . show $ unContractInstanceId cid
void $ liftIO getLine
shutdown
-- | Wait for the success of a contract.
waitForLast :: FromJSON a
^ The Contract ID .
-> S.Simulation t a -- ^ Action for waiting.
waitForLast cid =
flip S.waitForState cid
$ \json ->
case fromJSON json of
Success (Last (Just x)) -> Just x
_ -> Nothing
-- | Handle the contracts.
handleTheContracts :: Member (Error PABError) effs
=> Member (LogMsg (PABMultiAgentMsg (Builtin TheContracts))) effs
=> ContractEffect (Builtin TheContracts)
~> Eff effs
handleTheContracts =
contractHandler handleBuiltin
-- | Handlers for the contract.
handlers :: SimulatorEffectHandlers (Builtin TheContracts)
handlers =
S.mkSimulatorHandlers @(Builtin TheContracts) def def
$ interpret handleTheContracts
| Initialize the contract . The first wallet controls the oracle .
initContract :: TokenName -- ^ Name for the control token.
-> TokenName -- ^ Name for the datum token.
-> TokenName -- ^ Name for the fee token.
-> Integer -- ^ The fee amount.
-> Integer -- ^ The lovelace amount.
-> [(Wallet, Integer, FilePath)] -- ^ Wallets, their initial fee token amount, and the paths to their Contract ID (CID) files.
-> Contract (Last O.Oracle) Empty Text () -- ^ Action for initializing the contract.
initContract controlName datumName feeName feeAmount lovelaceAmount wallets =
do
ownPK <- pubKeyHash <$> ownPubKey
symbol <-
mapError (pack . show)
$ C.currencySymbol
<$> (
C.mintContract ownPK
[
(controlName, 1 )
, (datumName , 1 )
, (feeName , sum $ snd3 <$> wallets)
]
:: Contract (Last O.Oracle) s C.CurrencyError C.OneShotCurrency
)
sequence_
[
do
let
pkh = pubKeyHash $ walletPubKey w
v = singleton symbol feeName amount
tx <- submitTx $ mustPayToPubKey pkh v
awaitTxConfirmed $ txId tx
|
(w, amount, _) <- wallets
]
let
controlParameter = AssetClass (symbol, controlName)
datumParameter = AssetClass (symbol, datumName )
feeToken = AssetClass (symbol, feeName )
oracle = O.makeOracle O.Parameters{..}
O.writeOracle oracle $ B ""
tell . Last $ Just oracle
| Extract the second entry in a triplet .
snd3 :: (a, b, c) -> b
snd3 (_, x, _) = x
| null | https://raw.githubusercontent.com/functionally/mantis-oracle/10331c6720d8413fd9a01b8c7fb6dc0ef0f20f31/src/Mantra/Oracle/PAB.hs | haskell | ---------------------------------------------------------------------------
Module : $Headers
Stability : Experimental
---------------------------------------------------------------------------
# LANGUAGE DeriveAnyClass #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
* Types
* Action
| Contract specifications.
^ Initializer with control token name, datum token name, fee token name, fee amount, lovelace amount, and wallets with initial fee tokens and CID path.
^ Controller.
^ Client.
FIXME: Implement this!
^ Name for the control token.
^ Name for the datum token.
^ Name for the fee token.
^ The fee amount.
^ The lovelace ammount.
^ Wallets, their initial fee token amount, and the paths to their Contract ID (CID) files.
^ Action for running the PAB.
| Wait for the success of a contract.
^ Action for waiting.
| Handle the contracts.
| Handlers for the contract.
^ Name for the control token.
^ Name for the datum token.
^ Name for the fee token.
^ The fee amount.
^ The lovelace amount.
^ Wallets, their initial fee token amount, and the paths to their Contract ID (CID) files.
^ Action for initializing the contract. | Copyright : ( c ) 2021
License : MIT
Maintainer : < >
Portability : Portable
| application backend simulation for oracle contracts .
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE RankNTypes #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeApplications #
module Mantra.Oracle.PAB (
TheContracts(..)
, runPAB
) where
import Control.Monad (forM_, void, when)
import Control.Monad.Freer (Eff, Member, type (~>), interpret)
import Control.Monad.Freer.Error (Error)
import Control.Monad.Freer.Extras.Log (LogMsg)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Aeson (FromJSON, Result(..), ToJSON, fromJSON)
import Data.Default (def)
import Data.Monoid (Last(..))
import Data.OpenApi.Schema (ToSchema(..))
import Data.Text (Text, pack)
import Data.Text.Prettyprint.Doc (Pretty(..), viaShow)
import GHC.Generics (Generic)
import Ledger (pubKeyHash, txId)
import Ledger.Constraints (mustPayToPubKey)
import Ledger.Value (AssetClass(..), TokenName, singleton)
import Mantra.Orphans ()
import Plutus.Contract (Contract, ContractInstanceId, Empty, awaitTxConfirmed, mapError, ownPubKey, submitTx, tell)
import Plutus.PAB.Effects.Contract (ContractEffect(..))
import Plutus.PAB.Effects.Contract.Builtin (Builtin, HasDefinitions(..), SomeBuiltin(..), contractHandler, endpointsToSchemas, handleBuiltin)
import Plutus.PAB.Monitoring.PABLogMsg (PABMultiAgentMsg)
import Plutus.PAB.Simulator (SimulatorEffectHandlers)
import Plutus.PAB.Types (PABError(..))
import PlutusTx (Data(B))
import Wallet.Emulator.Types (Wallet(..), walletPubKey)
import Wallet.Types (ContractInstanceId(..))
import qualified Mantra.Oracle.Client as O (ClientSchema, runOracleClient)
import qualified Mantra.Oracle.Controller as O (OracleSchema, runOracleController, writeOracle)
import qualified Mantra.Oracle.Types as O (Oracle, Parameters(..), makeOracle)
import qualified Plutus.Contracts.Currency as C (CurrencyError, OneShotCurrency, currencySymbol, mintContract)
import qualified Plutus.PAB.Simulator as S (Simulation, activateContract, logString, mkSimulatorHandlers, runSimulationWith, waitForState, waitUntilFinished)
import qualified Plutus.PAB.Webserver.Server as P (startServerDebug)
data TheContracts =
deriving (Eq, FromJSON, Generic, Show, ToJSON)
instance ToSchema TheContracts where
instance Pretty TheContracts where
pretty = viaShow
instance HasDefinitions TheContracts where
getDefinitions = []
getSchema = \case
Init{} -> endpointsToSchemas @Empty
TheController _ -> endpointsToSchemas @O.OracleSchema
TheClient _ -> endpointsToSchemas @O.ClientSchema
getContract = \case
Init controlName datumName feeName feeAmount lovelaceAmount wallets -> SomeBuiltin $ initContract controlName datumName feeName feeAmount lovelaceAmount wallets
TheController oracle -> SomeBuiltin $ O.runOracleController oracle
TheClient oracle -> SomeBuiltin $ O.runOracleClient oracle
| Run the application backend . The first wallet controls the oracle .
runPAB controlName datumName feeName feeAmount lovelaceAmount wallets =
void . S.runSimulationWith handlers
$ do
let
(w1, _, f1) = head wallets
S.logString @(Builtin TheContracts) "Starting Oracle PAB webserver. Press enter to exit."
shutdown <- P.startServerDebug
cidInit <-
S.activateContract w1
$ Init controlName datumName feeName feeAmount lovelaceAmount wallets
oracle <- waitForLast cidInit
void $ S.waitUntilFinished cidInit
cidOracle <- S.activateContract w1 $ TheController oracle
liftIO . writeFile f1 . show $ unContractInstanceId cidOracle
forM_ wallets
$ \(w, _, f) ->
when (w /= w1)
$ do
cid <- S.activateContract w $ TheClient oracle
liftIO . writeFile f . show $ unContractInstanceId cid
void $ liftIO getLine
shutdown
waitForLast :: FromJSON a
^ The Contract ID .
waitForLast cid =
flip S.waitForState cid
$ \json ->
case fromJSON json of
Success (Last (Just x)) -> Just x
_ -> Nothing
handleTheContracts :: Member (Error PABError) effs
=> Member (LogMsg (PABMultiAgentMsg (Builtin TheContracts))) effs
=> ContractEffect (Builtin TheContracts)
~> Eff effs
handleTheContracts =
contractHandler handleBuiltin
handlers :: SimulatorEffectHandlers (Builtin TheContracts)
handlers =
S.mkSimulatorHandlers @(Builtin TheContracts) def def
$ interpret handleTheContracts
| Initialize the contract . The first wallet controls the oracle .
initContract controlName datumName feeName feeAmount lovelaceAmount wallets =
do
ownPK <- pubKeyHash <$> ownPubKey
symbol <-
mapError (pack . show)
$ C.currencySymbol
<$> (
C.mintContract ownPK
[
(controlName, 1 )
, (datumName , 1 )
, (feeName , sum $ snd3 <$> wallets)
]
:: Contract (Last O.Oracle) s C.CurrencyError C.OneShotCurrency
)
sequence_
[
do
let
pkh = pubKeyHash $ walletPubKey w
v = singleton symbol feeName amount
tx <- submitTx $ mustPayToPubKey pkh v
awaitTxConfirmed $ txId tx
|
(w, amount, _) <- wallets
]
let
controlParameter = AssetClass (symbol, controlName)
datumParameter = AssetClass (symbol, datumName )
feeToken = AssetClass (symbol, feeName )
oracle = O.makeOracle O.Parameters{..}
O.writeOracle oracle $ B ""
tell . Last $ Just oracle
| Extract the second entry in a triplet .
snd3 :: (a, b, c) -> b
snd3 (_, x, _) = x
|
3b40e25be2ac32288d56b2073e2b5a234d2a97dcd6bb990fcf379f80a6809f2d | dasuxullebt/uxul-world | xy-coordinates.lisp | Copyright 2009 - 2011
(in-package :uxul-world)
(declaim (inline make-xy coordinate-distance))
(defstruct xy-struct (x 0 :type fixnum) (y 0 :type fixnum))
(defmethod x ((obj xy-struct)) (slot-value obj 'x))
(defmethod (setf x) (new-value (obj xy-struct))
(setf (slot-value obj 'x) (the number new-value)))
(defmethod y ((obj xy-struct)) (slot-value obj 'y))
(defmethod (setf y) (new-value (obj xy-struct))
(setf (slot-value obj 'y) (the number new-value)))
(defclass xy-coordinates ()
((x :accessor x :initarg :x :initform 0 :type fixnum)
(y :accessor y :initarg :y :initform 0 :type fixnum)))
(defun coordinate-distance (a b)
"Calculate the euklidian distance of two points. They must have x-
and y-accessors."
(sqrt (+ (expt (- (x a) (x b)) 2) (expt (- (y a) (y b)) 2))))
(defun make-xy (x y)
(declare (type fixnum x y))
"Guess what this function does..."
(make-xy-struct :x x :y y)) | null | https://raw.githubusercontent.com/dasuxullebt/uxul-world/f05e44b099e5976411b3ef1f980ec616bd221425/xy-coordinates.lisp | lisp | Copyright 2009 - 2011
(in-package :uxul-world)
(declaim (inline make-xy coordinate-distance))
(defstruct xy-struct (x 0 :type fixnum) (y 0 :type fixnum))
(defmethod x ((obj xy-struct)) (slot-value obj 'x))
(defmethod (setf x) (new-value (obj xy-struct))
(setf (slot-value obj 'x) (the number new-value)))
(defmethod y ((obj xy-struct)) (slot-value obj 'y))
(defmethod (setf y) (new-value (obj xy-struct))
(setf (slot-value obj 'y) (the number new-value)))
(defclass xy-coordinates ()
((x :accessor x :initarg :x :initform 0 :type fixnum)
(y :accessor y :initarg :y :initform 0 :type fixnum)))
(defun coordinate-distance (a b)
"Calculate the euklidian distance of two points. They must have x-
and y-accessors."
(sqrt (+ (expt (- (x a) (x b)) 2) (expt (- (y a) (y b)) 2))))
(defun make-xy (x y)
(declare (type fixnum x y))
"Guess what this function does..."
(make-xy-struct :x x :y y)) | |
f8cbbdd9e33d5ac65cfbd3069243543de6219509bcca17d59ebd98da2f747f24 | fluree/db | proto.cljc | (ns fluree.db.ledger.proto)
#?(:clj (set! *warn-on-reflection* true))
(defprotocol iCommit
;; retrieving/updating DBs
(-commit! [ledger db] [ledger db opts] "Commits a db to a ledger."))
(defprotocol iLedger
;; retrieving/updating DBs
(-db [ledger] [ledger opts] "Returns queryable db with specified options")
(-db-update [ledger db] "Updates ledger state with new DB, and optional branch. Returns updated db (which might be modified with newer index).")
;; branching
(-branch [ledger] [ledger branch] "Returns all branch metadata, or metadata for just specified branch. :default branch is always current default.")
(-branch-checkout [ledger branch] "Checks out (or sets default) the specified branch. If optional 'create?' flag, forks from latest db of current branch")
(-branch-create [ledger branch opts] "Creates a new branch with specified options map.")
(-branch-delete [ledger branch] "Deletes specified branch.")
;; committing
(-commit-update [ledger branch db] [ledger branch db force?] "Once a commit completes, update ledger state to reflect. If optional force? flag present, don't validate consistent t sequence")
(-status [ledger] [ledger branch] "Returns status for branch (default branch if nil)")
;; ledger data across time
(-t-range [ledger from-t to-t] [ledger branch from-t to-t] "Returns list of ledger entries from/to t")
(-time->t [ledger time] "Returns t value at specified time.")
(-hash->t [ledger time] "Returns t value at specified ledger hash value.")
(-tag->t [ledger time] "Returns t value at specified ledger tag value.")
;; default did
(-did [ledger] "Returns default did configuration map")
;; alias name for graph
(-alias [ledger] "Returns the ledger local alias / graph name")
(-address [ledger] "Returns the permanent ledger address")
(-close [ledger] "Shuts down ledger processes and clears used resources."))
| null | https://raw.githubusercontent.com/fluree/db/6da45af99665a158f01fe6153f61dac84a1d190d/src/fluree/db/ledger/proto.cljc | clojure | retrieving/updating DBs
retrieving/updating DBs
branching
committing
ledger data across time
default did
alias name for graph | (ns fluree.db.ledger.proto)
#?(:clj (set! *warn-on-reflection* true))
(defprotocol iCommit
(-commit! [ledger db] [ledger db opts] "Commits a db to a ledger."))
(defprotocol iLedger
(-db [ledger] [ledger opts] "Returns queryable db with specified options")
(-db-update [ledger db] "Updates ledger state with new DB, and optional branch. Returns updated db (which might be modified with newer index).")
(-branch [ledger] [ledger branch] "Returns all branch metadata, or metadata for just specified branch. :default branch is always current default.")
(-branch-checkout [ledger branch] "Checks out (or sets default) the specified branch. If optional 'create?' flag, forks from latest db of current branch")
(-branch-create [ledger branch opts] "Creates a new branch with specified options map.")
(-branch-delete [ledger branch] "Deletes specified branch.")
(-commit-update [ledger branch db] [ledger branch db force?] "Once a commit completes, update ledger state to reflect. If optional force? flag present, don't validate consistent t sequence")
(-status [ledger] [ledger branch] "Returns status for branch (default branch if nil)")
(-t-range [ledger from-t to-t] [ledger branch from-t to-t] "Returns list of ledger entries from/to t")
(-time->t [ledger time] "Returns t value at specified time.")
(-hash->t [ledger time] "Returns t value at specified ledger hash value.")
(-tag->t [ledger time] "Returns t value at specified ledger tag value.")
(-did [ledger] "Returns default did configuration map")
(-alias [ledger] "Returns the ledger local alias / graph name")
(-address [ledger] "Returns the permanent ledger address")
(-close [ledger] "Shuts down ledger processes and clears used resources."))
|
821c079acfa63b717363b1b5dd1b8dd2634e2185eaa74f959a12e3d71dd914a6 | chaoxu/fancy-walks | 38.hs |
import Data.List
check n = (=="123456789").sort $ mapping n
mapping n = concatMap show $
last $ takeWhile (all ((==[]).tail).group.sort.concatMap show) $
inits [n,n+n..]
answer :: [Integer]
answer = map (read.mapping) $ filter check [1..9999]
problem_38 = maximum answer
main = print problem_38
| null | https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/projecteuler.net/38.hs | haskell |
import Data.List
check n = (=="123456789").sort $ mapping n
mapping n = concatMap show $
last $ takeWhile (all ((==[]).tail).group.sort.concatMap show) $
inits [n,n+n..]
answer :: [Integer]
answer = map (read.mapping) $ filter check [1..9999]
problem_38 = maximum answer
main = print problem_38
| |
ad0a6e9a477b4f7a93ab110a59674199b5998fb2255d1c32b206848a642d8803 | michaelklishin/langohr | util.clj | This source code is dual - licensed under the Apache License , version
2.0 , and the Eclipse Public License , version 1.0 .
;;
;; The APL v2.0:
;;
;; ----------------------------------------------------------------------------------
Copyright ( c ) 2011 - 2020 , , and the ClojureWerkz Team
;;
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.
;; ----------------------------------------------------------------------------------
;;
The EPL v1.0 :
;;
;; ----------------------------------------------------------------------------------
Copyright ( c ) 2011 - 2020 , , and the ClojureWerkz Team .
;; All rights reserved.
;;
;; This program and the accompanying materials are made available under the terms of
the Eclipse Public License Version 1.0 ,
;; which accompanies this distribution and is available at
-v10.html .
;; ----------------------------------------------------------------------------------
(ns langohr.util
(:import java.util.UUID))
;;
;; API
;;
(defn generate-consumer-tag
[^String base]
(str base "-" (UUID/randomUUID)))
| null | https://raw.githubusercontent.com/michaelklishin/langohr/0c63ac3c6bc97d73e290ed366e9e97e07d39dedb/src/clojure/langohr/util.clj | clojure |
The APL v2.0:
----------------------------------------------------------------------------------
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.
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
All rights reserved.
This program and the accompanying materials are made available under the terms of
which accompanies this distribution and is available at
----------------------------------------------------------------------------------
API
| This source code is dual - licensed under the Apache License , version
2.0 , and the Eclipse Public License , version 1.0 .
Copyright ( c ) 2011 - 2020 , , and the ClojureWerkz Team
distributed under the License is distributed on an " AS IS " BASIS ,
The EPL v1.0 :
Copyright ( c ) 2011 - 2020 , , and the ClojureWerkz Team .
the Eclipse Public License Version 1.0 ,
-v10.html .
(ns langohr.util
(:import java.util.UUID))
(defn generate-consumer-tag
[^String base]
(str base "-" (UUID/randomUUID)))
|
0c21a87b1f9daafa923270b71e3460744540fa92e35b3f293941bb55ec474ec6 | mirage/ocaml-xenstore-server | logging.mli |
* Copyright ( C ) Citrix Systems Inc.
*
* 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 ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* 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 .
* Copyright (C) Citrix Systems Inc.
*
* 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; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* 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.
*)
val debug: string -> ('b, unit, string, unit) format4 -> 'b
val info: string -> ('b, unit, string, unit) format4 -> 'b
val warn: string -> ('b, unit, string, unit) format4 -> 'b
val error: string -> ('b, unit, string, unit) format4 -> 'b
type logger
(** An in-memory non-blocking logger with a fixed size circular buffer.
If the buffer is full then some messages may be dropped. The logger
will replace runs of dropped messages with a single message with
a count of how many messages were dropped. *)
val logger: logger
(** The application logger *)
val get: logger -> string list Lwt.t
(** [get logger] returns any available log lines or, if none are available,
blocks until some are available. *)
| null | https://raw.githubusercontent.com/mirage/ocaml-xenstore-server/2a8ae397d2f9291107b5d9e9cfc6085fde8c0982/server/logging.mli | ocaml | * An in-memory non-blocking logger with a fixed size circular buffer.
If the buffer is full then some messages may be dropped. The logger
will replace runs of dropped messages with a single message with
a count of how many messages were dropped.
* The application logger
* [get logger] returns any available log lines or, if none are available,
blocks until some are available. |
* Copyright ( C ) Citrix Systems Inc.
*
* 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 ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* 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 .
* Copyright (C) Citrix Systems Inc.
*
* 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; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* 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.
*)
val debug: string -> ('b, unit, string, unit) format4 -> 'b
val info: string -> ('b, unit, string, unit) format4 -> 'b
val warn: string -> ('b, unit, string, unit) format4 -> 'b
val error: string -> ('b, unit, string, unit) format4 -> 'b
type logger
val logger: logger
val get: logger -> string list Lwt.t
|
6b580e047f82f79af4c965c4c543d1d3b83d3c4fc04366901e5197a3a020fd38 | yurug/ocaml4.04.0-copatterns | btype.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
and , projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Basic operations on core types *)
open Misc
open Asttypes
open Types
(**** Sets, maps and hashtables of types ****)
module TypeSet = Set.Make(TypeOps)
module TypeMap = Map.Make (TypeOps)
module TypeHash = Hashtbl.Make(TypeOps)
(**** Forward declarations ****)
let print_raw =
ref (fun _ -> assert false : Format.formatter -> type_expr -> unit)
(**** Type level management ****)
let generic_level = 100000000
(* Used to mark a type during a traversal. *)
let lowest_level = 0
let pivot_level = 2 * lowest_level - 1
(* pivot_level - lowest_level < lowest_level *)
(**** Some type creators ****)
let new_id = ref (-1)
let newty2 level desc =
incr new_id; { desc; level; id = !new_id }
let newgenty desc = newty2 generic_level desc
let newgenvar ?name () = newgenty (Tvar name)
let newmarkedvar level =
incr new_id ; { desc = Tvar ; level = pivot_level - level ; i d = ! new_id }
let ( ) =
incr new_id ;
{ desc = Tvar ; level = pivot_level - generic_level ; i d = ! new_id }
let newmarkedvar level =
incr new_id; { desc = Tvar; level = pivot_level - level; id = !new_id }
let newmarkedgenvar () =
incr new_id;
{ desc = Tvar; level = pivot_level - generic_level; id = !new_id }
*)
(**** Check some types ****)
let is_Tvar = function {desc=Tvar _} -> true | _ -> false
let is_Tunivar = function {desc=Tunivar _} -> true | _ -> false
let dummy_method = "*dummy method*"
let default_mty = function
Some mty -> mty
| None -> Mty_signature []
(**** Definitions for backtracking ****)
type change =
Ctype of type_expr * type_desc
| Ccompress of type_expr * type_desc * type_desc
| Clevel of type_expr * int
| Cname of
(Path.t * type_expr list) option ref * (Path.t * type_expr list) option
| Crow of row_field option ref * row_field option
| Ckind of field_kind option ref * field_kind option
| Ccommu of commutable ref * commutable
| Cuniv of type_expr option ref * type_expr option
| Ctypeset of TypeSet.t ref * TypeSet.t
type changes =
Change of change * changes ref
| Unchanged
| Invalid
let trail = Weak.create 1
let log_change ch =
match Weak.get trail 0 with None -> ()
| Some r ->
let r' = ref Unchanged in
r := Change (ch, r');
Weak.set trail 0 (Some r')
(**** Representative of a type ****)
let rec field_kind_repr =
function
Fvar {contents = Some kind} -> field_kind_repr kind
| kind -> kind
let rec repr_link compress t d =
function
{desc = Tlink t' as d'} ->
repr_link true t d' t'
| {desc = Tfield (_, k, _, t') as d'} when field_kind_repr k = Fabsent ->
repr_link true t d' t'
| t' ->
if compress then begin
log_change (Ccompress (t, t.desc, d)); t.desc <- d
end;
t'
let repr t =
match t.desc with
Tlink t' as d ->
repr_link false t d t'
| Tfield (_, k, _, t') as d when field_kind_repr k = Fabsent ->
repr_link false t d t'
| _ -> t
let rec commu_repr = function
Clink r when !r <> Cunknown -> commu_repr !r
| c -> c
let rec row_field_repr_aux tl = function
Reither(_, tl', _, {contents = Some fi}) ->
row_field_repr_aux (tl@tl') fi
| Reither(c, tl', m, r) ->
Reither(c, tl@tl', m, r)
| Rpresent (Some _) when tl <> [] ->
Rpresent (Some (List.hd tl))
| fi -> fi
let row_field_repr fi = row_field_repr_aux [] fi
let rec rev_concat l ll =
match ll with
[] -> l
| l'::ll -> rev_concat (l'@l) ll
let rec row_repr_aux ll row =
match (repr row.row_more).desc with
| Tvariant row' ->
let f = row.row_fields in
row_repr_aux (if f = [] then ll else f::ll) row'
| _ ->
if ll = [] then row else
{row with row_fields = rev_concat row.row_fields ll}
let row_repr row = row_repr_aux [] row
let rec row_field tag row =
let rec find = function
| (tag',f) :: fields ->
if tag = tag' then row_field_repr f else find fields
| [] ->
match repr row.row_more with
| {desc=Tvariant row'} -> row_field tag row'
| _ -> Rabsent
in find row.row_fields
let rec row_more row =
match repr row.row_more with
| {desc=Tvariant row'} -> row_more row'
| ty -> ty
let row_fixed row =
let row = row_repr row in
row.row_fixed ||
match (repr row.row_more).desc with
Tvar _ | Tnil -> false
| Tunivar _ | Tconstr _ -> true
| _ -> assert false
let static_row row =
let row = row_repr row in
row.row_closed &&
List.for_all
(fun (_,f) -> match row_field_repr f with Reither _ -> false | _ -> true)
row.row_fields
let hash_variant s =
let accu = ref 0 in
for i = 0 to String.length s - 1 do
accu := 223 * !accu + Char.code s.[i]
done;
reduce to 31 bits
accu := !accu land (1 lsl 31 - 1);
make it signed for 64 bits architectures
if !accu > 0x3FFFFFFF then !accu - (1 lsl 31) else !accu
let proxy ty =
let ty0 = repr ty in
match ty0.desc with
| Tvariant row when not (static_row row) ->
row_more row
| Tobject (ty, _) ->
let rec proxy_obj ty =
match ty.desc with
Tfield (_, _, _, ty) | Tlink ty -> proxy_obj ty
| Tvar _ | Tunivar _ | Tconstr _ -> ty
| Tnil -> ty0
| _ -> assert false
in proxy_obj ty
| _ -> ty0
(**** Utilities for fixed row private types ****)
let has_constr_row t =
match (repr t).desc with
Tobject(t,_) ->
let rec check_row t =
match (repr t).desc with
Tfield(_,_,_,t) -> check_row t
| Tconstr _ -> true
| _ -> false
in check_row t
| Tvariant row ->
(match row_more row with {desc=Tconstr _} -> true | _ -> false)
| _ ->
false
let is_row_name s =
let l = String.length s in
if l < 4 then false else String.sub s (l-4) 4 = "#row"
let is_constr_row t =
match t.desc with
Tconstr (Path.Pident id, _, _) -> is_row_name (Ident.name id)
| Tconstr (Path.Pdot (_, s, _), _, _) -> is_row_name s
| _ -> false
(**********************************)
Utilities for type traversal
(**********************************)
let rec iter_row f row =
List.iter
(fun (_, fi) ->
match row_field_repr fi with
| Rpresent(Some ty) -> f ty
| Reither(_, tl, _, _) -> List.iter f tl
| _ -> ())
row.row_fields;
match (repr row.row_more).desc with
Tvariant row -> iter_row f row
| Tvar _ | Tunivar _ | Tsubst _ | Tconstr _ | Tnil ->
Misc.may (fun (_,l) -> List.iter f l) row.row_name
| _ -> assert false
let iter_type_expr f ty =
match ty.desc with
Tvar _ -> ()
| Tarrow (_, ty1, ty2, _) -> f ty1; f ty2
| Ttuple l -> List.iter f l
| Tconstr (_, l, _) -> List.iter f l
| Tobject(ty, {contents = Some (_, p)})
-> f ty; List.iter f p
| Tobject (ty, _) -> f ty
| Tvariant row -> iter_row f row; f (row_more row)
| Tfield (_, _, ty1, ty2) -> f ty1; f ty2
| Tnil -> ()
| Tlink ty -> f ty
| Tsubst ty -> f ty
| Tunivar _ -> ()
| Tpoly (ty, tyl) -> f ty; List.iter f tyl
| Tpackage (_, _, l) -> List.iter f l
let rec iter_abbrev f = function
Mnil -> ()
| Mcons(_, _, ty, ty', rem) -> f ty; f ty'; iter_abbrev f rem
| Mlink rem -> iter_abbrev f !rem
type type_iterators =
{ it_signature: type_iterators -> signature -> unit;
it_signature_item: type_iterators -> signature_item -> unit;
it_value_description: type_iterators -> value_description -> unit;
it_type_declaration: type_iterators -> type_declaration -> unit;
it_extension_constructor: type_iterators -> extension_constructor -> unit;
it_module_declaration: type_iterators -> module_declaration -> unit;
it_modtype_declaration: type_iterators -> modtype_declaration -> unit;
it_class_declaration: type_iterators -> class_declaration -> unit;
it_class_type_declaration: type_iterators -> class_type_declaration -> unit;
it_module_type: type_iterators -> module_type -> unit;
it_class_type: type_iterators -> class_type -> unit;
it_type_kind: type_iterators -> type_kind -> unit;
it_do_type_expr: type_iterators -> type_expr -> unit;
it_type_expr: type_iterators -> type_expr -> unit;
it_path: Path.t -> unit; }
let iter_type_expr_cstr_args f = function
| Cstr_tuple tl -> List.iter f tl
| Cstr_record lbls -> List.iter (fun d -> f d.ld_type) lbls
let map_type_expr_cstr_args f = function
| Cstr_tuple tl -> Cstr_tuple (List.map f tl)
| Cstr_record lbls ->
Cstr_record (List.map (fun d -> {d with ld_type=f d.ld_type}) lbls)
let iter_type_expr_kind f = function
| Type_abstract -> ()
| Type_variant cstrs ->
List.iter
(fun cd ->
iter_type_expr_cstr_args f cd.cd_args;
Misc.may f cd.cd_res
)
cstrs
| Type_record(lbls, _) ->
List.iter (fun d -> f d.ld_type) lbls
| Type_open ->
()
let type_iterators =
let it_signature it =
List.iter (it.it_signature_item it)
and it_signature_item it = function
Sig_value (_, vd) -> it.it_value_description it vd
| Sig_type (_, td, _) -> it.it_type_declaration it td
| Sig_typext (_, td, _) -> it.it_extension_constructor it td
| Sig_module (_, md, _) -> it.it_module_declaration it md
| Sig_modtype (_, mtd) -> it.it_modtype_declaration it mtd
| Sig_class (_, cd, _) -> it.it_class_declaration it cd
| Sig_class_type (_, ctd, _) -> it.it_class_type_declaration it ctd
and it_value_description it vd =
it.it_type_expr it vd.val_type
and it_type_declaration it td =
List.iter (it.it_type_expr it) td.type_params;
may (it.it_type_expr it) td.type_manifest;
it.it_type_kind it td.type_kind
and it_extension_constructor it td =
it.it_path td.ext_type_path;
List.iter (it.it_type_expr it) td.ext_type_params;
iter_type_expr_cstr_args (it.it_type_expr it) td.ext_args;
may (it.it_type_expr it) td.ext_ret_type
and it_module_declaration it md =
it.it_module_type it md.md_type
and it_modtype_declaration it mtd =
may (it.it_module_type it) mtd.mtd_type
and it_class_declaration it cd =
List.iter (it.it_type_expr it) cd.cty_params;
it.it_class_type it cd.cty_type;
may (it.it_type_expr it) cd.cty_new;
it.it_path cd.cty_path
and it_class_type_declaration it ctd =
List.iter (it.it_type_expr it) ctd.clty_params;
it.it_class_type it ctd.clty_type;
it.it_path ctd.clty_path
and it_module_type it = function
Mty_ident p
| Mty_alias(_, p) -> it.it_path p
| Mty_signature sg -> it.it_signature it sg
| Mty_functor (_, mto, mt) ->
may (it.it_module_type it) mto;
it.it_module_type it mt
and it_class_type it = function
Cty_constr (p, tyl, cty) ->
it.it_path p;
List.iter (it.it_type_expr it) tyl;
it.it_class_type it cty
| Cty_signature cs ->
it.it_type_expr it cs.csig_self;
Vars.iter (fun _ (_,_,ty) -> it.it_type_expr it ty) cs.csig_vars;
List.iter
(fun (p, tl) -> it.it_path p; List.iter (it.it_type_expr it) tl)
cs.csig_inher
| Cty_arrow (_, ty, cty) ->
it.it_type_expr it ty;
it.it_class_type it cty
and it_type_kind it kind =
iter_type_expr_kind (it.it_type_expr it) kind
and it_do_type_expr it ty =
iter_type_expr (it.it_type_expr it) ty;
match ty.desc with
Tconstr (p, _, _)
| Tobject (_, {contents=Some (p, _)})
| Tpackage (p, _, _) ->
it.it_path p
| Tvariant row ->
may (fun (p,_) -> it.it_path p) (row_repr row).row_name
| _ -> ()
and it_path _p = ()
in
{ it_path; it_type_expr = it_do_type_expr; it_do_type_expr;
it_type_kind; it_class_type; it_module_type;
it_signature; it_class_type_declaration; it_class_declaration;
it_modtype_declaration; it_module_declaration; it_extension_constructor;
it_type_declaration; it_value_description; it_signature_item; }
let copy_row f fixed row keep more =
let fields = List.map
(fun (l, fi) -> l,
match row_field_repr fi with
| Rpresent(Some ty) -> Rpresent(Some(f ty))
| Reither(c, tl, m, e) ->
let e = if keep then e else ref None in
let m = if row.row_fixed then fixed else m in
let tl = List.map f tl in
Reither(c, tl, m, e)
| _ -> fi)
row.row_fields in
let name =
match row.row_name with None -> None
| Some (path, tl) -> Some (path, List.map f tl) in
{ row_fields = fields; row_more = more;
row_bound = (); row_fixed = row.row_fixed && fixed;
row_closed = row.row_closed; row_name = name; }
let rec copy_kind = function
Fvar{contents = Some k} -> copy_kind k
| Fvar _ -> Fvar (ref None)
| Fpresent -> Fpresent
| Fabsent -> assert false
let copy_commu c =
if commu_repr c = Cok then Cok else Clink (ref Cunknown)
(* Since univars may be used as row variables, we need to do some
encoding during substitution *)
let rec norm_univar ty =
match ty.desc with
Tunivar _ | Tsubst _ -> ty
| Tlink ty -> norm_univar ty
| Ttuple (ty :: _) -> norm_univar ty
| _ -> assert false
let rec copy_type_desc ?(keep_names=false) f = function
Tvar _ as ty -> if keep_names then ty else Tvar None
| Tarrow (p, ty1, ty2, c)-> Tarrow (p, f ty1, f ty2, copy_commu c)
| Ttuple l -> Ttuple (List.map f l)
| Tconstr (p, l, _) -> Tconstr (p, List.map f l, ref Mnil)
| Tobject(ty, {contents = Some (p, tl)})
-> Tobject (f ty, ref (Some(p, List.map f tl)))
| Tobject (ty, _) -> Tobject (f ty, ref None)
| Tvariant _ -> assert false (* too ambiguous *)
| Tfield (p, k, ty1, ty2) -> (* the kind is kept shared *)
Tfield (p, field_kind_repr k, f ty1, f ty2)
| Tnil -> Tnil
| Tlink ty -> copy_type_desc f ty.desc
| Tsubst _ -> assert false
| Tunivar _ as ty -> ty (* always keep the name *)
| Tpoly (ty, tyl) ->
let tyl = List.map (fun x -> norm_univar (f x)) tyl in
Tpoly (f ty, tyl)
| Tpackage (p, n, l) -> Tpackage (p, n, List.map f l)
Utilities for copying
let saved_desc = ref []
(* Saved association of generic nodes with their description. *)
let save_desc ty desc =
saved_desc := (ty, desc)::!saved_desc
let saved_kinds = ref [] (* duplicated kind variables *)
let new_kinds = ref [] (* new kind variables *)
let dup_kind r =
(match !r with None -> () | Some _ -> assert false);
if not (List.memq r !new_kinds) then begin
saved_kinds := r :: !saved_kinds;
let r' = ref None in
new_kinds := r' :: !new_kinds;
r := Some (Fvar r')
end
(* Restored type descriptions. *)
let cleanup_types () =
List.iter (fun (ty, desc) -> ty.desc <- desc) !saved_desc;
List.iter (fun r -> r := None) !saved_kinds;
saved_desc := []; saved_kinds := []; new_kinds := []
(* Mark a type. *)
let rec mark_type ty =
let ty = repr ty in
if ty.level >= lowest_level then begin
ty.level <- pivot_level - ty.level;
iter_type_expr mark_type ty
end
let mark_type_node ty =
let ty = repr ty in
if ty.level >= lowest_level then begin
ty.level <- pivot_level - ty.level;
end
let mark_type_params ty =
iter_type_expr mark_type ty
let type_iterators =
let it_type_expr it ty =
let ty = repr ty in
if ty.level >= lowest_level then begin
mark_type_node ty;
it.it_do_type_expr it ty;
end
in
{type_iterators with it_type_expr}
(* Remove marks from a type. *)
let rec unmark_type ty =
let ty = repr ty in
if ty.level < lowest_level then begin
ty.level <- pivot_level - ty.level;
iter_type_expr unmark_type ty
end
let unmark_iterators =
let it_type_expr _it ty = unmark_type ty in
{type_iterators with it_type_expr}
let unmark_type_decl decl =
unmark_iterators.it_type_declaration unmark_iterators decl
let unmark_extension_constructor ext =
List.iter unmark_type ext.ext_type_params;
iter_type_expr_cstr_args unmark_type ext.ext_args;
Misc.may unmark_type ext.ext_ret_type
let unmark_class_signature sign =
unmark_type sign.csig_self;
Vars.iter (fun _l (_m, _v, t) -> unmark_type t) sign.csig_vars
let unmark_class_type cty =
unmark_iterators.it_class_type unmark_iterators cty
(*******************************************)
(* Memorization of abbreviation expansion *)
(*******************************************)
(* Search whether the expansion has been memorized. *)
let lte_public p1 p2 = (* Private <= Public *)
match p1, p2 with
| Private, _ | _, Public -> true
| Public, Private -> false
let rec find_expans priv p1 = function
Mnil -> None
| Mcons (priv', p2, _ty0, ty, _)
when lte_public priv priv' && Path.same p1 p2 -> Some ty
| Mcons (_, _, _, _, rem) -> find_expans priv p1 rem
| Mlink {contents = rem} -> find_expans priv p1 rem
debug : check for cycles in abbreviation . only works with -principal
let rec check_expans visited ty =
let ty = repr ty in
assert ( not ( visited ) ) ;
match ty.desc with
Tconstr ( path , args , abbrev ) - >
begin match find_expans path ! abbrev with
Some ty ' - > check_expans ( ty : : visited ) ty '
| None - > ( )
end
| _ - > ( )
let rec check_expans visited ty =
let ty = repr ty in
assert (not (List.memq ty visited));
match ty.desc with
Tconstr (path, args, abbrev) ->
begin match find_expans path !abbrev with
Some ty' -> check_expans (ty :: visited) ty'
| None -> ()
end
| _ -> ()
*)
let memo = ref []
(* Contains the list of saved abbreviation expansions. *)
let cleanup_abbrev () =
(* Remove all memorized abbreviation expansions. *)
List.iter (fun abbr -> abbr := Mnil) !memo;
memo := []
let memorize_abbrev mem priv path v v' =
(* Memorize the expansion of an abbreviation. *)
mem := Mcons (priv, path, v, v', !mem);
check_expans [ ] v ;
memo := mem :: !memo
let rec forget_abbrev_rec mem path =
match mem with
Mnil ->
assert false
| Mcons (_, path', _, _, rem) when Path.same path path' ->
rem
| Mcons (priv, path', v, v', rem) ->
Mcons (priv, path', v, v', forget_abbrev_rec rem path)
| Mlink mem' ->
mem' := forget_abbrev_rec !mem' path;
raise Exit
let forget_abbrev mem path =
try mem := forget_abbrev_rec !mem path with Exit -> ()
debug : check for invalid abbreviations
let rec check_abbrev_rec = function
Mnil - > true
| Mcons ( _ , , ty2 , rem ) - >
repr ! = repr ty2
| Mlink mem ' - >
check_abbrev_rec ! '
let ( ) =
List.for_all ( fun mem - > check_abbrev_rec ! ) ! memo
let rec check_abbrev_rec = function
Mnil -> true
| Mcons (_, ty1, ty2, rem) ->
repr ty1 != repr ty2
| Mlink mem' ->
check_abbrev_rec !mem'
let check_memorized_abbrevs () =
List.for_all (fun mem -> check_abbrev_rec !mem) !memo
*)
(**********************************)
Utilities for labels
(**********************************)
let is_optional = function Optional _ -> true | _ -> false
let label_name = function
Nolabel -> ""
| Labelled s
| Optional s -> s
let prefixed_label_name = function
Nolabel -> ""
| Labelled s -> "~" ^ s
| Optional s -> "?" ^ s
let rec extract_label_aux hd l = function
[] -> raise Not_found
| (l',t as p) :: ls ->
if label_name l' = l then (l', t, List.rev hd, ls)
else extract_label_aux (p::hd) l ls
let extract_label l ls = extract_label_aux [] l ls
(**********************************)
Utilities for backtracking
(**********************************)
let undo_change = function
Ctype (ty, desc) -> ty.desc <- desc
| Ccompress (ty, desc, _) -> ty.desc <- desc
| Clevel (ty, level) -> ty.level <- level
| Cname (r, v) -> r := v
| Crow (r, v) -> r := v
| Ckind (r, v) -> r := v
| Ccommu (r, v) -> r := v
| Cuniv (r, v) -> r := v
| Ctypeset (r, v) -> r := v
type snapshot = changes ref * int
let last_snapshot = ref 0
let log_type ty =
if ty.id <= !last_snapshot then log_change (Ctype (ty, ty.desc))
let link_type ty ty' =
log_type ty;
let desc = ty.desc in
ty.desc <- Tlink ty';
(* Name is a user-supplied name for this unification variable (obtained
* through a type annotation for instance). *)
match desc, ty'.desc with
Tvar name, Tvar name' ->
begin match name, name' with
| Some _, None -> log_type ty'; ty'.desc <- Tvar name
| None, Some _ -> ()
| Some _, Some _ ->
if ty.level < ty'.level then (log_type ty'; ty'.desc <- Tvar name)
| None, None -> ()
end
| _ -> ()
; assert ( ( ) )
; check_expans [ ] ty '
let set_level ty level =
if ty.id <= !last_snapshot then log_change (Clevel (ty, ty.level));
ty.level <- level
let set_univar rty ty =
log_change (Cuniv (rty, !rty)); rty := Some ty
let set_name nm v =
log_change (Cname (nm, !nm)); nm := v
let set_row_field e v =
log_change (Crow (e, !e)); e := Some v
let set_kind rk k =
log_change (Ckind (rk, !rk)); rk := Some k
let set_commu rc c =
log_change (Ccommu (rc, !rc)); rc := c
let set_typeset rs s =
log_change (Ctypeset (rs, !rs)); rs := s
let snapshot () =
let old = !last_snapshot in
last_snapshot := !new_id;
match Weak.get trail 0 with Some r -> (r, old)
| None ->
let r = ref Unchanged in
Weak.set trail 0 (Some r);
(r, old)
let rec rev_log accu = function
Unchanged -> accu
| Invalid -> assert false
| Change (ch, next) ->
let d = !next in
next := Invalid;
rev_log (ch::accu) d
let backtrack (changes, old) =
match !changes with
Unchanged -> last_snapshot := old
| Invalid -> failwith "Btype.backtrack"
| Change _ as change ->
cleanup_abbrev ();
let backlog = rev_log [] change in
List.iter undo_change backlog;
changes := Unchanged;
last_snapshot := old;
Weak.set trail 0 (Some changes)
let rec rev_compress_log log r =
match !r with
Unchanged | Invalid ->
log
| Change (Ccompress _, next) ->
rev_compress_log (r::log) next
| Change (_, next) ->
rev_compress_log log next
let undo_compress (changes, _old) =
match !changes with
Unchanged
| Invalid -> ()
| Change _ ->
let log = rev_compress_log [] changes in
List.iter
(fun r -> match !r with
Change (Ccompress (ty, desc, d), next) when ty.desc == d ->
ty.desc <- desc; r := !next
| _ -> ())
log
| null | https://raw.githubusercontent.com/yurug/ocaml4.04.0-copatterns/b3ec6a3cc203bd2cde3b618546d29e10f1102323/typing/btype.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Basic operations on core types
*** Sets, maps and hashtables of types ***
*** Forward declarations ***
*** Type level management ***
Used to mark a type during a traversal.
pivot_level - lowest_level < lowest_level
*** Some type creators ***
*** Check some types ***
*** Definitions for backtracking ***
*** Representative of a type ***
*** Utilities for fixed row private types ***
********************************
********************************
Since univars may be used as row variables, we need to do some
encoding during substitution
too ambiguous
the kind is kept shared
always keep the name
Saved association of generic nodes with their description.
duplicated kind variables
new kind variables
Restored type descriptions.
Mark a type.
Remove marks from a type.
*****************************************
Memorization of abbreviation expansion
*****************************************
Search whether the expansion has been memorized.
Private <= Public
Contains the list of saved abbreviation expansions.
Remove all memorized abbreviation expansions.
Memorize the expansion of an abbreviation.
********************************
********************************
********************************
********************************
Name is a user-supplied name for this unification variable (obtained
* through a type annotation for instance). | and , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Misc
open Asttypes
open Types
module TypeSet = Set.Make(TypeOps)
module TypeMap = Map.Make (TypeOps)
module TypeHash = Hashtbl.Make(TypeOps)
let print_raw =
ref (fun _ -> assert false : Format.formatter -> type_expr -> unit)
let generic_level = 100000000
let lowest_level = 0
let pivot_level = 2 * lowest_level - 1
let new_id = ref (-1)
let newty2 level desc =
incr new_id; { desc; level; id = !new_id }
let newgenty desc = newty2 generic_level desc
let newgenvar ?name () = newgenty (Tvar name)
let newmarkedvar level =
incr new_id ; { desc = Tvar ; level = pivot_level - level ; i d = ! new_id }
let ( ) =
incr new_id ;
{ desc = Tvar ; level = pivot_level - generic_level ; i d = ! new_id }
let newmarkedvar level =
incr new_id; { desc = Tvar; level = pivot_level - level; id = !new_id }
let newmarkedgenvar () =
incr new_id;
{ desc = Tvar; level = pivot_level - generic_level; id = !new_id }
*)
let is_Tvar = function {desc=Tvar _} -> true | _ -> false
let is_Tunivar = function {desc=Tunivar _} -> true | _ -> false
let dummy_method = "*dummy method*"
let default_mty = function
Some mty -> mty
| None -> Mty_signature []
type change =
Ctype of type_expr * type_desc
| Ccompress of type_expr * type_desc * type_desc
| Clevel of type_expr * int
| Cname of
(Path.t * type_expr list) option ref * (Path.t * type_expr list) option
| Crow of row_field option ref * row_field option
| Ckind of field_kind option ref * field_kind option
| Ccommu of commutable ref * commutable
| Cuniv of type_expr option ref * type_expr option
| Ctypeset of TypeSet.t ref * TypeSet.t
type changes =
Change of change * changes ref
| Unchanged
| Invalid
let trail = Weak.create 1
let log_change ch =
match Weak.get trail 0 with None -> ()
| Some r ->
let r' = ref Unchanged in
r := Change (ch, r');
Weak.set trail 0 (Some r')
let rec field_kind_repr =
function
Fvar {contents = Some kind} -> field_kind_repr kind
| kind -> kind
let rec repr_link compress t d =
function
{desc = Tlink t' as d'} ->
repr_link true t d' t'
| {desc = Tfield (_, k, _, t') as d'} when field_kind_repr k = Fabsent ->
repr_link true t d' t'
| t' ->
if compress then begin
log_change (Ccompress (t, t.desc, d)); t.desc <- d
end;
t'
let repr t =
match t.desc with
Tlink t' as d ->
repr_link false t d t'
| Tfield (_, k, _, t') as d when field_kind_repr k = Fabsent ->
repr_link false t d t'
| _ -> t
let rec commu_repr = function
Clink r when !r <> Cunknown -> commu_repr !r
| c -> c
let rec row_field_repr_aux tl = function
Reither(_, tl', _, {contents = Some fi}) ->
row_field_repr_aux (tl@tl') fi
| Reither(c, tl', m, r) ->
Reither(c, tl@tl', m, r)
| Rpresent (Some _) when tl <> [] ->
Rpresent (Some (List.hd tl))
| fi -> fi
let row_field_repr fi = row_field_repr_aux [] fi
let rec rev_concat l ll =
match ll with
[] -> l
| l'::ll -> rev_concat (l'@l) ll
let rec row_repr_aux ll row =
match (repr row.row_more).desc with
| Tvariant row' ->
let f = row.row_fields in
row_repr_aux (if f = [] then ll else f::ll) row'
| _ ->
if ll = [] then row else
{row with row_fields = rev_concat row.row_fields ll}
let row_repr row = row_repr_aux [] row
let rec row_field tag row =
let rec find = function
| (tag',f) :: fields ->
if tag = tag' then row_field_repr f else find fields
| [] ->
match repr row.row_more with
| {desc=Tvariant row'} -> row_field tag row'
| _ -> Rabsent
in find row.row_fields
let rec row_more row =
match repr row.row_more with
| {desc=Tvariant row'} -> row_more row'
| ty -> ty
let row_fixed row =
let row = row_repr row in
row.row_fixed ||
match (repr row.row_more).desc with
Tvar _ | Tnil -> false
| Tunivar _ | Tconstr _ -> true
| _ -> assert false
let static_row row =
let row = row_repr row in
row.row_closed &&
List.for_all
(fun (_,f) -> match row_field_repr f with Reither _ -> false | _ -> true)
row.row_fields
let hash_variant s =
let accu = ref 0 in
for i = 0 to String.length s - 1 do
accu := 223 * !accu + Char.code s.[i]
done;
reduce to 31 bits
accu := !accu land (1 lsl 31 - 1);
make it signed for 64 bits architectures
if !accu > 0x3FFFFFFF then !accu - (1 lsl 31) else !accu
let proxy ty =
let ty0 = repr ty in
match ty0.desc with
| Tvariant row when not (static_row row) ->
row_more row
| Tobject (ty, _) ->
let rec proxy_obj ty =
match ty.desc with
Tfield (_, _, _, ty) | Tlink ty -> proxy_obj ty
| Tvar _ | Tunivar _ | Tconstr _ -> ty
| Tnil -> ty0
| _ -> assert false
in proxy_obj ty
| _ -> ty0
let has_constr_row t =
match (repr t).desc with
Tobject(t,_) ->
let rec check_row t =
match (repr t).desc with
Tfield(_,_,_,t) -> check_row t
| Tconstr _ -> true
| _ -> false
in check_row t
| Tvariant row ->
(match row_more row with {desc=Tconstr _} -> true | _ -> false)
| _ ->
false
let is_row_name s =
let l = String.length s in
if l < 4 then false else String.sub s (l-4) 4 = "#row"
let is_constr_row t =
match t.desc with
Tconstr (Path.Pident id, _, _) -> is_row_name (Ident.name id)
| Tconstr (Path.Pdot (_, s, _), _, _) -> is_row_name s
| _ -> false
Utilities for type traversal
let rec iter_row f row =
List.iter
(fun (_, fi) ->
match row_field_repr fi with
| Rpresent(Some ty) -> f ty
| Reither(_, tl, _, _) -> List.iter f tl
| _ -> ())
row.row_fields;
match (repr row.row_more).desc with
Tvariant row -> iter_row f row
| Tvar _ | Tunivar _ | Tsubst _ | Tconstr _ | Tnil ->
Misc.may (fun (_,l) -> List.iter f l) row.row_name
| _ -> assert false
let iter_type_expr f ty =
match ty.desc with
Tvar _ -> ()
| Tarrow (_, ty1, ty2, _) -> f ty1; f ty2
| Ttuple l -> List.iter f l
| Tconstr (_, l, _) -> List.iter f l
| Tobject(ty, {contents = Some (_, p)})
-> f ty; List.iter f p
| Tobject (ty, _) -> f ty
| Tvariant row -> iter_row f row; f (row_more row)
| Tfield (_, _, ty1, ty2) -> f ty1; f ty2
| Tnil -> ()
| Tlink ty -> f ty
| Tsubst ty -> f ty
| Tunivar _ -> ()
| Tpoly (ty, tyl) -> f ty; List.iter f tyl
| Tpackage (_, _, l) -> List.iter f l
let rec iter_abbrev f = function
Mnil -> ()
| Mcons(_, _, ty, ty', rem) -> f ty; f ty'; iter_abbrev f rem
| Mlink rem -> iter_abbrev f !rem
type type_iterators =
{ it_signature: type_iterators -> signature -> unit;
it_signature_item: type_iterators -> signature_item -> unit;
it_value_description: type_iterators -> value_description -> unit;
it_type_declaration: type_iterators -> type_declaration -> unit;
it_extension_constructor: type_iterators -> extension_constructor -> unit;
it_module_declaration: type_iterators -> module_declaration -> unit;
it_modtype_declaration: type_iterators -> modtype_declaration -> unit;
it_class_declaration: type_iterators -> class_declaration -> unit;
it_class_type_declaration: type_iterators -> class_type_declaration -> unit;
it_module_type: type_iterators -> module_type -> unit;
it_class_type: type_iterators -> class_type -> unit;
it_type_kind: type_iterators -> type_kind -> unit;
it_do_type_expr: type_iterators -> type_expr -> unit;
it_type_expr: type_iterators -> type_expr -> unit;
it_path: Path.t -> unit; }
let iter_type_expr_cstr_args f = function
| Cstr_tuple tl -> List.iter f tl
| Cstr_record lbls -> List.iter (fun d -> f d.ld_type) lbls
let map_type_expr_cstr_args f = function
| Cstr_tuple tl -> Cstr_tuple (List.map f tl)
| Cstr_record lbls ->
Cstr_record (List.map (fun d -> {d with ld_type=f d.ld_type}) lbls)
let iter_type_expr_kind f = function
| Type_abstract -> ()
| Type_variant cstrs ->
List.iter
(fun cd ->
iter_type_expr_cstr_args f cd.cd_args;
Misc.may f cd.cd_res
)
cstrs
| Type_record(lbls, _) ->
List.iter (fun d -> f d.ld_type) lbls
| Type_open ->
()
let type_iterators =
let it_signature it =
List.iter (it.it_signature_item it)
and it_signature_item it = function
Sig_value (_, vd) -> it.it_value_description it vd
| Sig_type (_, td, _) -> it.it_type_declaration it td
| Sig_typext (_, td, _) -> it.it_extension_constructor it td
| Sig_module (_, md, _) -> it.it_module_declaration it md
| Sig_modtype (_, mtd) -> it.it_modtype_declaration it mtd
| Sig_class (_, cd, _) -> it.it_class_declaration it cd
| Sig_class_type (_, ctd, _) -> it.it_class_type_declaration it ctd
and it_value_description it vd =
it.it_type_expr it vd.val_type
and it_type_declaration it td =
List.iter (it.it_type_expr it) td.type_params;
may (it.it_type_expr it) td.type_manifest;
it.it_type_kind it td.type_kind
and it_extension_constructor it td =
it.it_path td.ext_type_path;
List.iter (it.it_type_expr it) td.ext_type_params;
iter_type_expr_cstr_args (it.it_type_expr it) td.ext_args;
may (it.it_type_expr it) td.ext_ret_type
and it_module_declaration it md =
it.it_module_type it md.md_type
and it_modtype_declaration it mtd =
may (it.it_module_type it) mtd.mtd_type
and it_class_declaration it cd =
List.iter (it.it_type_expr it) cd.cty_params;
it.it_class_type it cd.cty_type;
may (it.it_type_expr it) cd.cty_new;
it.it_path cd.cty_path
and it_class_type_declaration it ctd =
List.iter (it.it_type_expr it) ctd.clty_params;
it.it_class_type it ctd.clty_type;
it.it_path ctd.clty_path
and it_module_type it = function
Mty_ident p
| Mty_alias(_, p) -> it.it_path p
| Mty_signature sg -> it.it_signature it sg
| Mty_functor (_, mto, mt) ->
may (it.it_module_type it) mto;
it.it_module_type it mt
and it_class_type it = function
Cty_constr (p, tyl, cty) ->
it.it_path p;
List.iter (it.it_type_expr it) tyl;
it.it_class_type it cty
| Cty_signature cs ->
it.it_type_expr it cs.csig_self;
Vars.iter (fun _ (_,_,ty) -> it.it_type_expr it ty) cs.csig_vars;
List.iter
(fun (p, tl) -> it.it_path p; List.iter (it.it_type_expr it) tl)
cs.csig_inher
| Cty_arrow (_, ty, cty) ->
it.it_type_expr it ty;
it.it_class_type it cty
and it_type_kind it kind =
iter_type_expr_kind (it.it_type_expr it) kind
and it_do_type_expr it ty =
iter_type_expr (it.it_type_expr it) ty;
match ty.desc with
Tconstr (p, _, _)
| Tobject (_, {contents=Some (p, _)})
| Tpackage (p, _, _) ->
it.it_path p
| Tvariant row ->
may (fun (p,_) -> it.it_path p) (row_repr row).row_name
| _ -> ()
and it_path _p = ()
in
{ it_path; it_type_expr = it_do_type_expr; it_do_type_expr;
it_type_kind; it_class_type; it_module_type;
it_signature; it_class_type_declaration; it_class_declaration;
it_modtype_declaration; it_module_declaration; it_extension_constructor;
it_type_declaration; it_value_description; it_signature_item; }
let copy_row f fixed row keep more =
let fields = List.map
(fun (l, fi) -> l,
match row_field_repr fi with
| Rpresent(Some ty) -> Rpresent(Some(f ty))
| Reither(c, tl, m, e) ->
let e = if keep then e else ref None in
let m = if row.row_fixed then fixed else m in
let tl = List.map f tl in
Reither(c, tl, m, e)
| _ -> fi)
row.row_fields in
let name =
match row.row_name with None -> None
| Some (path, tl) -> Some (path, List.map f tl) in
{ row_fields = fields; row_more = more;
row_bound = (); row_fixed = row.row_fixed && fixed;
row_closed = row.row_closed; row_name = name; }
let rec copy_kind = function
Fvar{contents = Some k} -> copy_kind k
| Fvar _ -> Fvar (ref None)
| Fpresent -> Fpresent
| Fabsent -> assert false
let copy_commu c =
if commu_repr c = Cok then Cok else Clink (ref Cunknown)
let rec norm_univar ty =
match ty.desc with
Tunivar _ | Tsubst _ -> ty
| Tlink ty -> norm_univar ty
| Ttuple (ty :: _) -> norm_univar ty
| _ -> assert false
let rec copy_type_desc ?(keep_names=false) f = function
Tvar _ as ty -> if keep_names then ty else Tvar None
| Tarrow (p, ty1, ty2, c)-> Tarrow (p, f ty1, f ty2, copy_commu c)
| Ttuple l -> Ttuple (List.map f l)
| Tconstr (p, l, _) -> Tconstr (p, List.map f l, ref Mnil)
| Tobject(ty, {contents = Some (p, tl)})
-> Tobject (f ty, ref (Some(p, List.map f tl)))
| Tobject (ty, _) -> Tobject (f ty, ref None)
Tfield (p, field_kind_repr k, f ty1, f ty2)
| Tnil -> Tnil
| Tlink ty -> copy_type_desc f ty.desc
| Tsubst _ -> assert false
| Tpoly (ty, tyl) ->
let tyl = List.map (fun x -> norm_univar (f x)) tyl in
Tpoly (f ty, tyl)
| Tpackage (p, n, l) -> Tpackage (p, n, List.map f l)
Utilities for copying
let saved_desc = ref []
let save_desc ty desc =
saved_desc := (ty, desc)::!saved_desc
let dup_kind r =
(match !r with None -> () | Some _ -> assert false);
if not (List.memq r !new_kinds) then begin
saved_kinds := r :: !saved_kinds;
let r' = ref None in
new_kinds := r' :: !new_kinds;
r := Some (Fvar r')
end
let cleanup_types () =
List.iter (fun (ty, desc) -> ty.desc <- desc) !saved_desc;
List.iter (fun r -> r := None) !saved_kinds;
saved_desc := []; saved_kinds := []; new_kinds := []
let rec mark_type ty =
let ty = repr ty in
if ty.level >= lowest_level then begin
ty.level <- pivot_level - ty.level;
iter_type_expr mark_type ty
end
let mark_type_node ty =
let ty = repr ty in
if ty.level >= lowest_level then begin
ty.level <- pivot_level - ty.level;
end
let mark_type_params ty =
iter_type_expr mark_type ty
let type_iterators =
let it_type_expr it ty =
let ty = repr ty in
if ty.level >= lowest_level then begin
mark_type_node ty;
it.it_do_type_expr it ty;
end
in
{type_iterators with it_type_expr}
let rec unmark_type ty =
let ty = repr ty in
if ty.level < lowest_level then begin
ty.level <- pivot_level - ty.level;
iter_type_expr unmark_type ty
end
let unmark_iterators =
let it_type_expr _it ty = unmark_type ty in
{type_iterators with it_type_expr}
let unmark_type_decl decl =
unmark_iterators.it_type_declaration unmark_iterators decl
let unmark_extension_constructor ext =
List.iter unmark_type ext.ext_type_params;
iter_type_expr_cstr_args unmark_type ext.ext_args;
Misc.may unmark_type ext.ext_ret_type
let unmark_class_signature sign =
unmark_type sign.csig_self;
Vars.iter (fun _l (_m, _v, t) -> unmark_type t) sign.csig_vars
let unmark_class_type cty =
unmark_iterators.it_class_type unmark_iterators cty
match p1, p2 with
| Private, _ | _, Public -> true
| Public, Private -> false
let rec find_expans priv p1 = function
Mnil -> None
| Mcons (priv', p2, _ty0, ty, _)
when lte_public priv priv' && Path.same p1 p2 -> Some ty
| Mcons (_, _, _, _, rem) -> find_expans priv p1 rem
| Mlink {contents = rem} -> find_expans priv p1 rem
debug : check for cycles in abbreviation . only works with -principal
let rec check_expans visited ty =
let ty = repr ty in
assert ( not ( visited ) ) ;
match ty.desc with
Tconstr ( path , args , abbrev ) - >
begin match find_expans path ! abbrev with
Some ty ' - > check_expans ( ty : : visited ) ty '
| None - > ( )
end
| _ - > ( )
let rec check_expans visited ty =
let ty = repr ty in
assert (not (List.memq ty visited));
match ty.desc with
Tconstr (path, args, abbrev) ->
begin match find_expans path !abbrev with
Some ty' -> check_expans (ty :: visited) ty'
| None -> ()
end
| _ -> ()
*)
let memo = ref []
let cleanup_abbrev () =
List.iter (fun abbr -> abbr := Mnil) !memo;
memo := []
let memorize_abbrev mem priv path v v' =
mem := Mcons (priv, path, v, v', !mem);
check_expans [ ] v ;
memo := mem :: !memo
let rec forget_abbrev_rec mem path =
match mem with
Mnil ->
assert false
| Mcons (_, path', _, _, rem) when Path.same path path' ->
rem
| Mcons (priv, path', v, v', rem) ->
Mcons (priv, path', v, v', forget_abbrev_rec rem path)
| Mlink mem' ->
mem' := forget_abbrev_rec !mem' path;
raise Exit
let forget_abbrev mem path =
try mem := forget_abbrev_rec !mem path with Exit -> ()
debug : check for invalid abbreviations
let rec check_abbrev_rec = function
Mnil - > true
| Mcons ( _ , , ty2 , rem ) - >
repr ! = repr ty2
| Mlink mem ' - >
check_abbrev_rec ! '
let ( ) =
List.for_all ( fun mem - > check_abbrev_rec ! ) ! memo
let rec check_abbrev_rec = function
Mnil -> true
| Mcons (_, ty1, ty2, rem) ->
repr ty1 != repr ty2
| Mlink mem' ->
check_abbrev_rec !mem'
let check_memorized_abbrevs () =
List.for_all (fun mem -> check_abbrev_rec !mem) !memo
*)
Utilities for labels
let is_optional = function Optional _ -> true | _ -> false
let label_name = function
Nolabel -> ""
| Labelled s
| Optional s -> s
let prefixed_label_name = function
Nolabel -> ""
| Labelled s -> "~" ^ s
| Optional s -> "?" ^ s
let rec extract_label_aux hd l = function
[] -> raise Not_found
| (l',t as p) :: ls ->
if label_name l' = l then (l', t, List.rev hd, ls)
else extract_label_aux (p::hd) l ls
let extract_label l ls = extract_label_aux [] l ls
Utilities for backtracking
let undo_change = function
Ctype (ty, desc) -> ty.desc <- desc
| Ccompress (ty, desc, _) -> ty.desc <- desc
| Clevel (ty, level) -> ty.level <- level
| Cname (r, v) -> r := v
| Crow (r, v) -> r := v
| Ckind (r, v) -> r := v
| Ccommu (r, v) -> r := v
| Cuniv (r, v) -> r := v
| Ctypeset (r, v) -> r := v
type snapshot = changes ref * int
let last_snapshot = ref 0
let log_type ty =
if ty.id <= !last_snapshot then log_change (Ctype (ty, ty.desc))
let link_type ty ty' =
log_type ty;
let desc = ty.desc in
ty.desc <- Tlink ty';
match desc, ty'.desc with
Tvar name, Tvar name' ->
begin match name, name' with
| Some _, None -> log_type ty'; ty'.desc <- Tvar name
| None, Some _ -> ()
| Some _, Some _ ->
if ty.level < ty'.level then (log_type ty'; ty'.desc <- Tvar name)
| None, None -> ()
end
| _ -> ()
; assert ( ( ) )
; check_expans [ ] ty '
let set_level ty level =
if ty.id <= !last_snapshot then log_change (Clevel (ty, ty.level));
ty.level <- level
let set_univar rty ty =
log_change (Cuniv (rty, !rty)); rty := Some ty
let set_name nm v =
log_change (Cname (nm, !nm)); nm := v
let set_row_field e v =
log_change (Crow (e, !e)); e := Some v
let set_kind rk k =
log_change (Ckind (rk, !rk)); rk := Some k
let set_commu rc c =
log_change (Ccommu (rc, !rc)); rc := c
let set_typeset rs s =
log_change (Ctypeset (rs, !rs)); rs := s
let snapshot () =
let old = !last_snapshot in
last_snapshot := !new_id;
match Weak.get trail 0 with Some r -> (r, old)
| None ->
let r = ref Unchanged in
Weak.set trail 0 (Some r);
(r, old)
let rec rev_log accu = function
Unchanged -> accu
| Invalid -> assert false
| Change (ch, next) ->
let d = !next in
next := Invalid;
rev_log (ch::accu) d
let backtrack (changes, old) =
match !changes with
Unchanged -> last_snapshot := old
| Invalid -> failwith "Btype.backtrack"
| Change _ as change ->
cleanup_abbrev ();
let backlog = rev_log [] change in
List.iter undo_change backlog;
changes := Unchanged;
last_snapshot := old;
Weak.set trail 0 (Some changes)
let rec rev_compress_log log r =
match !r with
Unchanged | Invalid ->
log
| Change (Ccompress _, next) ->
rev_compress_log (r::log) next
| Change (_, next) ->
rev_compress_log log next
let undo_compress (changes, _old) =
match !changes with
Unchanged
| Invalid -> ()
| Change _ ->
let log = rev_compress_log [] changes in
List.iter
(fun r -> match !r with
Change (Ccompress (ty, desc, d), next) when ty.desc == d ->
ty.desc <- desc; r := !next
| _ -> ())
log
|
7b0ee3102bd2006e4001ddaad775dcfaf141609f116a8051614a59818a8a1fec | rabbitmq/osiris | osiris_util.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2007 - 2022 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(osiris_util).
-include("osiris.hrl").
-export([validate_base64uri/1,
to_base64uri/1,
id/1,
lists_find/2,
hostname_from_node/0,
get_replication_configuration_from_tls_dist/0,
get_replication_configuration_from_tls_dist/1,
get_replication_configuration_from_tls_dist/2,
partition_parallel/3,
normalise_name/1,
get_reader_context/1,
cache_reader_context/6
]).
%% For testing
-export([inet_tls_enabled/1,
replication_over_tls_configuration/3]).
-define(BASE64_URI_CHARS,
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01"
"23456789_-=").
-spec validate_base64uri(string() | binary()) -> boolean().
validate_base64uri(Str) when ?IS_STRING(Str) ->
catch begin
[begin
case lists:member(C, ?BASE64_URI_CHARS) of
true ->
ok;
false ->
throw(false)
end
end
|| C <- string:to_graphemes(Str)],
string:is_empty(Str) == false
end.
-spec to_base64uri(string() | binary()) -> string().
to_base64uri(Str) when ?IS_STRING(Str) ->
lists:foldr(fun(G, Acc) ->
case lists:member(G, ?BASE64_URI_CHARS) of
true -> [G | Acc];
false -> [$_ | Acc]
end
end,
[], string:to_graphemes(Str)).
-spec id(term()) -> term().
id(X) ->
X.
-spec lists_find(fun((term()) -> boolean()), list()) ->
{ok, term()} | not_found.
lists_find(_Pred, []) ->
not_found;
lists_find(Pred, [Item | Rem]) ->
case Pred(Item) of
true ->
{ok, Item};
false ->
lists_find(Pred, Rem)
end.
hostname_from_node() ->
case re:split(atom_to_list(node()), "@", [{return, list}, {parts, 2}])
of
[_, Hostname] ->
Hostname;
[_] ->
{ok, H} = inet:gethostname(),
H
end.
get_replication_configuration_from_tls_dist() ->
get_replication_configuration_from_tls_dist(fun (debug, Fmt, Args) ->
?DEBUG(Fmt, Args);
(warn, Fmt, Args) ->
?WARN(Fmt, Args);
(warning, Fmt, Args) ->
?WARN(Fmt, Args);
(_, Fmt, Args) ->
?INFO(Fmt, Args)
end).
get_replication_configuration_from_tls_dist(LogFun) ->
get_replication_configuration_from_tls_dist(fun file:consult/1,
LogFun).
get_replication_configuration_from_tls_dist(FileConsultFun, LogFun) ->
InitArguments = init:get_arguments(),
case inet_tls_enabled(InitArguments) of
true ->
LogFun(debug,
"Inter-node TLS enabled, "
++ "configuring stream replication over TLS",
[]),
replication_over_tls_configuration(InitArguments, FileConsultFun, LogFun);
false ->
LogFun(debug, "Inter-node TLS not enabled", []),
[]
end.
replication_over_tls_configuration(InitArgs, FileConsultFun, LogFun) ->
case proplists:lookup(ssl_dist_optfile, InitArgs) of
none ->
LogFun(debug,
"Using ssl_dist_opt to configure "
++ "stream replication over TLS",
[]),
SslDistOpt = proplists:lookup_all(ssl_dist_opt, InitArgs),
[{replication_transport, ssl},
{replication_server_ssl_options,
build_replication_over_tls_options("server_", SslDistOpt, [])},
{replication_client_ssl_options,
build_replication_over_tls_options("client_", SslDistOpt, [])}];
{ssl_dist_optfile, [OptFile]} ->
LogFun(debug,
"Using ssl_dist_optfile to configure "
++ "stream replication over TLS",
[]),
case FileConsultFun(OptFile) of
{ok, [TlsDist]} ->
SslServerOptions = proplists:get_value(server, TlsDist, []),
SslClientOptions = proplists:get_value(client, TlsDist, []),
[{replication_transport, ssl},
{replication_server_ssl_options, SslServerOptions},
{replication_client_ssl_options, SslClientOptions}];
{error, Error} ->
LogFun(warn,
"Error while reading TLS "
++ "distributon option file ~ts: ~p",
[OptFile, Error]),
LogFun(warn,
"Stream replication over TLS will NOT be enabled",
[]),
[];
R ->
LogFun(warn,
"Unexpected result while reading TLS distributon "
"option file ~ts: ~p",
[OptFile, R]),
LogFun(warn,
"Stream replication over TLS will NOT be enabled",
[]),
[]
end
end.
build_replication_over_tls_options(_Prefix, [], Acc) ->
Acc;
build_replication_over_tls_options("server_" = Prefix,
[{ssl_dist_opt, ["server_" ++ Key, Value]}
| Tail],
Acc) ->
Option = list_to_atom(Key),
build_replication_over_tls_options(Prefix, Tail,
Acc
++ [extract_replication_over_tls_option(Option,
Value)]);
build_replication_over_tls_options("client_" = Prefix,
[{ssl_dist_opt, ["client_" ++ Key, Value]}
| Tail],
Acc) ->
Option = list_to_atom(Key),
build_replication_over_tls_options(Prefix, Tail,
Acc
++ [extract_replication_over_tls_option(Option,
Value)]);
build_replication_over_tls_options(Prefix,
[{ssl_dist_opt, [Key1, Value1, Key2, Value2]}
| Tail],
Acc) ->
%% For -ssl_dist_opt server_secure_renegotiate true client_secure_renegotiate true
build_replication_over_tls_options(Prefix,
[{ssl_dist_opt, [Key1, Value1]},
{ssl_dist_opt, [Key2, Value2]}]
++ Tail,
Acc);
build_replication_over_tls_options(Prefix,
[{ssl_dist_opt, [_Key, _Value]} | Tail],
Acc) ->
build_replication_over_tls_options(Prefix, Tail, Acc).
extract_replication_over_tls_option(certfile, V) ->
{certfile, V};
extract_replication_over_tls_option(keyfile, V) ->
{keyfile, V};
extract_replication_over_tls_option(password, V) ->
{password, V};
extract_replication_over_tls_option(cacertfile, V) ->
{cacertfile, V};
extract_replication_over_tls_option(verify, V) ->
{verify, list_to_atom(V)};
extract_replication_over_tls_option(verify_fun, V) ->
%% Write as {Module, Function, InitialUserState}
{verify_fun, eval_term(V)};
extract_replication_over_tls_option(crl_check, V) ->
{crl_check, list_to_atom(V)};
extract_replication_over_tls_option(crl_cache, V) ->
%% Write as Erlang term
{crl_cache, eval_term(V)};
extract_replication_over_tls_option(reuse_sessions, V) ->
%% boolean() | save
{reuse_sessions, eval_term(V)};
extract_replication_over_tls_option(secure_renegotiate, V) ->
{secure_renegotiate, list_to_atom(V)};
extract_replication_over_tls_option(depth, V) ->
{depth, list_to_integer(V)};
extract_replication_over_tls_option(hibernate_after, "undefined") ->
{hibernate_after, undefined};
extract_replication_over_tls_option(hibernate_after, V) ->
{hibernate_after, list_to_integer(V)};
extract_replication_over_tls_option(ciphers, V) ->
%% Use old string format
e.g. TLS_AES_256_GCM_SHA384 : TLS_AES_128_GCM_SHA256
{ciphers, V};
extract_replication_over_tls_option(fail_if_no_peer_cert, V) ->
{fail_if_no_peer_cert, list_to_atom(V)};
extract_replication_over_tls_option(dhfile, V) ->
{dhfile, V}.
eval_term(V) ->
{ok, Tokens, _EndLine} = erl_scan:string(V ++ "."),
{ok, AbsForm} = erl_parse:parse_exprs(Tokens),
{value, Term, _Bs} = erl_eval:exprs(AbsForm, erl_eval:new_bindings()),
Term.
inet_tls_enabled([]) ->
false;
inet_tls_enabled([{proto_dist, ["inet_tls"]} | _]) ->
true;
inet_tls_enabled([_Opt | Tail]) ->
inet_tls_enabled(Tail).
partition_parallel(F, Es, Timeout) ->
Parent = self(),
Running = [{spawn_monitor(fun() -> Parent ! {self(), F(E)} end), E}
|| E <- Es],
collect(Running, {[], []}, Timeout).
collect([], Acc, _Timeout) ->
Acc;
collect([{{Pid, MRef}, E} | Next], {Left, Right}, Timeout) ->
receive
{Pid, true} ->
erlang:demonitor(MRef, [flush]),
collect(Next, {[E | Left], Right}, Timeout);
{Pid, false} ->
erlang:demonitor(MRef, [flush]),
collect(Next, {Left, [E | Right]}, Timeout);
{'DOWN', MRef, process, Pid, _Reason} ->
collect(Next, {Left, [E | Right]}, Timeout)
after Timeout ->
exit(partition_parallel_timeout)
end.
normalise_name(Name) when is_binary(Name) ->
Name;
normalise_name(Name) when is_list(Name) ->
list_to_binary(Name).
get_reader_context(Pid)
when is_pid(Pid) andalso node(Pid) == node() ->
case ets:lookup(osiris_reader_context_cache, Pid) of
[] ->
{ok, Ctx0} = gen:call(Pid, '$gen_call', get_reader_context),
Ctx0;
[{_Pid, Dir, Name, Shared, Ref, ReadersCountersFun}] ->
#{dir => Dir,
name => Name,
shared => Shared,
reference => Ref,
readers_counter_fun => ReadersCountersFun}
end.
cache_reader_context(Pid, Dir, Name, Shared, Ref, ReadersCounterFun)
when is_pid(Pid) andalso
?IS_STRING(Dir) andalso
is_function(ReadersCounterFun) ->
true = ets:insert(osiris_reader_context_cache,
{Pid, Dir, Name, Shared, Ref, ReadersCounterFun}),
ok.
| null | https://raw.githubusercontent.com/rabbitmq/osiris/399b470aac3da54da17ae3f149c768bedf91368d/src/osiris_util.erl | erlang |
For testing
For -ssl_dist_opt server_secure_renegotiate true client_secure_renegotiate true
Write as {Module, Function, InitialUserState}
Write as Erlang term
boolean() | save
Use old string format | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2007 - 2022 VMware , Inc. or its affiliates . All rights reserved .
-module(osiris_util).
-include("osiris.hrl").
-export([validate_base64uri/1,
to_base64uri/1,
id/1,
lists_find/2,
hostname_from_node/0,
get_replication_configuration_from_tls_dist/0,
get_replication_configuration_from_tls_dist/1,
get_replication_configuration_from_tls_dist/2,
partition_parallel/3,
normalise_name/1,
get_reader_context/1,
cache_reader_context/6
]).
-export([inet_tls_enabled/1,
replication_over_tls_configuration/3]).
-define(BASE64_URI_CHARS,
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01"
"23456789_-=").
-spec validate_base64uri(string() | binary()) -> boolean().
validate_base64uri(Str) when ?IS_STRING(Str) ->
catch begin
[begin
case lists:member(C, ?BASE64_URI_CHARS) of
true ->
ok;
false ->
throw(false)
end
end
|| C <- string:to_graphemes(Str)],
string:is_empty(Str) == false
end.
-spec to_base64uri(string() | binary()) -> string().
to_base64uri(Str) when ?IS_STRING(Str) ->
lists:foldr(fun(G, Acc) ->
case lists:member(G, ?BASE64_URI_CHARS) of
true -> [G | Acc];
false -> [$_ | Acc]
end
end,
[], string:to_graphemes(Str)).
-spec id(term()) -> term().
id(X) ->
X.
-spec lists_find(fun((term()) -> boolean()), list()) ->
{ok, term()} | not_found.
lists_find(_Pred, []) ->
not_found;
lists_find(Pred, [Item | Rem]) ->
case Pred(Item) of
true ->
{ok, Item};
false ->
lists_find(Pred, Rem)
end.
hostname_from_node() ->
case re:split(atom_to_list(node()), "@", [{return, list}, {parts, 2}])
of
[_, Hostname] ->
Hostname;
[_] ->
{ok, H} = inet:gethostname(),
H
end.
get_replication_configuration_from_tls_dist() ->
get_replication_configuration_from_tls_dist(fun (debug, Fmt, Args) ->
?DEBUG(Fmt, Args);
(warn, Fmt, Args) ->
?WARN(Fmt, Args);
(warning, Fmt, Args) ->
?WARN(Fmt, Args);
(_, Fmt, Args) ->
?INFO(Fmt, Args)
end).
get_replication_configuration_from_tls_dist(LogFun) ->
get_replication_configuration_from_tls_dist(fun file:consult/1,
LogFun).
get_replication_configuration_from_tls_dist(FileConsultFun, LogFun) ->
InitArguments = init:get_arguments(),
case inet_tls_enabled(InitArguments) of
true ->
LogFun(debug,
"Inter-node TLS enabled, "
++ "configuring stream replication over TLS",
[]),
replication_over_tls_configuration(InitArguments, FileConsultFun, LogFun);
false ->
LogFun(debug, "Inter-node TLS not enabled", []),
[]
end.
replication_over_tls_configuration(InitArgs, FileConsultFun, LogFun) ->
case proplists:lookup(ssl_dist_optfile, InitArgs) of
none ->
LogFun(debug,
"Using ssl_dist_opt to configure "
++ "stream replication over TLS",
[]),
SslDistOpt = proplists:lookup_all(ssl_dist_opt, InitArgs),
[{replication_transport, ssl},
{replication_server_ssl_options,
build_replication_over_tls_options("server_", SslDistOpt, [])},
{replication_client_ssl_options,
build_replication_over_tls_options("client_", SslDistOpt, [])}];
{ssl_dist_optfile, [OptFile]} ->
LogFun(debug,
"Using ssl_dist_optfile to configure "
++ "stream replication over TLS",
[]),
case FileConsultFun(OptFile) of
{ok, [TlsDist]} ->
SslServerOptions = proplists:get_value(server, TlsDist, []),
SslClientOptions = proplists:get_value(client, TlsDist, []),
[{replication_transport, ssl},
{replication_server_ssl_options, SslServerOptions},
{replication_client_ssl_options, SslClientOptions}];
{error, Error} ->
LogFun(warn,
"Error while reading TLS "
++ "distributon option file ~ts: ~p",
[OptFile, Error]),
LogFun(warn,
"Stream replication over TLS will NOT be enabled",
[]),
[];
R ->
LogFun(warn,
"Unexpected result while reading TLS distributon "
"option file ~ts: ~p",
[OptFile, R]),
LogFun(warn,
"Stream replication over TLS will NOT be enabled",
[]),
[]
end
end.
build_replication_over_tls_options(_Prefix, [], Acc) ->
Acc;
build_replication_over_tls_options("server_" = Prefix,
[{ssl_dist_opt, ["server_" ++ Key, Value]}
| Tail],
Acc) ->
Option = list_to_atom(Key),
build_replication_over_tls_options(Prefix, Tail,
Acc
++ [extract_replication_over_tls_option(Option,
Value)]);
build_replication_over_tls_options("client_" = Prefix,
[{ssl_dist_opt, ["client_" ++ Key, Value]}
| Tail],
Acc) ->
Option = list_to_atom(Key),
build_replication_over_tls_options(Prefix, Tail,
Acc
++ [extract_replication_over_tls_option(Option,
Value)]);
build_replication_over_tls_options(Prefix,
[{ssl_dist_opt, [Key1, Value1, Key2, Value2]}
| Tail],
Acc) ->
build_replication_over_tls_options(Prefix,
[{ssl_dist_opt, [Key1, Value1]},
{ssl_dist_opt, [Key2, Value2]}]
++ Tail,
Acc);
build_replication_over_tls_options(Prefix,
[{ssl_dist_opt, [_Key, _Value]} | Tail],
Acc) ->
build_replication_over_tls_options(Prefix, Tail, Acc).
extract_replication_over_tls_option(certfile, V) ->
{certfile, V};
extract_replication_over_tls_option(keyfile, V) ->
{keyfile, V};
extract_replication_over_tls_option(password, V) ->
{password, V};
extract_replication_over_tls_option(cacertfile, V) ->
{cacertfile, V};
extract_replication_over_tls_option(verify, V) ->
{verify, list_to_atom(V)};
extract_replication_over_tls_option(verify_fun, V) ->
{verify_fun, eval_term(V)};
extract_replication_over_tls_option(crl_check, V) ->
{crl_check, list_to_atom(V)};
extract_replication_over_tls_option(crl_cache, V) ->
{crl_cache, eval_term(V)};
extract_replication_over_tls_option(reuse_sessions, V) ->
{reuse_sessions, eval_term(V)};
extract_replication_over_tls_option(secure_renegotiate, V) ->
{secure_renegotiate, list_to_atom(V)};
extract_replication_over_tls_option(depth, V) ->
{depth, list_to_integer(V)};
extract_replication_over_tls_option(hibernate_after, "undefined") ->
{hibernate_after, undefined};
extract_replication_over_tls_option(hibernate_after, V) ->
{hibernate_after, list_to_integer(V)};
extract_replication_over_tls_option(ciphers, V) ->
e.g. TLS_AES_256_GCM_SHA384 : TLS_AES_128_GCM_SHA256
{ciphers, V};
extract_replication_over_tls_option(fail_if_no_peer_cert, V) ->
{fail_if_no_peer_cert, list_to_atom(V)};
extract_replication_over_tls_option(dhfile, V) ->
{dhfile, V}.
eval_term(V) ->
{ok, Tokens, _EndLine} = erl_scan:string(V ++ "."),
{ok, AbsForm} = erl_parse:parse_exprs(Tokens),
{value, Term, _Bs} = erl_eval:exprs(AbsForm, erl_eval:new_bindings()),
Term.
inet_tls_enabled([]) ->
false;
inet_tls_enabled([{proto_dist, ["inet_tls"]} | _]) ->
true;
inet_tls_enabled([_Opt | Tail]) ->
inet_tls_enabled(Tail).
partition_parallel(F, Es, Timeout) ->
Parent = self(),
Running = [{spawn_monitor(fun() -> Parent ! {self(), F(E)} end), E}
|| E <- Es],
collect(Running, {[], []}, Timeout).
collect([], Acc, _Timeout) ->
Acc;
collect([{{Pid, MRef}, E} | Next], {Left, Right}, Timeout) ->
receive
{Pid, true} ->
erlang:demonitor(MRef, [flush]),
collect(Next, {[E | Left], Right}, Timeout);
{Pid, false} ->
erlang:demonitor(MRef, [flush]),
collect(Next, {Left, [E | Right]}, Timeout);
{'DOWN', MRef, process, Pid, _Reason} ->
collect(Next, {Left, [E | Right]}, Timeout)
after Timeout ->
exit(partition_parallel_timeout)
end.
normalise_name(Name) when is_binary(Name) ->
Name;
normalise_name(Name) when is_list(Name) ->
list_to_binary(Name).
get_reader_context(Pid)
when is_pid(Pid) andalso node(Pid) == node() ->
case ets:lookup(osiris_reader_context_cache, Pid) of
[] ->
{ok, Ctx0} = gen:call(Pid, '$gen_call', get_reader_context),
Ctx0;
[{_Pid, Dir, Name, Shared, Ref, ReadersCountersFun}] ->
#{dir => Dir,
name => Name,
shared => Shared,
reference => Ref,
readers_counter_fun => ReadersCountersFun}
end.
cache_reader_context(Pid, Dir, Name, Shared, Ref, ReadersCounterFun)
when is_pid(Pid) andalso
?IS_STRING(Dir) andalso
is_function(ReadersCounterFun) ->
true = ets:insert(osiris_reader_context_cache,
{Pid, Dir, Name, Shared, Ref, ReadersCounterFun}),
ok.
|
89aeee4001dc1f60e26c8dc5983a22c6bafd35e0e2bd378ac7e070d604addb5b | mirage/ocaml-matrix | http.mli | module Server : sig
type scheme = [ `Http | `Https ]
type t = {scheme: scheme; host: string; port: int}
val pp : Format.formatter -> t -> unit
val v : scheme -> string -> int -> t
val to_uri : t -> string -> (string * string list) list option -> Uri.t
end
type 'a or_error = ('a, Matrix_ctos.Errors.t) result
val get :
Server.t ->
?header:(string * string) list ->
string ->
(string * string list) list option ->
'a Json_encoding.encoding ->
string option ->
'a or_error Lwt.t
val post :
Server.t ->
?header:(string * string) list ->
string ->
(string * string list) list option ->
'a ->
'a Json_encoding.encoding ->
'b Json_encoding.encoding ->
string option ->
'b or_error Lwt.t
val put :
Server.t ->
?header:(string * string) list ->
string ->
(string * string list) list option ->
'a ->
'a Json_encoding.encoding ->
'b Json_encoding.encoding ->
string option ->
'b or_error Lwt.t
| null | https://raw.githubusercontent.com/mirage/ocaml-matrix/2a58d3d41c43404741f2dfdaf1d2d0f3757b2b69/ci-client/http.mli | ocaml | module Server : sig
type scheme = [ `Http | `Https ]
type t = {scheme: scheme; host: string; port: int}
val pp : Format.formatter -> t -> unit
val v : scheme -> string -> int -> t
val to_uri : t -> string -> (string * string list) list option -> Uri.t
end
type 'a or_error = ('a, Matrix_ctos.Errors.t) result
val get :
Server.t ->
?header:(string * string) list ->
string ->
(string * string list) list option ->
'a Json_encoding.encoding ->
string option ->
'a or_error Lwt.t
val post :
Server.t ->
?header:(string * string) list ->
string ->
(string * string list) list option ->
'a ->
'a Json_encoding.encoding ->
'b Json_encoding.encoding ->
string option ->
'b or_error Lwt.t
val put :
Server.t ->
?header:(string * string) list ->
string ->
(string * string list) list option ->
'a ->
'a Json_encoding.encoding ->
'b Json_encoding.encoding ->
string option ->
'b or_error Lwt.t
| |
1474a4d0bb030a6d7a39f8aadacfae414d7a366f4373981ccea3c0d37950aa7e | axellang/axel | Error.hs | # LANGUAGE TemplateHaskell #
module Axel.Haskell.Error where
import Axel.Prelude
import Axel.Sourcemap
( ModuleInfo
, Position(Position)
, SourcePosition
, renderSourcePosition
)
import qualified Axel.Sourcemap as SM
import Axel.Utils.FilePath (replaceExtension)
import Axel.Utils.Json (_Int)
import Axel.Utils.Text (encodeUtf8Lazy, indent)
import Control.Lens.Operators ((^.), (^?))
import Control.Lens.TH (makeFieldsNoPrefix)
import Control.Lens.Tuple (_1, _2)
import Control.Monad (join)
import qualified Data.Aeson as Json
import Data.Aeson.Lens (_String, key)
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import qualified Data.Text as T
data GhcError =
GhcError
{ _message :: Text
, _sourcePosition :: SourcePosition
}
deriving (Show)
makeFieldsNoPrefix ''GhcError
processStackOutputLine :: ModuleInfo -> Text -> [Text]
processStackOutputLine moduleInfo line =
fromMaybe [line] (tryProcessGhcOutput moduleInfo line)
tryProcessGhcOutput :: ModuleInfo -> Text -> Maybe [Text]
tryProcessGhcOutput moduleInfo line = do
let obj `viewText` field = obj ^? field . _String
jsonLine <- Json.decode' @Json.Value (encodeUtf8Lazy line)
msg <- jsonLine `viewText` key "doc"
pure $ fromMaybe [msg] $ do
jsonSpan <- jsonLine ^? key "span"
startPosition <-
Position <$> (jsonSpan ^? key "startLine" . _Int) <*>
(jsonSpan ^? key "startCol" . _Int)
filePath <- jsonSpan `viewText` key "file"
let haskellSourcePosition = (T.unpack filePath, startPosition)
let maybeAxelError =
toAxelError moduleInfo $ GhcError msg haskellSourcePosition
let haskellError =
"\n" <> indent 4 msg <>
"The above message is in terms of the generated Haskell, at " <>
renderSourcePosition haskellSourcePosition <>
".\nIt couldn't be mapped to an Axel location (did a macro lose a sourcemapping annotation along the way?).\n"
pure [fromMaybe haskellError maybeAxelError]
toAxelError :: ModuleInfo -> GhcError -> Maybe Text
toAxelError moduleInfo ghcError = do
let haskellPath = ghcError ^. sourcePosition . _1
let haskellPosition = ghcError ^. sourcePosition . _2
let axelPath = replaceExtension (FilePath $ T.pack haskellPath) "axel"
let positionHint startPos = "at " <> renderSourcePosition startPos
SM.Output transpiledOutput <- M.lookup axelPath moduleInfo >>= snd
axelSourcePosition <-
join $ SM.findOriginalPosition transpiledOutput haskellPosition
pure $ "\n" <> indent 4 (ghcError ^. message) <>
"The above message is in terms of the generated Haskell, " <>
positionHint (haskellPath, haskellPosition) <>
".\nTry checking " <>
positionHint axelSourcePosition <>
".\nIf the Axel code at that position doesn't seem related, something may have gone wrong during a macro expansion.\n"
| null | https://raw.githubusercontent.com/axellang/axel/f51b4d984ae1674727e90b81274b635693d389ea/src/Axel/Haskell/Error.hs | haskell | # LANGUAGE TemplateHaskell #
module Axel.Haskell.Error where
import Axel.Prelude
import Axel.Sourcemap
( ModuleInfo
, Position(Position)
, SourcePosition
, renderSourcePosition
)
import qualified Axel.Sourcemap as SM
import Axel.Utils.FilePath (replaceExtension)
import Axel.Utils.Json (_Int)
import Axel.Utils.Text (encodeUtf8Lazy, indent)
import Control.Lens.Operators ((^.), (^?))
import Control.Lens.TH (makeFieldsNoPrefix)
import Control.Lens.Tuple (_1, _2)
import Control.Monad (join)
import qualified Data.Aeson as Json
import Data.Aeson.Lens (_String, key)
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import qualified Data.Text as T
data GhcError =
GhcError
{ _message :: Text
, _sourcePosition :: SourcePosition
}
deriving (Show)
makeFieldsNoPrefix ''GhcError
processStackOutputLine :: ModuleInfo -> Text -> [Text]
processStackOutputLine moduleInfo line =
fromMaybe [line] (tryProcessGhcOutput moduleInfo line)
tryProcessGhcOutput :: ModuleInfo -> Text -> Maybe [Text]
tryProcessGhcOutput moduleInfo line = do
let obj `viewText` field = obj ^? field . _String
jsonLine <- Json.decode' @Json.Value (encodeUtf8Lazy line)
msg <- jsonLine `viewText` key "doc"
pure $ fromMaybe [msg] $ do
jsonSpan <- jsonLine ^? key "span"
startPosition <-
Position <$> (jsonSpan ^? key "startLine" . _Int) <*>
(jsonSpan ^? key "startCol" . _Int)
filePath <- jsonSpan `viewText` key "file"
let haskellSourcePosition = (T.unpack filePath, startPosition)
let maybeAxelError =
toAxelError moduleInfo $ GhcError msg haskellSourcePosition
let haskellError =
"\n" <> indent 4 msg <>
"The above message is in terms of the generated Haskell, at " <>
renderSourcePosition haskellSourcePosition <>
".\nIt couldn't be mapped to an Axel location (did a macro lose a sourcemapping annotation along the way?).\n"
pure [fromMaybe haskellError maybeAxelError]
toAxelError :: ModuleInfo -> GhcError -> Maybe Text
toAxelError moduleInfo ghcError = do
let haskellPath = ghcError ^. sourcePosition . _1
let haskellPosition = ghcError ^. sourcePosition . _2
let axelPath = replaceExtension (FilePath $ T.pack haskellPath) "axel"
let positionHint startPos = "at " <> renderSourcePosition startPos
SM.Output transpiledOutput <- M.lookup axelPath moduleInfo >>= snd
axelSourcePosition <-
join $ SM.findOriginalPosition transpiledOutput haskellPosition
pure $ "\n" <> indent 4 (ghcError ^. message) <>
"The above message is in terms of the generated Haskell, " <>
positionHint (haskellPath, haskellPosition) <>
".\nTry checking " <>
positionHint axelSourcePosition <>
".\nIf the Axel code at that position doesn't seem related, something may have gone wrong during a macro expansion.\n"
| |
e62fe5ebf91ec284a6f7b810d78dd2ece256abdd50b5dc2a1f0e81fe2c70e26a | hgoes/vvt | Value.hs | # LANGUAGE RankNTypes , TypeFamilies , MultiParamTypeClasses , FlexibleContexts ,
FlexibleInstances , ScopedTypeVariables , GADTs , DeriveDataTypeable ,
DeriveFunctor , , DeriveTraversable #
FlexibleInstances,ScopedTypeVariables,GADTs,DeriveDataTypeable,
DeriveFunctor,DeriveFoldable,DeriveTraversable #-}
module Realization.Lisp.Value where
import Realization.Lisp.Array
import Args
import PartialArgs
import Language.SMTLib2.Internals.Type hiding (Constr,Field)
import Language.SMTLib2.Internals.Type.Nat
import Language.SMTLib2.Internals.Type.List (List(..))
import qualified Language.SMTLib2.Internals.Type.List as List
import Language.SMTLib2.Internals.Type.Struct (Tree(..),Struct(..))
import qualified Language.SMTLib2.Internals.Type.Struct as Struct
import Language.SMTLib2.Internals.Embed
import Language.SMTLib2.Internals.Interface
import Data.List (genericLength)
import Data.Foldable
import Data.Traversable
import Data.Typeable
import Prelude hiding (mapM,foldl,and,concat)
import Data.GADT.Compare
import Data.GADT.Show
import Control.Monad.Identity
import Text.Show
data LispValue (sig :: ([Type],Tree Type)) (e::Type -> *) where
LispValue :: Size e sz -> Struct (Sized e sz) tps -> LispValue '(sz,tps) e
lispValueType :: GetType e => LispValue '(sz,tps) e -> (List Repr sz,Struct Repr tps)
lispValueType (LispValue sz val) = (rsz,Struct.map (\e -> sizedType e rsz) val)
where
rsz = sizeIndices sz
eqValue :: (Embed m e,Monad m,GetType e)
=> LispValue '(lvl,tps) e
-> LispValue '(lvl,tps) e
-> m (e BoolType)
eqValue (LispValue sz1 v1) (LispValue sz2 v2) = do
conj1 <- eqSize sz1 sz2
conj2 <- eqVal v1 v2
case conj1++conj2 of
[] -> true
[x] -> return x
xs -> and' xs
where
eqVal :: (Embed m e,Monad m,GetType e) => Struct (Sized e lvl) tps
-> Struct (Sized e lvl) tps
-> m [e BoolType]
eqVal = Struct.zipFlatten (\(Sized x) (Sized y) -> do
res <- x .==. y
return [res])
(return . concat)
iteValue :: (Embed m e,Monad m,GetType e)
=> e BoolType -> LispValue '(sz,tps) e -> LispValue '(sz,tps) e
-> m (LispValue '(sz,tps) e)
iteValue c (LispValue sz1 v1) (LispValue sz2 v2) = do
nsz <- iteSize c sz1 sz2
nval <- Struct.zipWithM (\(Sized x) (Sized y) -> do
z <- ite c x y
return (Sized z)
) v1 v2
return (LispValue nsz nval)
geqValue :: (GetType e,GEq e) => LispValue '(lvl1,tps1) e -> LispValue '(lvl2,tps2) e -> Maybe (lvl1 :~: lvl2,tps1 :~: tps2)
geqValue (LispValue (Size sz1 _) val1) (LispValue (Size sz2 _) val2) = do
Refl <- geq sz1 sz2
Refl <- eqSized sz1 val1 val2
return (Refl,Refl)
where
eqSized :: (GetType e,GEq e) => List Repr sz
-> Struct (Sized e sz) tp1
-> Struct (Sized e sz) tp2
-> Maybe (tp1 :~: tp2)
eqSized sz (Singleton x) (Singleton y) = do
Refl <- geqSized sz x y
return Refl
eqSized sz (Struct Nil) (Struct Nil) = return Refl
eqSized sz (Struct (x ::: xs)) (Struct (y ::: ys)) = do
Refl <- eqSized sz x y
Refl <- eqSized sz (Struct xs) (Struct ys)
return Refl
eqSized _ _ _ = Nothing
data LispUVal (sig :: ([Type],Tree Type)) where
LispU :: Struct Value tps -> LispUVal '( '[],tps)
LispUArray :: Repr sz -> List Repr szs -> Struct Repr tps
-> [LispUVal '(szs,tps)] -> LispUVal '(sz ': szs,tps)
instance GEq LispUVal where
geq (LispU x) (LispU y) = do
Refl <- geq x y
return Refl
geq (LispUArray nx nxs tpx x) (LispUArray ny nys tpy y) = do
Refl <- geq nx ny
Refl <- geq nxs nys
Refl <- geq tpx tpy
if x==y
then return Refl
else Nothing
geq _ _ = Nothing
deriving instance Eq (LispUVal sig)
deriving instance Ord (LispUVal sig)
instance Show (LispUVal sig) where
showsPrec p (LispU x) = showsPrec p x
showsPrec p (LispUArray _ _ _ arr) = showListWith (showsPrec 0) arr
data LispPVal (sig :: ([Type],Tree Type)) where
LispP :: Struct PValue tps -> LispPVal '( '[],tps)
LispPArray :: Repr sz -> [LispPVal '(szs,tps)] -> LispPVal '(sz ': szs,tps)
deriving instance Eq (LispPVal sig)
deriving instance Ord (LispPVal sig)
instance Show (LispPVal sig) where
showsPrec p (LispP struct) = showsPrec p struct
showsPrec p (LispPArray _ arr) = showsPrec p arr
type LispIndex idx = List Natural idx
lispIndexType :: Struct Repr tps -> LispIndex idx -> Repr (Struct.ElementIndex tps idx)
lispIndexType = Struct.elementIndex
accessVal :: Monad m
=> LispIndex idx
-> Struct (Sized e lvl) tp
-> (Sized e lvl (Struct.ElementIndex tp idx) -> m (a,Sized e lvl ntp))
-> m (a,Struct (Sized e lvl) (Struct.Insert tp idx (Leaf ntp)))
accessVal idx val = Struct.accessElement val idx
data RevValue sig t where
RevVar :: LispIndex idx
-> RevValue '(sz,tps) (Arrayed sz (Struct.ElementIndex tps idx))
RevSize :: Natural i
-> RevValue '(sz,tps) (List.Index (SizeList sz) i)
instance GEq (RevValue sig) where
geq (RevVar i1) (RevVar i2) = do
Refl <- geq i1 i2
return Refl
geq (RevSize n1) (RevSize n2) = do
Refl <- geq n1 n2
return Refl
geq _ _ = Nothing
instance GCompare (RevValue sig) where
gcompare (RevVar i1) (RevVar i2) = case gcompare i1 i2 of
GEQ -> GEQ
GLT -> GLT
GGT -> GGT
gcompare (RevVar _) _ = GLT
gcompare _ (RevVar _) = GGT
gcompare (RevSize n1) (RevSize n2) = case gcompare n1 n2 of
GEQ -> GEQ
GLT -> GLT
GGT -> GGT
instance Show (RevValue sig t) where
showsPrec p (RevVar idx) = showParen (p>10) $
showString "RevVar " .
showsPrec 11 idx
showsPrec p (RevSize lvl) = showParen (p>10) $
showString "RevSize " .
showsPrec 11 lvl
instance GShow (RevValue sig) where
gshowsPrec = showsPrec
instance Composite (LispValue '(lvl,tps)) where
type CompDescr (LispValue '(lvl,tps)) = (List Repr lvl,Struct Repr tps)
type RevComp (LispValue '(lvl,tps)) = RevValue '(lvl,tps)
compositeType (sz,tps)
= LispValue (sizeType sz)
(runIdentity $ Struct.mapM
(\tp -> return (Sized (arrayType sz tp))) tps)
foldExprs f (LispValue sz val) = do
sz' <- foldSize (\i -> f (RevSize i)) sz
val' <- Struct.mapIndexM (\idx (Sized e) -> fmap Sized (f (RevVar idx) e)) val
return $ LispValue sz' val'
createComposite f (lvl,tp) = do
sz <- createSize (\i tp -> f tp (RevSize i)) lvl
val <- createStruct f lvl tp
return (LispValue sz val)
where
createStruct :: Monad m => (forall t. Repr t -> RevValue '(lvl,tps) t -> m (e t))
-> List Repr lvl
-> Struct Repr tps
-> m (Struct (Sized e lvl) tps)
createStruct f lvl = Struct.mapIndexM
(\idx tp -> do
e <- f (arrayType lvl tp) (RevVar idx)
return (Sized e))
accessComposite (RevVar idx) (LispValue sz val)
= fst $ runIdentity $ accessVal idx val $
\v@(Sized e) -> return (e,v)
accessComposite (RevSize idx) (LispValue sz val)
= fst $ runIdentity $ accessSize (\e -> return (e,e)) idx sz
eqComposite = eqValue
revType _ (lvl,tps) (RevVar idx) = arrayType lvl (Struct.elementIndex tps idx)
revType _ (lvl,tps) (RevSize idx)
= List.index (sizeListType lvl) idx
instance LiftComp (LispValue '(lvl,tps)) where
type Unpacked (LispValue '(lvl,tps)) = LispUVal '(lvl,tps)
liftComp (LispU vals) = do
vals' <- Struct.mapM (\v -> do
c <- constant v
return (Sized c)
) vals
return $ LispValue (Size Nil Nil) vals'
liftComp (LispUArray sz szs tps lst) = do
lst' <- mapM liftComp lst
liftValues sz szs tps lst'
unliftComp f lv@(LispValue sz val) = case sz of
Size Nil Nil -> do
rval <- Struct.mapM (\(Sized e) -> f e) val
return (LispU rval)
Size (_ ::: _) (_ ::: _) -> case lispValueType lv of
(sz' ::: szs,tps) -> do
vals <- unliftValue f lv
vals' <- mapM (unliftComp f) vals
return $ LispUArray sz' szs tps vals'
indexValue :: (Embed m e,Monad m,GetType e) => (forall t. e t -> Value t -> m p)
-> Value sz
-> LispValue '(sz ': szs,tps) e
-> m (p,LispValue '(szs,tps) e)
indexValue f idx (LispValue sz val) = do
(res,nsz) <- indexSize f idx sz
nval <- indexValue' f idx val
return (res,LispValue nsz nval)
where
indexSize :: (Embed m e,Monad m,GetType e) => (forall t. e t -> Value t -> m p)
-> Value sz -> Size e (sz ': szs)
-> m (p,Size e szs)
indexSize f n (Size (tp ::: tps) (sz ::: szs)) = do
res <- f sz n
nszs <- List.unmapM (sizeListType tps) szs (\arr -> do
n' <- constant n
select arr (n' ::: Nil))
return (res,Size tps nszs)
indexValue' :: (Embed m e,Monad m,GetType e) => (forall t. e t -> Value t -> m p)
-> Value sz
-> Struct (Sized e (sz ': szs)) tps
-> m (Struct (Sized e szs) tps)
indexValue' f n = Struct.mapM
(\(Sized x)
-> do
n' <- constant n
x' <- select x (n' ::: Nil)
return $ Sized x')
assignPartialLisp :: (Embed m e,Monad m,GetType e) => (forall t. e t -> Value t -> m p)
-> LispValue tps e -> LispPVal tps
-> m [Maybe p]
assignPartialLisp f (LispValue sz val) (LispP str) = assignStruct f val str
where
assignStruct :: (Embed m e,Monad m) => (forall t. e t -> Value t -> m p)
-> Struct (Sized e '[]) tps'
-> Struct PValue tps'
-> m [Maybe p]
assignStruct f (Singleton (Sized x)) (Singleton (PValue val)) = do
r <- f x val
return [Just r]
assignStruct _ _ (Singleton (NoPValue _)) = return [Nothing]
assignStruct f (Struct xs) (Struct ys) = assignStructs f xs ys
assignStructs :: (Embed m e,Monad m) => (forall t. e t -> Value t -> m p)
-> List (Struct (Sized e '[])) tps'
-> List (Struct PValue) tps'
-> m [Maybe p]
assignStructs _ Nil Nil = return []
assignStructs f (x ::: xs) (y ::: ys) = do
r1 <- assignStruct f x y
r2 <- assignStructs f xs ys
return $ r1++r2
assignPartialLisp f val (LispPArray sz xs) = do
lst <- mapM (\(x,n) -> do
(asgnSize,nval) <- indexValue f n val
rest <- assignPartialLisp f nval x
return (Just asgnSize:rest)
) (zip xs range)
return $ concat lst
where
len = lengthValue sz (genericLength xs)
range = sizeRange len
unmaskLispValue :: LispUVal tps -> LispPVal tps
unmaskLispValue (LispU xs) = LispP $ runIdentity $ Struct.mapM (return.PValue) xs
unmaskLispValue (LispUArray sz _ _ xs)
= LispPArray sz (fmap unmaskLispValue xs)
maskLispValue :: LispPVal tps -> [Bool] -> (LispPVal tps,[Bool])
maskLispValue (LispP str) xs = let (str',xs') = maskStruct str xs
in (LispP str',xs')
maskLispValue (LispPArray sz arr) xs
= let (xs',arr') = mapAccumL (\xs e -> let (e',xs') = maskLispValue e xs
in (xs',e')
) xs arr
in (LispPArray sz arr',xs')
maskStruct :: Struct PValue tps -> [Bool] -> (Struct PValue tps,[Bool])
maskStruct (Singleton (NoPValue tp)) (_:xs) = (Singleton (NoPValue tp),xs)
maskStruct (Singleton (PValue x)) (False:xs) = (Singleton (NoPValue (valueType x)),xs)
maskStruct (Singleton (PValue v)) (True:xs) = (Singleton (PValue v),xs)
maskStruct (Struct str) xs = let (str',xs') = maskStructs str xs
in (Struct str',xs')
maskStructs :: List (Struct PValue) tps' -> [Bool]
-> (List (Struct PValue) tps',[Bool])
maskStructs Nil xs = (Nil,xs)
maskStructs (y ::: ys) xs = let (y',xs1) = maskStruct y xs
(ys',xs2) = maskStructs ys xs1
in (y' ::: ys',xs2)
extractStruct :: Monad m => (forall t. e t -> m (Value t))
-> Struct (Sized e '[]) tps
-> m (Struct Value tps)
extractStruct f = Struct.mapM (\(Sized x) -> f x)
unliftValue :: (Embed m e,Monad m,GetType e) => (forall t. e t -> m (Value t))
-> LispValue '(sz ': szs,tps) e
-> m [LispValue '(szs,tps) e]
unliftValue f lv@(LispValue sz val) = case lispValueType lv of
(csz ::: szs,tps) -> do
nszs <- unliftSize f sz
nvals <- unliftStruct f csz nszs val
return $ zipWith LispValue nszs nvals
unliftStruct :: (Embed m e,Monad m,GetType e) => (forall t. e t -> m (Value t))
-> Repr sz
-> [Size e szs]
-> Struct (Sized e (sz ': szs)) tps
-> m [Struct (Sized e szs) tps]
unliftStruct f sz szs (Singleton (Sized x))
= mapM (\(idx,sz) -> do
idx' <- constant idx
el <- select x (idx' ::: Nil)
return $ Singleton (Sized el)
) (zip range szs)
where
len = lengthValue sz (genericLength szs)
range = sizeRange len
unliftStruct f sz szs (Struct vals) = do
vals' <- unliftStructs f sz szs vals
return $ fmap Struct vals'
unliftStructs :: (Embed m e,Monad m,GetType e)
=> (forall t. e t -> m (Value t))
-> Repr sz
-> [Size e szs]
-> List (Struct (Sized e (sz ': szs))) tps
-> m [List (Struct (Sized e szs)) tps]
unliftStructs f sz szs Nil = return $ fmap (const Nil) szs
unliftStructs f sz szs (x ::: xs) = do
x' <- unliftStruct f sz szs x
xs' <- unliftStructs f sz szs xs
return $ zipWith (:::) x' xs'
liftValues :: (Embed m e,Monad m,GetType e)
=> Repr sz
-> List Repr szs
-> Struct Repr tps
-> [LispValue '(szs,tps) e]
-> m (LispValue '(sz ': szs,tps) e)
liftValues sz szs tps xs = do
nsz <- liftSizes sz szs (fmap (\(LispValue sz _) -> sz) xs)
nval <- liftStructs sz szs tps (fmap (\(LispValue _ val) -> val) xs)
return $ LispValue nsz nval
liftStruct :: (Embed m e,Monad m,GetType e)
=> Struct Value tps
-> m (Struct (Sized e '[]) tps)
liftStruct = Struct.mapM (fmap Sized . constant)
liftStructs :: (Embed m e,Monad m,GetType e)
=> Repr sz
-> List Repr szs
-> Struct Repr tp
-> [Struct (Sized e szs) tp]
-> m (Struct (Sized e (sz ': szs)) tp)
liftStructs sz szs tp vals = case tp of
Singleton tp' -> fmap Singleton $ liftSized sz szs tp' (fmap (\(Singleton x) -> x) vals)
Struct tps -> fmap Struct (liftStructs' sz szs tps (fmap (\(Struct x) -> x) vals))
where
liftStructs' :: (Embed m e,Monad m,GetType e)
=> Repr sz
-> List Repr szs
-> List (Struct Repr) tps
-> [List (Struct (Sized e szs)) tps]
-> m (List (Struct (Sized e (sz ': szs))) tps)
liftStructs' sz szs Nil _ = return Nil
liftStructs' sz szs (tp ::: tps) vals = do
y <- liftStructs sz szs tp $ fmap (\(x ::: _) -> x) vals
ys <- liftStructs' sz szs tps $ fmap (\(_ ::: xs) -> xs) vals
return $ y ::: ys
| null | https://raw.githubusercontent.com/hgoes/vvt/dd2809753d7e5059d9103ea578f36afa8294cd84/Realization/Lisp/Value.hs | haskell | # LANGUAGE RankNTypes , TypeFamilies , MultiParamTypeClasses , FlexibleContexts ,
FlexibleInstances , ScopedTypeVariables , GADTs , DeriveDataTypeable ,
DeriveFunctor , , DeriveTraversable #
FlexibleInstances,ScopedTypeVariables,GADTs,DeriveDataTypeable,
DeriveFunctor,DeriveFoldable,DeriveTraversable #-}
module Realization.Lisp.Value where
import Realization.Lisp.Array
import Args
import PartialArgs
import Language.SMTLib2.Internals.Type hiding (Constr,Field)
import Language.SMTLib2.Internals.Type.Nat
import Language.SMTLib2.Internals.Type.List (List(..))
import qualified Language.SMTLib2.Internals.Type.List as List
import Language.SMTLib2.Internals.Type.Struct (Tree(..),Struct(..))
import qualified Language.SMTLib2.Internals.Type.Struct as Struct
import Language.SMTLib2.Internals.Embed
import Language.SMTLib2.Internals.Interface
import Data.List (genericLength)
import Data.Foldable
import Data.Traversable
import Data.Typeable
import Prelude hiding (mapM,foldl,and,concat)
import Data.GADT.Compare
import Data.GADT.Show
import Control.Monad.Identity
import Text.Show
data LispValue (sig :: ([Type],Tree Type)) (e::Type -> *) where
LispValue :: Size e sz -> Struct (Sized e sz) tps -> LispValue '(sz,tps) e
lispValueType :: GetType e => LispValue '(sz,tps) e -> (List Repr sz,Struct Repr tps)
lispValueType (LispValue sz val) = (rsz,Struct.map (\e -> sizedType e rsz) val)
where
rsz = sizeIndices sz
eqValue :: (Embed m e,Monad m,GetType e)
=> LispValue '(lvl,tps) e
-> LispValue '(lvl,tps) e
-> m (e BoolType)
eqValue (LispValue sz1 v1) (LispValue sz2 v2) = do
conj1 <- eqSize sz1 sz2
conj2 <- eqVal v1 v2
case conj1++conj2 of
[] -> true
[x] -> return x
xs -> and' xs
where
eqVal :: (Embed m e,Monad m,GetType e) => Struct (Sized e lvl) tps
-> Struct (Sized e lvl) tps
-> m [e BoolType]
eqVal = Struct.zipFlatten (\(Sized x) (Sized y) -> do
res <- x .==. y
return [res])
(return . concat)
iteValue :: (Embed m e,Monad m,GetType e)
=> e BoolType -> LispValue '(sz,tps) e -> LispValue '(sz,tps) e
-> m (LispValue '(sz,tps) e)
iteValue c (LispValue sz1 v1) (LispValue sz2 v2) = do
nsz <- iteSize c sz1 sz2
nval <- Struct.zipWithM (\(Sized x) (Sized y) -> do
z <- ite c x y
return (Sized z)
) v1 v2
return (LispValue nsz nval)
geqValue :: (GetType e,GEq e) => LispValue '(lvl1,tps1) e -> LispValue '(lvl2,tps2) e -> Maybe (lvl1 :~: lvl2,tps1 :~: tps2)
geqValue (LispValue (Size sz1 _) val1) (LispValue (Size sz2 _) val2) = do
Refl <- geq sz1 sz2
Refl <- eqSized sz1 val1 val2
return (Refl,Refl)
where
eqSized :: (GetType e,GEq e) => List Repr sz
-> Struct (Sized e sz) tp1
-> Struct (Sized e sz) tp2
-> Maybe (tp1 :~: tp2)
eqSized sz (Singleton x) (Singleton y) = do
Refl <- geqSized sz x y
return Refl
eqSized sz (Struct Nil) (Struct Nil) = return Refl
eqSized sz (Struct (x ::: xs)) (Struct (y ::: ys)) = do
Refl <- eqSized sz x y
Refl <- eqSized sz (Struct xs) (Struct ys)
return Refl
eqSized _ _ _ = Nothing
data LispUVal (sig :: ([Type],Tree Type)) where
LispU :: Struct Value tps -> LispUVal '( '[],tps)
LispUArray :: Repr sz -> List Repr szs -> Struct Repr tps
-> [LispUVal '(szs,tps)] -> LispUVal '(sz ': szs,tps)
instance GEq LispUVal where
geq (LispU x) (LispU y) = do
Refl <- geq x y
return Refl
geq (LispUArray nx nxs tpx x) (LispUArray ny nys tpy y) = do
Refl <- geq nx ny
Refl <- geq nxs nys
Refl <- geq tpx tpy
if x==y
then return Refl
else Nothing
geq _ _ = Nothing
deriving instance Eq (LispUVal sig)
deriving instance Ord (LispUVal sig)
instance Show (LispUVal sig) where
showsPrec p (LispU x) = showsPrec p x
showsPrec p (LispUArray _ _ _ arr) = showListWith (showsPrec 0) arr
data LispPVal (sig :: ([Type],Tree Type)) where
LispP :: Struct PValue tps -> LispPVal '( '[],tps)
LispPArray :: Repr sz -> [LispPVal '(szs,tps)] -> LispPVal '(sz ': szs,tps)
deriving instance Eq (LispPVal sig)
deriving instance Ord (LispPVal sig)
instance Show (LispPVal sig) where
showsPrec p (LispP struct) = showsPrec p struct
showsPrec p (LispPArray _ arr) = showsPrec p arr
type LispIndex idx = List Natural idx
lispIndexType :: Struct Repr tps -> LispIndex idx -> Repr (Struct.ElementIndex tps idx)
lispIndexType = Struct.elementIndex
accessVal :: Monad m
=> LispIndex idx
-> Struct (Sized e lvl) tp
-> (Sized e lvl (Struct.ElementIndex tp idx) -> m (a,Sized e lvl ntp))
-> m (a,Struct (Sized e lvl) (Struct.Insert tp idx (Leaf ntp)))
accessVal idx val = Struct.accessElement val idx
data RevValue sig t where
RevVar :: LispIndex idx
-> RevValue '(sz,tps) (Arrayed sz (Struct.ElementIndex tps idx))
RevSize :: Natural i
-> RevValue '(sz,tps) (List.Index (SizeList sz) i)
instance GEq (RevValue sig) where
geq (RevVar i1) (RevVar i2) = do
Refl <- geq i1 i2
return Refl
geq (RevSize n1) (RevSize n2) = do
Refl <- geq n1 n2
return Refl
geq _ _ = Nothing
instance GCompare (RevValue sig) where
gcompare (RevVar i1) (RevVar i2) = case gcompare i1 i2 of
GEQ -> GEQ
GLT -> GLT
GGT -> GGT
gcompare (RevVar _) _ = GLT
gcompare _ (RevVar _) = GGT
gcompare (RevSize n1) (RevSize n2) = case gcompare n1 n2 of
GEQ -> GEQ
GLT -> GLT
GGT -> GGT
instance Show (RevValue sig t) where
showsPrec p (RevVar idx) = showParen (p>10) $
showString "RevVar " .
showsPrec 11 idx
showsPrec p (RevSize lvl) = showParen (p>10) $
showString "RevSize " .
showsPrec 11 lvl
instance GShow (RevValue sig) where
gshowsPrec = showsPrec
instance Composite (LispValue '(lvl,tps)) where
type CompDescr (LispValue '(lvl,tps)) = (List Repr lvl,Struct Repr tps)
type RevComp (LispValue '(lvl,tps)) = RevValue '(lvl,tps)
compositeType (sz,tps)
= LispValue (sizeType sz)
(runIdentity $ Struct.mapM
(\tp -> return (Sized (arrayType sz tp))) tps)
foldExprs f (LispValue sz val) = do
sz' <- foldSize (\i -> f (RevSize i)) sz
val' <- Struct.mapIndexM (\idx (Sized e) -> fmap Sized (f (RevVar idx) e)) val
return $ LispValue sz' val'
createComposite f (lvl,tp) = do
sz <- createSize (\i tp -> f tp (RevSize i)) lvl
val <- createStruct f lvl tp
return (LispValue sz val)
where
createStruct :: Monad m => (forall t. Repr t -> RevValue '(lvl,tps) t -> m (e t))
-> List Repr lvl
-> Struct Repr tps
-> m (Struct (Sized e lvl) tps)
createStruct f lvl = Struct.mapIndexM
(\idx tp -> do
e <- f (arrayType lvl tp) (RevVar idx)
return (Sized e))
accessComposite (RevVar idx) (LispValue sz val)
= fst $ runIdentity $ accessVal idx val $
\v@(Sized e) -> return (e,v)
accessComposite (RevSize idx) (LispValue sz val)
= fst $ runIdentity $ accessSize (\e -> return (e,e)) idx sz
eqComposite = eqValue
revType _ (lvl,tps) (RevVar idx) = arrayType lvl (Struct.elementIndex tps idx)
revType _ (lvl,tps) (RevSize idx)
= List.index (sizeListType lvl) idx
instance LiftComp (LispValue '(lvl,tps)) where
type Unpacked (LispValue '(lvl,tps)) = LispUVal '(lvl,tps)
liftComp (LispU vals) = do
vals' <- Struct.mapM (\v -> do
c <- constant v
return (Sized c)
) vals
return $ LispValue (Size Nil Nil) vals'
liftComp (LispUArray sz szs tps lst) = do
lst' <- mapM liftComp lst
liftValues sz szs tps lst'
unliftComp f lv@(LispValue sz val) = case sz of
Size Nil Nil -> do
rval <- Struct.mapM (\(Sized e) -> f e) val
return (LispU rval)
Size (_ ::: _) (_ ::: _) -> case lispValueType lv of
(sz' ::: szs,tps) -> do
vals <- unliftValue f lv
vals' <- mapM (unliftComp f) vals
return $ LispUArray sz' szs tps vals'
indexValue :: (Embed m e,Monad m,GetType e) => (forall t. e t -> Value t -> m p)
-> Value sz
-> LispValue '(sz ': szs,tps) e
-> m (p,LispValue '(szs,tps) e)
indexValue f idx (LispValue sz val) = do
(res,nsz) <- indexSize f idx sz
nval <- indexValue' f idx val
return (res,LispValue nsz nval)
where
indexSize :: (Embed m e,Monad m,GetType e) => (forall t. e t -> Value t -> m p)
-> Value sz -> Size e (sz ': szs)
-> m (p,Size e szs)
indexSize f n (Size (tp ::: tps) (sz ::: szs)) = do
res <- f sz n
nszs <- List.unmapM (sizeListType tps) szs (\arr -> do
n' <- constant n
select arr (n' ::: Nil))
return (res,Size tps nszs)
indexValue' :: (Embed m e,Monad m,GetType e) => (forall t. e t -> Value t -> m p)
-> Value sz
-> Struct (Sized e (sz ': szs)) tps
-> m (Struct (Sized e szs) tps)
indexValue' f n = Struct.mapM
(\(Sized x)
-> do
n' <- constant n
x' <- select x (n' ::: Nil)
return $ Sized x')
assignPartialLisp :: (Embed m e,Monad m,GetType e) => (forall t. e t -> Value t -> m p)
-> LispValue tps e -> LispPVal tps
-> m [Maybe p]
assignPartialLisp f (LispValue sz val) (LispP str) = assignStruct f val str
where
assignStruct :: (Embed m e,Monad m) => (forall t. e t -> Value t -> m p)
-> Struct (Sized e '[]) tps'
-> Struct PValue tps'
-> m [Maybe p]
assignStruct f (Singleton (Sized x)) (Singleton (PValue val)) = do
r <- f x val
return [Just r]
assignStruct _ _ (Singleton (NoPValue _)) = return [Nothing]
assignStruct f (Struct xs) (Struct ys) = assignStructs f xs ys
assignStructs :: (Embed m e,Monad m) => (forall t. e t -> Value t -> m p)
-> List (Struct (Sized e '[])) tps'
-> List (Struct PValue) tps'
-> m [Maybe p]
assignStructs _ Nil Nil = return []
assignStructs f (x ::: xs) (y ::: ys) = do
r1 <- assignStruct f x y
r2 <- assignStructs f xs ys
return $ r1++r2
assignPartialLisp f val (LispPArray sz xs) = do
lst <- mapM (\(x,n) -> do
(asgnSize,nval) <- indexValue f n val
rest <- assignPartialLisp f nval x
return (Just asgnSize:rest)
) (zip xs range)
return $ concat lst
where
len = lengthValue sz (genericLength xs)
range = sizeRange len
unmaskLispValue :: LispUVal tps -> LispPVal tps
unmaskLispValue (LispU xs) = LispP $ runIdentity $ Struct.mapM (return.PValue) xs
unmaskLispValue (LispUArray sz _ _ xs)
= LispPArray sz (fmap unmaskLispValue xs)
maskLispValue :: LispPVal tps -> [Bool] -> (LispPVal tps,[Bool])
maskLispValue (LispP str) xs = let (str',xs') = maskStruct str xs
in (LispP str',xs')
maskLispValue (LispPArray sz arr) xs
= let (xs',arr') = mapAccumL (\xs e -> let (e',xs') = maskLispValue e xs
in (xs',e')
) xs arr
in (LispPArray sz arr',xs')
maskStruct :: Struct PValue tps -> [Bool] -> (Struct PValue tps,[Bool])
maskStruct (Singleton (NoPValue tp)) (_:xs) = (Singleton (NoPValue tp),xs)
maskStruct (Singleton (PValue x)) (False:xs) = (Singleton (NoPValue (valueType x)),xs)
maskStruct (Singleton (PValue v)) (True:xs) = (Singleton (PValue v),xs)
maskStruct (Struct str) xs = let (str',xs') = maskStructs str xs
in (Struct str',xs')
maskStructs :: List (Struct PValue) tps' -> [Bool]
-> (List (Struct PValue) tps',[Bool])
maskStructs Nil xs = (Nil,xs)
maskStructs (y ::: ys) xs = let (y',xs1) = maskStruct y xs
(ys',xs2) = maskStructs ys xs1
in (y' ::: ys',xs2)
extractStruct :: Monad m => (forall t. e t -> m (Value t))
-> Struct (Sized e '[]) tps
-> m (Struct Value tps)
extractStruct f = Struct.mapM (\(Sized x) -> f x)
unliftValue :: (Embed m e,Monad m,GetType e) => (forall t. e t -> m (Value t))
-> LispValue '(sz ': szs,tps) e
-> m [LispValue '(szs,tps) e]
unliftValue f lv@(LispValue sz val) = case lispValueType lv of
(csz ::: szs,tps) -> do
nszs <- unliftSize f sz
nvals <- unliftStruct f csz nszs val
return $ zipWith LispValue nszs nvals
unliftStruct :: (Embed m e,Monad m,GetType e) => (forall t. e t -> m (Value t))
-> Repr sz
-> [Size e szs]
-> Struct (Sized e (sz ': szs)) tps
-> m [Struct (Sized e szs) tps]
unliftStruct f sz szs (Singleton (Sized x))
= mapM (\(idx,sz) -> do
idx' <- constant idx
el <- select x (idx' ::: Nil)
return $ Singleton (Sized el)
) (zip range szs)
where
len = lengthValue sz (genericLength szs)
range = sizeRange len
unliftStruct f sz szs (Struct vals) = do
vals' <- unliftStructs f sz szs vals
return $ fmap Struct vals'
unliftStructs :: (Embed m e,Monad m,GetType e)
=> (forall t. e t -> m (Value t))
-> Repr sz
-> [Size e szs]
-> List (Struct (Sized e (sz ': szs))) tps
-> m [List (Struct (Sized e szs)) tps]
unliftStructs f sz szs Nil = return $ fmap (const Nil) szs
unliftStructs f sz szs (x ::: xs) = do
x' <- unliftStruct f sz szs x
xs' <- unliftStructs f sz szs xs
return $ zipWith (:::) x' xs'
liftValues :: (Embed m e,Monad m,GetType e)
=> Repr sz
-> List Repr szs
-> Struct Repr tps
-> [LispValue '(szs,tps) e]
-> m (LispValue '(sz ': szs,tps) e)
liftValues sz szs tps xs = do
nsz <- liftSizes sz szs (fmap (\(LispValue sz _) -> sz) xs)
nval <- liftStructs sz szs tps (fmap (\(LispValue _ val) -> val) xs)
return $ LispValue nsz nval
liftStruct :: (Embed m e,Monad m,GetType e)
=> Struct Value tps
-> m (Struct (Sized e '[]) tps)
liftStruct = Struct.mapM (fmap Sized . constant)
liftStructs :: (Embed m e,Monad m,GetType e)
=> Repr sz
-> List Repr szs
-> Struct Repr tp
-> [Struct (Sized e szs) tp]
-> m (Struct (Sized e (sz ': szs)) tp)
liftStructs sz szs tp vals = case tp of
Singleton tp' -> fmap Singleton $ liftSized sz szs tp' (fmap (\(Singleton x) -> x) vals)
Struct tps -> fmap Struct (liftStructs' sz szs tps (fmap (\(Struct x) -> x) vals))
where
liftStructs' :: (Embed m e,Monad m,GetType e)
=> Repr sz
-> List Repr szs
-> List (Struct Repr) tps
-> [List (Struct (Sized e szs)) tps]
-> m (List (Struct (Sized e (sz ': szs))) tps)
liftStructs' sz szs Nil _ = return Nil
liftStructs' sz szs (tp ::: tps) vals = do
y <- liftStructs sz szs tp $ fmap (\(x ::: _) -> x) vals
ys <- liftStructs' sz szs tps $ fmap (\(_ ::: xs) -> xs) vals
return $ y ::: ys
| |
c229ca7ecd138e1b6591594121e4012b3a8bca98318d5d75208852ae3f26dd32 | mars0i/free | example_5.clj | This software is copyright 2016 by , and is distributed
under the Gnu General Public License version 3.0 as specified in the
;; the file LICENSE.
;; This example shows that
( a ) Sigma responds to changing error rates due to changing
;; causes (i.e. change in the mean of generated inputs), by
;; going up and down in response,
;; (b) Eventually settling in a region with a stable cycle
( c ) When change stops , sigma goes to zero ( or as low as we allow ) .
;; Here are command that will show this:
;; (use '[free.plots] :reload)
;; (require '[free.example-5 :as e] :reload)
( plot - level ( e / make - stages ) 1 300000 ) ; 300 K ticks
( plot - level ( e / make - stages ) 1 3500000 100 ) 3.5 M ticks , sampled every 100
To see what 's going on at the initial sensory level , replace 1 with 0 .
(ns free.example-5
(:require [free.level :as lvl]
will be clj or cljs depending on dialect
;; Generative function phi^2:
(defn gen [phi] (* phi phi)) ;; or: (lvl/m-square phi)
or : ( ar / m * phi 2 ) )
(def init-theta 1) ; i.e. initially pass value of gen(phi) through unchanged
;; next-bottom function
;; all this atom stuff is "bad", but is really just implementing a loop while allowing the function to be arg-less
(def change-every 20000) ; change in inputs every this many ticks
(def stop-changing-after 3000000)
(def change-ticks$ (atom (range change-every stop-changing-after change-every)))
(def means$ (atom (cycle [40 2]))) ; cycle between these means
(def mean$ (atom 2)) ; initial value of mean
(def sd 5) ; constant stddev
(def tick$ (atom 0)) ; timestep
(def next-bottom (lvl/make-next-bottom
(fn []
(when (and (first @change-ticks$) ; stop when sequence exhausted
(= (swap! tick$ inc) (first @change-ticks$)))
(reset! mean$ (first @means$))
(swap! change-ticks$ rest)
(swap! means$ rest))
SHOULD THIS BE FED INTO gen ?
controls degree of fluctuation in at level 1
(def error-u 0) ; epsilon
Note that the bottom - level needs to be an arbitrary number so that
epsilon - inc does n't NPE on the first tick , but the number does n't matter , and
;; it will immediately replaced when next-bottom is run.
;; middle level params
what phi is initialized to , and prior mean at top
controls how close to true value at level 1
(def error-p 0)
needs a number for epsilon - inc on 1st tick ; immediately replaced by next - bottom
:epsilon error-u
:sigma sigma-u
:theta init-theta
unused at bottom since epsilon update uses higher gen
unused at bottom since comes from outside
:phi-dt 0.01
:epsilon-dt 0.01
:sigma-dt 0.0
:theta-dt 0.0})
(def mid-map {:phi v-p
:epsilon error-p
:sigma sigma-p
:theta init-theta
:gen gen ; used to calc error at next level down, i.e. epsilon
used to update at this level
:phi-dt 0.0001
:epsilon-dt 0.01
:sigma-dt 0.0001
:theta-dt 0.00005})
(def init-bot (lvl/map->Level bot-map))
(def init-mid (lvl/map->Level mid-map))
(def init-mid-fixed-theta (lvl/map->Level (assoc mid-map :theta-dt 0.0)))
will have phi , and identity as : gen ; other fields nil
(defn make-stages [] (iterate (partial lvl/next-levels-3 next-bottom) [init-bot init-mid top]))
| null | https://raw.githubusercontent.com/mars0i/free/fe0fdc1c0bf1866cb07b4558a009a829f8d6ba23/src/clj/general/free/example_5.clj | clojure | the file LICENSE.
This example shows that
causes (i.e. change in the mean of generated inputs), by
going up and down in response,
(b) Eventually settling in a region with a stable cycle
Here are command that will show this:
(use '[free.plots] :reload)
(require '[free.example-5 :as e] :reload)
300 K ticks
Generative function phi^2:
or: (lvl/m-square phi)
i.e. initially pass value of gen(phi) through unchanged
next-bottom function
all this atom stuff is "bad", but is really just implementing a loop while allowing the function to be arg-less
change in inputs every this many ticks
cycle between these means
initial value of mean
constant stddev
timestep
stop when sequence exhausted
epsilon
it will immediately replaced when next-bottom is run.
middle level params
immediately replaced by next - bottom
used to calc error at next level down, i.e. epsilon
other fields nil | This software is copyright 2016 by , and is distributed
under the Gnu General Public License version 3.0 as specified in the
( a ) Sigma responds to changing error rates due to changing
( c ) When change stops , sigma goes to zero ( or as low as we allow ) .
( plot - level ( e / make - stages ) 1 3500000 100 ) 3.5 M ticks , sampled every 100
To see what 's going on at the initial sensory level , replace 1 with 0 .
(ns free.example-5
(:require [free.level :as lvl]
will be clj or cljs depending on dialect
or : ( ar / m * phi 2 ) )
(def stop-changing-after 3000000)
(def change-ticks$ (atom (range change-every stop-changing-after change-every)))
(def next-bottom (lvl/make-next-bottom
(fn []
(= (swap! tick$ inc) (first @change-ticks$)))
(reset! mean$ (first @means$))
(swap! change-ticks$ rest)
(swap! means$ rest))
SHOULD THIS BE FED INTO gen ?
controls degree of fluctuation in at level 1
Note that the bottom - level needs to be an arbitrary number so that
epsilon - inc does n't NPE on the first tick , but the number does n't matter , and
what phi is initialized to , and prior mean at top
controls how close to true value at level 1
(def error-p 0)
:epsilon error-u
:sigma sigma-u
:theta init-theta
unused at bottom since epsilon update uses higher gen
unused at bottom since comes from outside
:phi-dt 0.01
:epsilon-dt 0.01
:sigma-dt 0.0
:theta-dt 0.0})
(def mid-map {:phi v-p
:epsilon error-p
:sigma sigma-p
:theta init-theta
used to update at this level
:phi-dt 0.0001
:epsilon-dt 0.01
:sigma-dt 0.0001
:theta-dt 0.00005})
(def init-bot (lvl/map->Level bot-map))
(def init-mid (lvl/map->Level mid-map))
(def init-mid-fixed-theta (lvl/map->Level (assoc mid-map :theta-dt 0.0)))
(defn make-stages [] (iterate (partial lvl/next-levels-3 next-bottom) [init-bot init-mid top]))
|
a8e2bcaadf01459386bd35e48dbf5442a7407fc5a0dd24dd91d82a17fc30c542 | district0x/district-voting | countdown_timer.cljs | (ns district-voting.components.countdown-timer
(:require
[district-voting.styles :as styles]
[district0x.utils :as u]))
(defn countdown [time-remaining]
(let [{:keys [:seconds :minutes :hours :days :caption]} time-remaining]
[:h3
{:style (merge styles/full-width
styles/text-center
styles/margin-top-gutter-less)}
(if caption caption
"remaining ")
days " " (u/pluralize "day" days) " "
hours " " (u/pluralize "hour" hours) " "
minutes " " (u/pluralize "minute" minutes) " "
seconds " " (u/pluralize "second" seconds) " "]))
| null | https://raw.githubusercontent.com/district0x/district-voting/ef253671b00bdccec4575bcfa1b72b25e28afc22/src/cljs/district_voting/components/countdown_timer.cljs | clojure | (ns district-voting.components.countdown-timer
(:require
[district-voting.styles :as styles]
[district0x.utils :as u]))
(defn countdown [time-remaining]
(let [{:keys [:seconds :minutes :hours :days :caption]} time-remaining]
[:h3
{:style (merge styles/full-width
styles/text-center
styles/margin-top-gutter-less)}
(if caption caption
"remaining ")
days " " (u/pluralize "day" days) " "
hours " " (u/pluralize "hour" hours) " "
minutes " " (u/pluralize "minute" minutes) " "
seconds " " (u/pluralize "second" seconds) " "]))
| |
3b648cb0b76b2d0b876f5c94aaab12722a0d4c117b9691015135f2af3666d2d3 | JustusAdam/marvin | Internal.hs | |
Module : $ Header$
Description : Internal types for the slack adapter
Copyright : ( c ) , 2016
License : :
Stability : experimental
Portability : POSIX
See for documentation about this adapter .
The contents of this module are intended to provide access to internal functions and data structures for the slack adaper .
The use of this module is intended for advanced users .
No part of the API exposed here is to be consideres stable and may change unexpectedly .
Module : $Header$
Description : Internal types for the slack adapter
Copyright : (c) Justus Adam, 2016
License : BSD3
Maintainer :
Stability : experimental
Portability : POSIX
See #slack for documentation about this adapter.
The contents of this module are intended to provide access to internal functions and data structures for the slack adaper.
The use of this module is intended for advanced users.
No part of the API exposed here is to be consideres stable and may change unexpectedly.
-}
module Marvin.Adapter.Slack.Internal
( SlackUserId(..), SlackChannelId(..)
, MkSlack(..), SlackAdapter(..), InternalType(..)
, LimitedChannelInfo(..), ChannelCache(..), UserCache(..)
, UserInfo(..)
, HasTopic(..), HasIdValue(..), HasNameResolver(..), HasInfoCache(..), HasCreated(..)
) where
import Marvin.Adapter.Slack.Internal.Common
import Marvin.Adapter.Slack.Internal.Types
| null | https://raw.githubusercontent.com/JustusAdam/marvin/c49db1f7efbd5cc0803c9802ca31bb4488472ac3/src/Marvin/Adapter/Slack/Internal.hs | haskell | |
Module : $ Header$
Description : Internal types for the slack adapter
Copyright : ( c ) , 2016
License : :
Stability : experimental
Portability : POSIX
See for documentation about this adapter .
The contents of this module are intended to provide access to internal functions and data structures for the slack adaper .
The use of this module is intended for advanced users .
No part of the API exposed here is to be consideres stable and may change unexpectedly .
Module : $Header$
Description : Internal types for the slack adapter
Copyright : (c) Justus Adam, 2016
License : BSD3
Maintainer :
Stability : experimental
Portability : POSIX
See #slack for documentation about this adapter.
The contents of this module are intended to provide access to internal functions and data structures for the slack adaper.
The use of this module is intended for advanced users.
No part of the API exposed here is to be consideres stable and may change unexpectedly.
-}
module Marvin.Adapter.Slack.Internal
( SlackUserId(..), SlackChannelId(..)
, MkSlack(..), SlackAdapter(..), InternalType(..)
, LimitedChannelInfo(..), ChannelCache(..), UserCache(..)
, UserInfo(..)
, HasTopic(..), HasIdValue(..), HasNameResolver(..), HasInfoCache(..), HasCreated(..)
) where
import Marvin.Adapter.Slack.Internal.Common
import Marvin.Adapter.Slack.Internal.Types
| |
3b1aea5119c60260796f554d47143e80093b9e004f2733e8a3b9f0790edabd26 | ocaml/merlin | context.ml | { { { COPYING * (
This file is part of Merlin , an helper for ocaml editors
Copyright ( C ) 2013 - 2015 < frederic.bour(_)lakaban.net >
refis.thomas(_)gmail.com >
< simon.castellan(_)iuwt.fr >
Permission is hereby granted , free of charge , to any person obtaining a
copy of this software and associated documentation files ( the " Software " ) ,
to deal in the Software without restriction , including without limitation the
rights to use , copy , modify , merge , publish , distribute , sublicense , and/or
sell copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
The Software is provided " as is " , without warranty of any kind , express or
implied , including but not limited to the warranties of merchantability ,
fitness for a particular purpose and noninfringement . In no event shall
the authors or copyright holders be liable for any claim , damages or other
liability , whether in an action of contract , tort or otherwise , arising
from , out of or in connection with the software or the use or other dealings
in the Software .
) * } } }
This file is part of Merlin, an helper for ocaml editors
Copyright (C) 2013 - 2015 Frédéric Bour <frederic.bour(_)lakaban.net>
Thomas Refis <refis.thomas(_)gmail.com>
Simon Castellan <simon.castellan(_)iuwt.fr>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
The Software is provided "as is", without warranty of any kind, express or
implied, including but not limited to the warranties of merchantability,
fitness for a particular purpose and noninfringement. In no event shall
the authors or copyright holders be liable for any claim, damages or other
liability, whether in an action of contract, tort or otherwise, arising
from, out of or in connection with the software or the use or other dealings
in the Software.
)* }}} *)
open Std
let {Logger. log} = Logger.for_section "context"
type t =
| Constructor of Types.constructor_description * Location.t
We attach the constructor description here so in the case of
disambiguated constructors we actually directly look for the type
path ( cf . # 486 , # 794 ) .
disambiguated constructors we actually directly look for the type
path (cf. #486, #794). *)
| Expr
| Label of Types.label_description (* Similar to constructors. *)
| Module_path
| Module_type
| Patt
| Type
| Constant
| Unknown
let to_string = function
| Constructor (cd, _) -> Printf.sprintf "constructor %s" cd.cstr_name
| Expr -> "expression"
| Label lbl -> Printf.sprintf "record field %s" lbl.lbl_name
| Module_path -> "module path"
| Module_type -> "module type"
| Patt -> "pattern"
| Constant -> "constant"
| Type -> "type"
| Unknown -> "unknown"
Distinguish between " Mo[d]ule.something " and " Module.some[t]hing "
let cursor_on_longident_end
~cursor:cursor_pos
~lid_loc:{ Asttypes.loc; txt = lid }
name
=
match lid with
| Longident.Lident _ -> true
| _ ->
let end_offset = loc.loc_end.pos_cnum in
let cstr_name_size = String.length name in
let constr_pos =
{ loc.loc_end
with pos_cnum = end_offset - cstr_name_size }
in
Lexing.compare_pos cursor_pos constr_pos >= 0
let inspect_pattern (type a) ~cursor ~lid (p : a Typedtree.general_pattern) =
log ~title:"inspect_context" "%a" Logger.fmt
(fun fmt -> Format.fprintf fmt "current pattern is: %a"
(Printtyped.pattern 0) p);
match p.pat_desc with
| Tpat_any when Longident.last lid = "_" -> None
| Tpat_var (_, str_loc) when (Longident.last lid) = str_loc.txt ->
None
| Tpat_alias (_, _, str_loc)
when (Longident.last lid) = str_loc.txt ->
(* Assumption: if [Browse.enclosing] stopped on this node and not on the
subpattern, then it must mean that the cursor is on the alias. *)
None
| Tpat_construct (lid_loc, cd, _, _)
when cursor_on_longident_end ~cursor ~lid_loc cd.cstr_name
&& (Longident.last lid) = (Longident.last lid_loc.txt) ->
(* Assumption: if [Browse.enclosing] stopped on this node and not on the
subpattern, then it must mean that the cursor is on the constructor
itself. *)
Some (Constructor (cd, lid_loc.loc))
| Tpat_construct _ -> Some Module_path
| _ ->
Some Patt
let inspect_expression ~cursor ~lid e : t =
match e.Typedtree.exp_desc with
| Texp_construct (lid_loc, cd, _) ->
TODO : is this first test necessary ?
if (Longident.last lid) = (Longident.last lid_loc.txt) then
if cursor_on_longident_end ~cursor ~lid_loc cd.cstr_name then
Constructor (cd, lid_loc.loc)
else Module_path
else Module_path
| Texp_ident (p, lid_loc, _) ->
let name = Path.last p in
if name = "*type-error*" then
(* For type_enclosing: it is enough to return Module_path here.
- If the cursor was on the end of the lid typing should fail anyway
- If the cursor is on a segment of the path it should be typed ad a
Module_path
TODO: double check that this is correct-enough behavior for Locate *)
Module_path
else if cursor_on_longident_end ~cursor ~lid_loc name then
Expr
else
Module_path
| Texp_constant _ -> Constant
| _ ->
Expr
let inspect_browse_tree ~cursor lid browse : t option =
log ~title:"inspect_context" "current node is: [%s]"
(String.concat ~sep:"|" (
List.map ~f:(Mbrowse.print ()) browse
));
match Mbrowse.enclosing cursor browse with
| [] ->
log ~title:"inspect_context"
"no enclosing around: %a" Lexing.print_position cursor;
Some Unknown
| enclosings ->
let open Browse_raw in
let node = Browse_tree.of_browse enclosings in
log ~title:"inspect_context" "current enclosing node is: %s"
(string_of_node node.Browse_tree.t_node);
match node.Browse_tree.t_node with
| Pattern p -> inspect_pattern ~cursor ~lid p
| Value_description _
| Type_declaration _
| Extension_constructor _
| Module_binding_name _
| Module_declaration_name _ ->
None
| Module_expr _
| Open_description _ -> Some Module_path
| Module_type _ -> Some Module_type
| Core_type _ -> Some Type
| Record_field (_, lbl, _) when (Longident.last lid) = lbl.lbl_name ->
(* if we stopped here, then we're on the label itself, and whether or
not punning is happening is not important *)
Some (Label lbl)
| Expression e -> Some (inspect_expression ~cursor ~lid e)
| _ ->
Some Unknown
| null | https://raw.githubusercontent.com/ocaml/merlin/7607238326a9352cbee9ecf612669e28ae9fa36e/src/analysis/context.ml | ocaml | Similar to constructors.
Assumption: if [Browse.enclosing] stopped on this node and not on the
subpattern, then it must mean that the cursor is on the alias.
Assumption: if [Browse.enclosing] stopped on this node and not on the
subpattern, then it must mean that the cursor is on the constructor
itself.
For type_enclosing: it is enough to return Module_path here.
- If the cursor was on the end of the lid typing should fail anyway
- If the cursor is on a segment of the path it should be typed ad a
Module_path
TODO: double check that this is correct-enough behavior for Locate
if we stopped here, then we're on the label itself, and whether or
not punning is happening is not important | { { { COPYING * (
This file is part of Merlin , an helper for ocaml editors
Copyright ( C ) 2013 - 2015 < frederic.bour(_)lakaban.net >
refis.thomas(_)gmail.com >
< simon.castellan(_)iuwt.fr >
Permission is hereby granted , free of charge , to any person obtaining a
copy of this software and associated documentation files ( the " Software " ) ,
to deal in the Software without restriction , including without limitation the
rights to use , copy , modify , merge , publish , distribute , sublicense , and/or
sell copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
The Software is provided " as is " , without warranty of any kind , express or
implied , including but not limited to the warranties of merchantability ,
fitness for a particular purpose and noninfringement . In no event shall
the authors or copyright holders be liable for any claim , damages or other
liability , whether in an action of contract , tort or otherwise , arising
from , out of or in connection with the software or the use or other dealings
in the Software .
) * } } }
This file is part of Merlin, an helper for ocaml editors
Copyright (C) 2013 - 2015 Frédéric Bour <frederic.bour(_)lakaban.net>
Thomas Refis <refis.thomas(_)gmail.com>
Simon Castellan <simon.castellan(_)iuwt.fr>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
The Software is provided "as is", without warranty of any kind, express or
implied, including but not limited to the warranties of merchantability,
fitness for a particular purpose and noninfringement. In no event shall
the authors or copyright holders be liable for any claim, damages or other
liability, whether in an action of contract, tort or otherwise, arising
from, out of or in connection with the software or the use or other dealings
in the Software.
)* }}} *)
open Std
let {Logger. log} = Logger.for_section "context"
type t =
| Constructor of Types.constructor_description * Location.t
We attach the constructor description here so in the case of
disambiguated constructors we actually directly look for the type
path ( cf . # 486 , # 794 ) .
disambiguated constructors we actually directly look for the type
path (cf. #486, #794). *)
| Expr
| Module_path
| Module_type
| Patt
| Type
| Constant
| Unknown
let to_string = function
| Constructor (cd, _) -> Printf.sprintf "constructor %s" cd.cstr_name
| Expr -> "expression"
| Label lbl -> Printf.sprintf "record field %s" lbl.lbl_name
| Module_path -> "module path"
| Module_type -> "module type"
| Patt -> "pattern"
| Constant -> "constant"
| Type -> "type"
| Unknown -> "unknown"
Distinguish between " Mo[d]ule.something " and " Module.some[t]hing "
let cursor_on_longident_end
~cursor:cursor_pos
~lid_loc:{ Asttypes.loc; txt = lid }
name
=
match lid with
| Longident.Lident _ -> true
| _ ->
let end_offset = loc.loc_end.pos_cnum in
let cstr_name_size = String.length name in
let constr_pos =
{ loc.loc_end
with pos_cnum = end_offset - cstr_name_size }
in
Lexing.compare_pos cursor_pos constr_pos >= 0
let inspect_pattern (type a) ~cursor ~lid (p : a Typedtree.general_pattern) =
log ~title:"inspect_context" "%a" Logger.fmt
(fun fmt -> Format.fprintf fmt "current pattern is: %a"
(Printtyped.pattern 0) p);
match p.pat_desc with
| Tpat_any when Longident.last lid = "_" -> None
| Tpat_var (_, str_loc) when (Longident.last lid) = str_loc.txt ->
None
| Tpat_alias (_, _, str_loc)
when (Longident.last lid) = str_loc.txt ->
None
| Tpat_construct (lid_loc, cd, _, _)
when cursor_on_longident_end ~cursor ~lid_loc cd.cstr_name
&& (Longident.last lid) = (Longident.last lid_loc.txt) ->
Some (Constructor (cd, lid_loc.loc))
| Tpat_construct _ -> Some Module_path
| _ ->
Some Patt
let inspect_expression ~cursor ~lid e : t =
match e.Typedtree.exp_desc with
| Texp_construct (lid_loc, cd, _) ->
TODO : is this first test necessary ?
if (Longident.last lid) = (Longident.last lid_loc.txt) then
if cursor_on_longident_end ~cursor ~lid_loc cd.cstr_name then
Constructor (cd, lid_loc.loc)
else Module_path
else Module_path
| Texp_ident (p, lid_loc, _) ->
let name = Path.last p in
if name = "*type-error*" then
Module_path
else if cursor_on_longident_end ~cursor ~lid_loc name then
Expr
else
Module_path
| Texp_constant _ -> Constant
| _ ->
Expr
let inspect_browse_tree ~cursor lid browse : t option =
log ~title:"inspect_context" "current node is: [%s]"
(String.concat ~sep:"|" (
List.map ~f:(Mbrowse.print ()) browse
));
match Mbrowse.enclosing cursor browse with
| [] ->
log ~title:"inspect_context"
"no enclosing around: %a" Lexing.print_position cursor;
Some Unknown
| enclosings ->
let open Browse_raw in
let node = Browse_tree.of_browse enclosings in
log ~title:"inspect_context" "current enclosing node is: %s"
(string_of_node node.Browse_tree.t_node);
match node.Browse_tree.t_node with
| Pattern p -> inspect_pattern ~cursor ~lid p
| Value_description _
| Type_declaration _
| Extension_constructor _
| Module_binding_name _
| Module_declaration_name _ ->
None
| Module_expr _
| Open_description _ -> Some Module_path
| Module_type _ -> Some Module_type
| Core_type _ -> Some Type
| Record_field (_, lbl, _) when (Longident.last lid) = lbl.lbl_name ->
Some (Label lbl)
| Expression e -> Some (inspect_expression ~cursor ~lid e)
| _ ->
Some Unknown
|
ed51722359b986604097653ae2076d75be0ba05a71965e801b17642c8a138baf | juxt/site | repl.clj | Copyright © 2021 , JUXT LTD .
(ns juxt.site.alpha.repl
(:require
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.walk :refer [postwalk]]
[xtdb.api :as xt]
[crypto.password.bcrypt :as password]
[jsonista.core :as json]
[clojure.java.shell :as sh]
[io.aviso.ansi :as ansi]
[juxt.pass.alpha.authentication :as authn]
[juxt.site.alpha.graphql :as graphql]
[juxt.grab.alpha.schema :as graphql.schema]
[juxt.grab.alpha.document :as graphql.document]
[juxt.grab.alpha.parser :as graphql.parser]
[selmer.parser :as selmer]
[juxt.site.alpha.main :as main]
[juxt.site.alpha.handler :as handler]
[juxt.site.alpha.cache :as cache]
[juxt.site.alpha.init :as init]
[clojure.string :as str]
[juxt.grab.alpha.parser :as parser])
(:import (java.util Date)))
(alias 'dave (create-ns 'juxt.dave.alpha))
(alias 'http (create-ns 'juxt.http.alpha))
(alias 'pass (create-ns 'juxt.pass.alpha))
(alias 'site (create-ns 'juxt.site.alpha))
(defn base64-reader [form]
{:pre [(string? form)]}
(let [decoder (java.util.Base64/getDecoder)]
(.decode decoder form)))
(def edn-readers
{'juxt.site/base64 base64-reader
'regex #(re-pattern %)})
(defn config []
(main/config))
(defn system []
main/system)
(defn base-uri []
(::site/base-uri (config)))
(defn help []
(doseq [[_ v] (sort (ns-publics 'juxt.site.alpha.repl))
:let [m (meta v)]]
(println (format "%s %s: %s"
(:name m) (:arglists m) (:doc m))))
:ok)
(defn xt-node []
(:juxt.site.alpha.db/xt-node main/system))
(defn db []
(xt/db (xt-node)))
(defn e [id]
(postwalk
(fn [x] (if (and (vector? x)
(#{::http/content ::http/body} (first x))
(> (count (second x)) 1024))
[(first x)
(cond
(= ::http/content (first x)) (str (subs (second x) 0 80) "…")
:else (format "(%d bytes)" (count (second x))))]
x))
(xt/entity (db) id)))
(defn hist [id]
(xt/entity-history (db) id :asc {:with-docs? true}))
(defn valid-time [id] (:xtdb.api/valid-time (xt/entity-tx (db) id)))
(defn put! [& ms]
(->>
(xt/submit-tx
(xt-node)
(for [m ms]
(let [vt (:xtdb.api/valid-time m)]
[:xtdb.api/put (dissoc m :xtdb.api/valid-time) vt])))
(xt/await-tx (xt-node))))
(defn grep [re coll]
(filter #(re-matches (re-pattern re) %) coll))
(defn rm! [& ids]
(->>
(xt/submit-tx
(xt-node)
(for [id ids]
[:xtdb.api/delete id]))
(xt/await-tx (xt-node))))
(defn evict! [& ids]
(->>
(xt/submit-tx
(xt-node)
(for [id ids]
[:xtdb.api/evict id]))
(xt/await-tx (xt-node))))
(defn q [query & args]
(apply xt/q (db) query args))
(defn t [t]
(map
first
(xt/q (db) '{:find [e] :where [[e ::site/type t]] :in [t]} t)))
(defn t* [t]
(map
first
(xt/q (db) '{:find [e] :where [[e :type t]] :in [t]} t)))
(defn types []
(->> (q '{:find [t]
:where [[_ ::site/type t]]})
(map first)
(sort)))
(defn ls
"List Site resources"
([]
(->> (q '{:find [(pull e [:xt/id ::site/type])]
:where [[e :xt/id]]})
(map first)
(filter #(not= (::site/type %) "Request"))
(map :xt/id)
(sort-by str)))
([pat]
(->> (q '{:find [e]
:where [[e :xt/id]
[(str e) id]
[(re-seq pat id) match]
[(some? match)]]
:in [pat]}
(re-pattern pat))
(map first)
(sort-by str))))
(defn ls-type
[t]
(->> (q '{:find [e]
:where [[e :xt/id]
[e ::site/type t]]
:in [t]} t)
(map first)
(sort)))
(defn now-id []
(.format
(.withZone
(java.time.format.DateTimeFormatter/ofPattern "yyyy-MM-dd-HHmmss")
(java.time.ZoneId/systemDefault))
(java.time.Instant/now)))
Start import at 00:35
(defn resources-from-stream [in]
(let [record (try
(edn/read
{:eof :eof :readers edn-readers}
in)
(catch Exception e
(def in in)
(prn (.getMessage e))))]
(cond
(nil? record)
(lazy-seq (resources-from-stream in))
(not= record :eof)
(cons record (lazy-seq (resources-from-stream in)))
:else
nil)))
(defn- submit-and-wait-tx
[node tx]
(let [tx-id (xt/submit-tx node tx)]
(xt/await-tx node tx-id)))
(defn import-resources
([] (import-resources "import/resources.edn"))
([filename]
(let [node (xt-node)
in (java.io.PushbackReader. (io/reader (io/input-stream (io/file filename))))]
(doseq [rec (resources-from-stream in)]
(when (:xt/id rec)
(if (xt/entity (xt/db node) (:xt/id rec))
(println "Skipping existing resource: " (:xt/id rec))
(do
(submit-and-wait-tx node [[:xtdb.api/put rec]])
(println "Imported resource: " (:xt/id rec)))))))))
(defn validate-resource-line [s]
(edn/read-string
{:eof :eof :readers edn-readers}
s))
(defn get-zipped-output-stream []
(let [zos (doto
(-> (str (now-id) ".edn.zip")
io/file
io/output-stream
java.util.zip.ZipOutputStream.)
(.putNextEntry (java.util.zip.ZipEntry. "resources.edn")))]
(java.io.OutputStreamWriter. zos)))
(defn apply-uri-mappings [mapping]
(fn [ent]
;; Create a regex pattern which detects anything as a mapping key
(let [pat (re-pattern (str/join "|" (map #(format "\\Q%s\\E" %) (keys mapping))))]
(postwalk
(fn [s]
(cond-> s
(string? s)
(str/replace pat (fn [x] (get mapping x)))))
ent))))
(comment
(export-resources
{:pred (fn [x] (or (= (:juxt.home/type x) "Person")))
:filename "/home/mal/Sync/persons.edn"
:uri-mapping {":2021"
""}}))
(defn export-resources
"Export all resources to a file."
([]
(export-resources {}))
([{:keys [out pred filename uri-mapping]}]
(let [out (or out
(when filename (io/output-stream (io/file filename)))
(get-zipped-output-stream))
pred (or pred some?)
encoder (java.util.Base64/getEncoder)
resources
(cond->> (q '{:find [(pull e [*])]
:where [[e :xt/id]]})
true (map first)
true (filter #(not= (::site/type %) "Request"))
pred (filter pred)
uri-mapping (map (apply-uri-mappings uri-mapping))
true (sort-by :xt/id))]
(defmethod print-method (type (byte-array [])) [x writer]
(.write writer "#juxt.site/base64")
(.write writer (str " \"" (String. (.encode encoder x)) "\"")))
(with-open [w (io/writer out)]
(doseq [batch (partition-all 100 (map vector (range) resources))]
(doseq [[_ ent] batch]
(let [line (pr-str ent)]
;; Test the line can be read
#_(try
(validate-resource-line line)
(catch Exception e
(throw
(ex-info
(format "Serialization of entity '%s' will not be readable" (:xt/id ent))
{:xt/id (:xt/id ent)} e))))
(.write w line)
(.write w (System/lineSeparator))))
(let [n (inc (first (last batch)))
total (count resources)
pct (float (/ (* 100 n) total))]
(printf "Written %d/%d (%.2f%%) resources\n" n total pct))))
(remove-method print-method (type (byte-array [])))
(printf "Dumped %d resources\n" (count resources)))))
(defn cat-type
[t]
(->> (q '{:find [(pull e [*])]
:where [[e :xt/id]
[e ::site/type t]]
:in [t]} t)
(map first)
(sort-by str)))
(defn rules []
(sort-by
str
(map first
(q '{:find [(pull e [*])] :where [[e ::site/type "Rule"]]}))))
(defn uuid
([] (str (java.util.UUID/randomUUID)))
([s]
(cond
(string? s) (java.util.UUID/fromString s)
(uuid? s) s)))
(defn req [s]
(into
(sorted-map)
(cache/find
cache/requests-cache
(re-pattern (str "/_site/requests/" s)))))
(defn recent
([] (recent 5))
([n]
(map (juxt ::site/request-id ::site/date ::site/uri :ring.request/method :ring.response/status)
(cache/recent cache/requests-cache n))
))
(defn requests-cache []
cache/requests-cache)
(defn gc
"Remove request data that is older than an hour."
([] (gc (* 1 60 60)))
([seconds]
(let [records (map first
(q '{:find [e]
:where [[e ::site/type "Request"]
[e ::site/end-date ended]
[(< ended checkpoint)]]
:in [checkpoint]}
(Date. (- (.getTime (Date.)) (* seconds 1000)))))]
(doseq [batch (partition-all 100 records)]
(println "Evicting" (count batch) "records")
(println (apply evict! batch))))))
(defn sessions []
(authn/expire-sessions! (java.util.Date.))
(deref authn/sessions-by-access-token))
(defn clear-sessions []
(reset! authn/sessions-by-access-token {}))
(defn superusers
([] (superusers (config)))
([{::site/keys [base-uri]}]
(map first
(xt/q (db) '{:find [user]
:where [[user ::site/type "User"]
[mapping ::site/type "UserRoleMapping"]
[mapping ::pass/assignee user]
[mapping ::pass/role superuser]]
:in [superuser]}
(str base-uri "/_site/roles/superuser")))))
(defn steps
([] (steps (config)))
([opts]
(let [{::site/keys [base-uri]} opts
_ (assert base-uri)
db (xt/db (xt-node))]
[;; Awaiting a fix to
#_{:complete? (and
(xt/entity db (str base-uri "/_site/tx_fns/put_if_match_wildcard"))
(xt/entity db (str base-uri "/_site/tx_fns/put_if_match_etags")))
:happy-message "Site transaction functions installed."
:sad-message "Site transaction functions not installed. "
:fix "Enter (put-site-txfns!) to fix this."}
{:complete? (xt/entity db (str base-uri "/_site/apis/site/openapi.json"))
:happy-message "Site API resources installed."
:sad-message "Site API not installed. "
:fix "Enter (put-site-api!) to fix this."}
{:complete? (xt/entity db (str base-uri "/_site/token"))
:happy-message "Authentication resources installed."
:sad-message "Authentication resources not installed. "
:fix "Enter (put-auth-resources!) to fix this."}
{:complete? (xt/entity db (str base-uri "/_site/roles/superuser"))
:happy-message "Role of superuser exists."
:sad-message "Role of superuser not yet created."
:fix "Enter (put-superuser-role!) to fix this."}
{:complete? (pos? (count (superusers opts)))
:happy-message "At least one superuser exists."
:sad-message "No superusers exist."
:fix "Enter (put-superuser! <username> <fullname>) or (put-superuser! <username> <fullname> <password>) to fix this."}])))
(defn status
([] (status (steps (config))))
([steps]
(println)
(doseq [{:keys [complete? happy-message sad-message fix]} steps]
(if complete?
(println "[✔] " (ansi/green happy-message))
(println
"[ ] "
(ansi/red sad-message)
(ansi/yellow fix))))
(println)
(if (every? :complete? steps) :ok :incomplete)))
(defn put-site-api! []
(let [config (config)
xt-node (xt-node)]
(init/put-site-api! xt-node config)
(status (steps config))))
(defn put-auth-resources! []
(let [config (config)
xt-node (xt-node)]
(init/put-openid-token-endpoint! xt-node config)
(init/put-login-endpoint! xt-node config)
(init/put-logout-endpoint! xt-node config)
(status (steps config))))
(defn put-superuser-role! []
(let [config (config)
xt-node (xt-node)]
(init/put-superuser-role! xt-node config)
(status (steps config))))
(defn get-password [pass-name]
(println "Getting password" pass-name)
(let [{:keys [exit out err]} (sh/sh "pass" "show" pass-name)]
(if (zero? exit) (str/trim out) (println (ansi/red "Failed to get password")))))
(defn put-superuser!
([username fullname]
(if-let [password-prefix (:juxt.site.alpha.unix-pass/password-prefix (config))]
(if-let [password (get-password (str password-prefix username))]
(put-superuser! username fullname password)
(println (ansi/red "Failed to get password")))
(println (ansi/red "Password required!"))))
([username fullname password]
(let [config (config)
xt-node (xt-node)]
(init/put-superuser!
xt-node
{:username username
:fullname fullname
:password password}
config)
(status (steps config)))))
(defn update-site-graphql
[]
(init/put-graphql-schema-endpoint! (xt-node) (config)))
(defn init!
[username password]
(let [xt-node (xt-node)
config (config)]
(put-site-api!)
(put-auth-resources!)
(put-superuser-role!)
(put-superuser! username "Administrator" password)
(init/put-graphql-operations! xt-node config)
(init/put-graphql-schema-endpoint! xt-node config)
(init/put-request-template! xt-node config)))
(defn allow-public-access-to-public-resources! []
(let [config (config)
xt-node (xt-node)]
(init/allow-public-access-to-public-resources! xt-node config)))
(defn put-site-txfns! []
(let [config (config)
xt-node (xt-node)]
(init/put-site-txfns! xt-node config)
(status)))
(defn reset-password! [username password]
(let [user (str (::site/base-uri (config)) "/_site/users/" username)]
(put!
{:xt/id (str user "/password")
::site/type "Password"
::http/methods #{:post}
::pass/user user
::pass/password-hash (password/encrypt password)
::pass/classification "RESTRICTED"})))
(defn user [username]
(e (format "%s/_site/users/%s" (::site/base-uri (config)) username)))
(defn user-apps [username]
(q '{:find [(pull application [*])]
:keys [app]
:where [[grant :juxt.site.alpha/type "Grant"]
[subject :juxt.pass.alpha/user user]
[user :juxt.pass.alpha/username username]
[grant :juxt.pass.alpha/user user]
[grant :juxt.pass.alpha/permission permission]
[permission :juxt.site.alpha/application application]]
:in [username]}
username))
(defn introspect-graphql []
(let [config (config)
schema (:juxt.grab.alpha/schema (e (format "%s/_site/graphql" (::site/base-uri config))))
document (graphql.document/compile-document (graphql.parser/parse (slurp (io/file "opt/graphql/graphiql-introspection-query.graphql"))) schema)]
(graphql/query schema document "IntrospectionQuery" {} {::site/db (db)})))
| null | https://raw.githubusercontent.com/juxt/site/222ca9bda164fdb6bde621959536e3af5f85c410/src/juxt/site/alpha/repl.clj | clojure | Create a regex pattern which detects anything as a mapping key
Test the line can be read
Awaiting a fix to | Copyright © 2021 , JUXT LTD .
(ns juxt.site.alpha.repl
(:require
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.walk :refer [postwalk]]
[xtdb.api :as xt]
[crypto.password.bcrypt :as password]
[jsonista.core :as json]
[clojure.java.shell :as sh]
[io.aviso.ansi :as ansi]
[juxt.pass.alpha.authentication :as authn]
[juxt.site.alpha.graphql :as graphql]
[juxt.grab.alpha.schema :as graphql.schema]
[juxt.grab.alpha.document :as graphql.document]
[juxt.grab.alpha.parser :as graphql.parser]
[selmer.parser :as selmer]
[juxt.site.alpha.main :as main]
[juxt.site.alpha.handler :as handler]
[juxt.site.alpha.cache :as cache]
[juxt.site.alpha.init :as init]
[clojure.string :as str]
[juxt.grab.alpha.parser :as parser])
(:import (java.util Date)))
(alias 'dave (create-ns 'juxt.dave.alpha))
(alias 'http (create-ns 'juxt.http.alpha))
(alias 'pass (create-ns 'juxt.pass.alpha))
(alias 'site (create-ns 'juxt.site.alpha))
(defn base64-reader [form]
{:pre [(string? form)]}
(let [decoder (java.util.Base64/getDecoder)]
(.decode decoder form)))
(def edn-readers
{'juxt.site/base64 base64-reader
'regex #(re-pattern %)})
(defn config []
(main/config))
(defn system []
main/system)
(defn base-uri []
(::site/base-uri (config)))
(defn help []
(doseq [[_ v] (sort (ns-publics 'juxt.site.alpha.repl))
:let [m (meta v)]]
(println (format "%s %s: %s"
(:name m) (:arglists m) (:doc m))))
:ok)
(defn xt-node []
(:juxt.site.alpha.db/xt-node main/system))
(defn db []
(xt/db (xt-node)))
(defn e [id]
(postwalk
(fn [x] (if (and (vector? x)
(#{::http/content ::http/body} (first x))
(> (count (second x)) 1024))
[(first x)
(cond
(= ::http/content (first x)) (str (subs (second x) 0 80) "…")
:else (format "(%d bytes)" (count (second x))))]
x))
(xt/entity (db) id)))
(defn hist [id]
(xt/entity-history (db) id :asc {:with-docs? true}))
(defn valid-time [id] (:xtdb.api/valid-time (xt/entity-tx (db) id)))
(defn put! [& ms]
(->>
(xt/submit-tx
(xt-node)
(for [m ms]
(let [vt (:xtdb.api/valid-time m)]
[:xtdb.api/put (dissoc m :xtdb.api/valid-time) vt])))
(xt/await-tx (xt-node))))
(defn grep [re coll]
(filter #(re-matches (re-pattern re) %) coll))
(defn rm! [& ids]
(->>
(xt/submit-tx
(xt-node)
(for [id ids]
[:xtdb.api/delete id]))
(xt/await-tx (xt-node))))
(defn evict! [& ids]
(->>
(xt/submit-tx
(xt-node)
(for [id ids]
[:xtdb.api/evict id]))
(xt/await-tx (xt-node))))
(defn q [query & args]
(apply xt/q (db) query args))
(defn t [t]
(map
first
(xt/q (db) '{:find [e] :where [[e ::site/type t]] :in [t]} t)))
(defn t* [t]
(map
first
(xt/q (db) '{:find [e] :where [[e :type t]] :in [t]} t)))
(defn types []
(->> (q '{:find [t]
:where [[_ ::site/type t]]})
(map first)
(sort)))
(defn ls
"List Site resources"
([]
(->> (q '{:find [(pull e [:xt/id ::site/type])]
:where [[e :xt/id]]})
(map first)
(filter #(not= (::site/type %) "Request"))
(map :xt/id)
(sort-by str)))
([pat]
(->> (q '{:find [e]
:where [[e :xt/id]
[(str e) id]
[(re-seq pat id) match]
[(some? match)]]
:in [pat]}
(re-pattern pat))
(map first)
(sort-by str))))
(defn ls-type
[t]
(->> (q '{:find [e]
:where [[e :xt/id]
[e ::site/type t]]
:in [t]} t)
(map first)
(sort)))
(defn now-id []
(.format
(.withZone
(java.time.format.DateTimeFormatter/ofPattern "yyyy-MM-dd-HHmmss")
(java.time.ZoneId/systemDefault))
(java.time.Instant/now)))
Start import at 00:35
(defn resources-from-stream [in]
(let [record (try
(edn/read
{:eof :eof :readers edn-readers}
in)
(catch Exception e
(def in in)
(prn (.getMessage e))))]
(cond
(nil? record)
(lazy-seq (resources-from-stream in))
(not= record :eof)
(cons record (lazy-seq (resources-from-stream in)))
:else
nil)))
(defn- submit-and-wait-tx
[node tx]
(let [tx-id (xt/submit-tx node tx)]
(xt/await-tx node tx-id)))
(defn import-resources
([] (import-resources "import/resources.edn"))
([filename]
(let [node (xt-node)
in (java.io.PushbackReader. (io/reader (io/input-stream (io/file filename))))]
(doseq [rec (resources-from-stream in)]
(when (:xt/id rec)
(if (xt/entity (xt/db node) (:xt/id rec))
(println "Skipping existing resource: " (:xt/id rec))
(do
(submit-and-wait-tx node [[:xtdb.api/put rec]])
(println "Imported resource: " (:xt/id rec)))))))))
(defn validate-resource-line [s]
(edn/read-string
{:eof :eof :readers edn-readers}
s))
(defn get-zipped-output-stream []
(let [zos (doto
(-> (str (now-id) ".edn.zip")
io/file
io/output-stream
java.util.zip.ZipOutputStream.)
(.putNextEntry (java.util.zip.ZipEntry. "resources.edn")))]
(java.io.OutputStreamWriter. zos)))
(defn apply-uri-mappings [mapping]
(fn [ent]
(let [pat (re-pattern (str/join "|" (map #(format "\\Q%s\\E" %) (keys mapping))))]
(postwalk
(fn [s]
(cond-> s
(string? s)
(str/replace pat (fn [x] (get mapping x)))))
ent))))
(comment
(export-resources
{:pred (fn [x] (or (= (:juxt.home/type x) "Person")))
:filename "/home/mal/Sync/persons.edn"
:uri-mapping {":2021"
""}}))
(defn export-resources
"Export all resources to a file."
([]
(export-resources {}))
([{:keys [out pred filename uri-mapping]}]
(let [out (or out
(when filename (io/output-stream (io/file filename)))
(get-zipped-output-stream))
pred (or pred some?)
encoder (java.util.Base64/getEncoder)
resources
(cond->> (q '{:find [(pull e [*])]
:where [[e :xt/id]]})
true (map first)
true (filter #(not= (::site/type %) "Request"))
pred (filter pred)
uri-mapping (map (apply-uri-mappings uri-mapping))
true (sort-by :xt/id))]
(defmethod print-method (type (byte-array [])) [x writer]
(.write writer "#juxt.site/base64")
(.write writer (str " \"" (String. (.encode encoder x)) "\"")))
(with-open [w (io/writer out)]
(doseq [batch (partition-all 100 (map vector (range) resources))]
(doseq [[_ ent] batch]
(let [line (pr-str ent)]
#_(try
(validate-resource-line line)
(catch Exception e
(throw
(ex-info
(format "Serialization of entity '%s' will not be readable" (:xt/id ent))
{:xt/id (:xt/id ent)} e))))
(.write w line)
(.write w (System/lineSeparator))))
(let [n (inc (first (last batch)))
total (count resources)
pct (float (/ (* 100 n) total))]
(printf "Written %d/%d (%.2f%%) resources\n" n total pct))))
(remove-method print-method (type (byte-array [])))
(printf "Dumped %d resources\n" (count resources)))))
(defn cat-type
[t]
(->> (q '{:find [(pull e [*])]
:where [[e :xt/id]
[e ::site/type t]]
:in [t]} t)
(map first)
(sort-by str)))
(defn rules []
(sort-by
str
(map first
(q '{:find [(pull e [*])] :where [[e ::site/type "Rule"]]}))))
(defn uuid
([] (str (java.util.UUID/randomUUID)))
([s]
(cond
(string? s) (java.util.UUID/fromString s)
(uuid? s) s)))
(defn req [s]
(into
(sorted-map)
(cache/find
cache/requests-cache
(re-pattern (str "/_site/requests/" s)))))
(defn recent
([] (recent 5))
([n]
(map (juxt ::site/request-id ::site/date ::site/uri :ring.request/method :ring.response/status)
(cache/recent cache/requests-cache n))
))
(defn requests-cache []
cache/requests-cache)
(defn gc
"Remove request data that is older than an hour."
([] (gc (* 1 60 60)))
([seconds]
(let [records (map first
(q '{:find [e]
:where [[e ::site/type "Request"]
[e ::site/end-date ended]
[(< ended checkpoint)]]
:in [checkpoint]}
(Date. (- (.getTime (Date.)) (* seconds 1000)))))]
(doseq [batch (partition-all 100 records)]
(println "Evicting" (count batch) "records")
(println (apply evict! batch))))))
(defn sessions []
(authn/expire-sessions! (java.util.Date.))
(deref authn/sessions-by-access-token))
(defn clear-sessions []
(reset! authn/sessions-by-access-token {}))
(defn superusers
([] (superusers (config)))
([{::site/keys [base-uri]}]
(map first
(xt/q (db) '{:find [user]
:where [[user ::site/type "User"]
[mapping ::site/type "UserRoleMapping"]
[mapping ::pass/assignee user]
[mapping ::pass/role superuser]]
:in [superuser]}
(str base-uri "/_site/roles/superuser")))))
(defn steps
([] (steps (config)))
([opts]
(let [{::site/keys [base-uri]} opts
_ (assert base-uri)
db (xt/db (xt-node))]
#_{:complete? (and
(xt/entity db (str base-uri "/_site/tx_fns/put_if_match_wildcard"))
(xt/entity db (str base-uri "/_site/tx_fns/put_if_match_etags")))
:happy-message "Site transaction functions installed."
:sad-message "Site transaction functions not installed. "
:fix "Enter (put-site-txfns!) to fix this."}
{:complete? (xt/entity db (str base-uri "/_site/apis/site/openapi.json"))
:happy-message "Site API resources installed."
:sad-message "Site API not installed. "
:fix "Enter (put-site-api!) to fix this."}
{:complete? (xt/entity db (str base-uri "/_site/token"))
:happy-message "Authentication resources installed."
:sad-message "Authentication resources not installed. "
:fix "Enter (put-auth-resources!) to fix this."}
{:complete? (xt/entity db (str base-uri "/_site/roles/superuser"))
:happy-message "Role of superuser exists."
:sad-message "Role of superuser not yet created."
:fix "Enter (put-superuser-role!) to fix this."}
{:complete? (pos? (count (superusers opts)))
:happy-message "At least one superuser exists."
:sad-message "No superusers exist."
:fix "Enter (put-superuser! <username> <fullname>) or (put-superuser! <username> <fullname> <password>) to fix this."}])))
(defn status
([] (status (steps (config))))
([steps]
(println)
(doseq [{:keys [complete? happy-message sad-message fix]} steps]
(if complete?
(println "[✔] " (ansi/green happy-message))
(println
"[ ] "
(ansi/red sad-message)
(ansi/yellow fix))))
(println)
(if (every? :complete? steps) :ok :incomplete)))
(defn put-site-api! []
(let [config (config)
xt-node (xt-node)]
(init/put-site-api! xt-node config)
(status (steps config))))
(defn put-auth-resources! []
(let [config (config)
xt-node (xt-node)]
(init/put-openid-token-endpoint! xt-node config)
(init/put-login-endpoint! xt-node config)
(init/put-logout-endpoint! xt-node config)
(status (steps config))))
(defn put-superuser-role! []
(let [config (config)
xt-node (xt-node)]
(init/put-superuser-role! xt-node config)
(status (steps config))))
(defn get-password [pass-name]
(println "Getting password" pass-name)
(let [{:keys [exit out err]} (sh/sh "pass" "show" pass-name)]
(if (zero? exit) (str/trim out) (println (ansi/red "Failed to get password")))))
(defn put-superuser!
([username fullname]
(if-let [password-prefix (:juxt.site.alpha.unix-pass/password-prefix (config))]
(if-let [password (get-password (str password-prefix username))]
(put-superuser! username fullname password)
(println (ansi/red "Failed to get password")))
(println (ansi/red "Password required!"))))
([username fullname password]
(let [config (config)
xt-node (xt-node)]
(init/put-superuser!
xt-node
{:username username
:fullname fullname
:password password}
config)
(status (steps config)))))
(defn update-site-graphql
[]
(init/put-graphql-schema-endpoint! (xt-node) (config)))
(defn init!
[username password]
(let [xt-node (xt-node)
config (config)]
(put-site-api!)
(put-auth-resources!)
(put-superuser-role!)
(put-superuser! username "Administrator" password)
(init/put-graphql-operations! xt-node config)
(init/put-graphql-schema-endpoint! xt-node config)
(init/put-request-template! xt-node config)))
(defn allow-public-access-to-public-resources! []
(let [config (config)
xt-node (xt-node)]
(init/allow-public-access-to-public-resources! xt-node config)))
(defn put-site-txfns! []
(let [config (config)
xt-node (xt-node)]
(init/put-site-txfns! xt-node config)
(status)))
(defn reset-password! [username password]
(let [user (str (::site/base-uri (config)) "/_site/users/" username)]
(put!
{:xt/id (str user "/password")
::site/type "Password"
::http/methods #{:post}
::pass/user user
::pass/password-hash (password/encrypt password)
::pass/classification "RESTRICTED"})))
(defn user [username]
(e (format "%s/_site/users/%s" (::site/base-uri (config)) username)))
(defn user-apps [username]
(q '{:find [(pull application [*])]
:keys [app]
:where [[grant :juxt.site.alpha/type "Grant"]
[subject :juxt.pass.alpha/user user]
[user :juxt.pass.alpha/username username]
[grant :juxt.pass.alpha/user user]
[grant :juxt.pass.alpha/permission permission]
[permission :juxt.site.alpha/application application]]
:in [username]}
username))
(defn introspect-graphql []
(let [config (config)
schema (:juxt.grab.alpha/schema (e (format "%s/_site/graphql" (::site/base-uri config))))
document (graphql.document/compile-document (graphql.parser/parse (slurp (io/file "opt/graphql/graphiql-introspection-query.graphql"))) schema)]
(graphql/query schema document "IntrospectionQuery" {} {::site/db (db)})))
|
887968d94e3542dd3ad47ee0a46c724755d04fa5989a7efa4241cbe253cdc6df | herbelin/coq-hh | evd.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Pp
open Util
open Names
open Nameops
open Term
open Termops
open Sign
open Environ
open Libnames
open Mod_subst
(* The kinds of existential variable *)
type obligation_definition_status = Define of bool | Expand
type hole_kind =
| ImplicitArg of global_reference * (int * identifier option) * bool
| BinderType of name
| QuestionMark of obligation_definition_status
| CasesType
| InternalHole
| TomatchTypeParameter of inductive * int
| GoalEvar
| ImpossibleCase
| MatchingVar of bool * identifier
(* The type of mappings for existential variables *)
type evar = existential_key
let string_of_existential evk = "?" ^ string_of_int evk
let existential_of_int evk = evk
type evar_body =
| Evar_empty
| Evar_defined of constr
type evar_info = {
evar_concl : constr;
evar_hyps : named_context_val;
evar_body : evar_body;
evar_filter : bool list;
evar_source : hole_kind located;
evar_extra : Store.t }
let make_evar hyps ccl = {
evar_concl = ccl;
evar_hyps = hyps;
evar_body = Evar_empty;
evar_filter = List.map (fun _ -> true) (named_context_of_val hyps);
evar_source = (dummy_loc,InternalHole);
evar_extra = Store.empty
}
let evar_concl evi = evi.evar_concl
let evar_hyps evi = evi.evar_hyps
let evar_context evi = named_context_of_val evi.evar_hyps
let evar_body evi = evi.evar_body
let evar_filter evi = evi.evar_filter
let evar_unfiltered_env evi = Global.env_of_context evi.evar_hyps
let evar_filtered_context evi =
snd (list_filter2 (fun b c -> b) (evar_filter evi,evar_context evi))
let evar_env evi =
List.fold_right push_named (evar_filtered_context evi)
(reset_context (Global.env()))
let eq_evar_info ei1 ei2 =
ei1 == ei2 ||
eq_constr ei1.evar_concl ei2.evar_concl &&
eq_named_context_val (ei1.evar_hyps) (ei2.evar_hyps) &&
ei1.evar_body = ei2.evar_body
spiwack : Revised hierarchy :
- ExistentialMap ( Maps of existential_keys )
- EvarInfoMap ( .t = evar_info ExistentialMap.t * evar_info ExistentialMap )
- EvarMap ( .t = EvarInfoMap.t * sort_constraints )
- evar_map ( exported )
- ExistentialMap ( Maps of existential_keys )
- EvarInfoMap ( .t = evar_info ExistentialMap.t * evar_info ExistentialMap )
- EvarMap ( .t = EvarInfoMap.t * sort_constraints )
- evar_map (exported)
*)
module ExistentialMap = Intmap
module ExistentialSet = Intset
(* This exception is raised by *.existential_value *)
exception NotInstantiatedEvar
module EvarInfoMap = struct
type t = evar_info ExistentialMap.t * evar_info ExistentialMap.t
let empty = ExistentialMap.empty, ExistentialMap.empty
let to_list (def,undef) =
Workaround for change in Map.fold behavior in ocaml 3.08.4
let l = ref [] in
ExistentialMap.iter (fun evk x -> l := (evk,x)::!l) def;
ExistentialMap.iter (fun evk x -> l := (evk,x)::!l) undef;
!l
let undefined_list (def,undef) =
Order is important : needs ocaml > = 3.08.4 from which " fold " is a
" fold_left "
"fold_left" *)
ExistentialMap.fold (fun evk evi l -> (evk,evi)::l) undef []
let undefined_evars (def,undef) = (ExistentialMap.empty,undef)
let find (def,undef) k =
try ExistentialMap.find k def
with Not_found -> ExistentialMap.find k undef
let find_undefined (def,undef) k = ExistentialMap.find k undef
let remove (def,undef) k =
(ExistentialMap.remove k def,ExistentialMap.remove k undef)
let mem (def,undef) k =
ExistentialMap.mem k def || ExistentialMap.mem k undef
let fold (def,undef) f a =
ExistentialMap.fold f def (ExistentialMap.fold f undef a)
let fold_undefined (def,undef) f a =
ExistentialMap.fold f undef a
let exists_undefined (def,undef) f =
ExistentialMap.fold (fun k v b -> b || f k v) undef false
let add (def,undef) evk newinfo =
if newinfo.evar_body = Evar_empty then
(def,ExistentialMap.add evk newinfo undef)
else
(ExistentialMap.add evk newinfo def,undef)
let add_undefined (def,undef) evk newinfo =
assert (newinfo.evar_body = Evar_empty);
(def,ExistentialMap.add evk newinfo undef)
let map f (def,undef) = (ExistentialMap.map f def, ExistentialMap.map f undef)
let define (def,undef) evk body =
let oldinfo =
try ExistentialMap.find evk undef
with Not_found -> anomaly "Evd.define: cannot define undeclared evar" in
let newinfo =
{ oldinfo with
evar_body = Evar_defined body } in
match oldinfo.evar_body with
| Evar_empty ->
(ExistentialMap.add evk newinfo def,ExistentialMap.remove evk undef)
| _ ->
anomaly "Evd.define: cannot define an evar twice"
let is_evar = mem
let is_defined (def,undef) evk = ExistentialMap.mem evk def
let is_undefined (def,undef) evk = ExistentialMap.mem evk undef
(*******************************************************************)
Formerly Instantiate module
let is_id_inst inst =
let is_id (id,c) = match kind_of_term c with
| Var id' -> id = id'
| _ -> false
in
List.for_all is_id inst
Vérifier que les instances des let - in sont compatibles ? ?
let instantiate_sign_including_let sign args =
let rec instrec = function
| ((id,b,_) :: sign, c::args) -> (id,c) :: (instrec (sign,args))
| ([],[]) -> []
| ([],_) | (_,[]) ->
anomaly "Signature and its instance do not match"
in
instrec (sign,args)
let instantiate_evar sign c args =
let inst = instantiate_sign_including_let sign args in
if is_id_inst inst then
c
else
replace_vars inst c
(* Existentials. *)
let existential_type sigma (n,args) =
let info =
try find sigma n
with Not_found ->
anomaly ("Evar "^(string_of_existential n)^" was not declared") in
let hyps = evar_filtered_context info in
instantiate_evar hyps info.evar_concl (Array.to_list args)
let existential_value sigma (n,args) =
let info = find sigma n in
let hyps = evar_filtered_context info in
match evar_body info with
| Evar_defined c ->
instantiate_evar hyps c (Array.to_list args)
| Evar_empty ->
raise NotInstantiatedEvar
let existential_opt_value sigma ev =
try Some (existential_value sigma ev)
with NotInstantiatedEvar -> None
end
(*******************************************************************)
(* Constraints for sort variables *)
(*******************************************************************)
type sort_var = Univ.universe
type sort_constraint =
| DefinedSort of sorts (* instantiated sort var *)
( leq , geq )
| EqSort of sort_var
module UniverseMap =
Map.Make (struct type t = Univ.universe let compare = compare end)
type sort_constraints = sort_constraint UniverseMap.t
let rec canonical_find u scstr =
match UniverseMap.find u scstr with
EqSort u' -> canonical_find u' scstr
| c -> (u,c)
let whd_sort_var scstr t =
match kind_of_term t with
Sort(Type u) ->
(try
match canonical_find u scstr with
_, DefinedSort s -> mkSort s
| _ -> t
with Not_found -> t)
| _ -> t
let rec set_impredicative u s scstr =
match UniverseMap.find u scstr with
| DefinedSort s' ->
if family_of_sort s = family_of_sort s' then scstr
else failwith "sort constraint inconsistency"
| EqSort u' ->
UniverseMap.add u (DefinedSort s) (set_impredicative u' s scstr)
| SortVar(_,ul) ->
also set sorts lower than u as impredicative
UniverseMap.add u (DefinedSort s)
(List.fold_left (fun g u' -> set_impredicative u' s g) scstr ul)
let rec set_predicative u s scstr =
match UniverseMap.find u scstr with
| DefinedSort s' ->
if family_of_sort s = family_of_sort s' then scstr
else failwith "sort constraint inconsistency"
| EqSort u' ->
UniverseMap.add u (DefinedSort s) (set_predicative u' s scstr)
| SortVar(ul,_) ->
UniverseMap.add u (DefinedSort s)
(List.fold_left (fun g u' -> set_impredicative u' s g) scstr ul)
let var_of_sort = function
Type u -> u
| _ -> assert false
let is_sort_var s scstr =
match s with
Type u ->
(try
match canonical_find u scstr with
_, DefinedSort _ -> false
| _ -> true
with Not_found -> false)
| _ -> false
let new_sort_var cstr =
let u = Termops.new_univ() in
(u, UniverseMap.add u (SortVar([],[])) cstr)
let set_leq_sort (u1,(leq1,geq1)) (u2,(leq2,geq2)) scstr =
let rec search_rec (is_b, betw, not_betw) u1 =
if List.mem u1 betw then (true, betw, not_betw)
else if List.mem u1 not_betw then (is_b, betw, not_betw)
else if u1 = u2 then (true, u1::betw,not_betw) else
match UniverseMap.find u1 scstr with
EqSort u1' -> search_rec (is_b,betw,not_betw) u1'
| SortVar(leq,_) ->
let (is_b',betw',not_betw') =
List.fold_left search_rec (false,betw,not_betw) leq in
if is_b' then (true, u1::betw', not_betw')
else (false, betw', not_betw')
| DefinedSort _ -> (false,betw,u1::not_betw) in
let (is_betw,betw,_) = search_rec (false, [], []) u1 in
if is_betw then
UniverseMap.add u1 (SortVar(leq1@leq2,geq1@geq2))
(List.fold_left
(fun g u -> UniverseMap.add u (EqSort u1) g) scstr betw)
else
UniverseMap.add u1 (SortVar(u2::leq1,geq1))
(UniverseMap.add u2 (SortVar(leq2, u1::geq2)) scstr)
let set_leq s1 s2 scstr =
let u1 = var_of_sort s1 in
let u2 = var_of_sort s2 in
let (cu1,c1) = canonical_find u1 scstr in
let (cu2,c2) = canonical_find u2 scstr in
if cu1=cu2 then scstr
else
match c1,c2 with
(EqSort _, _ | _, EqSort _) -> assert false
| SortVar(leq1,geq1), SortVar(leq2,geq2) ->
set_leq_sort (cu1,(leq1,geq1)) (cu2,(leq2,geq2)) scstr
| _, DefinedSort(Prop _ as s) -> set_impredicative u1 s scstr
| _, DefinedSort(Type _) -> scstr
| DefinedSort(Type _ as s), _ -> set_predicative u2 s scstr
| DefinedSort(Prop _), _ -> scstr
let set_sort_variable s1 s2 scstr =
let u = var_of_sort s1 in
match s2 with
Prop _ -> set_impredicative u s2 scstr
| Type _ -> set_predicative u s2 scstr
let pr_sort_cstrs g =
let l = UniverseMap.fold (fun u c l -> (u,c)::l) g [] in
str "SORT CONSTRAINTS:" ++ fnl() ++
prlist_with_sep fnl (fun (u,c) ->
match c with
EqSort u' -> Univ.pr_uni u ++ str" == " ++ Univ.pr_uni u'
| DefinedSort s -> Univ.pr_uni u ++ str " := " ++ print_sort s
| SortVar(leq,geq) ->
str"[" ++ hov 0 (prlist_with_sep spc Univ.pr_uni geq) ++
str"] <= "++ Univ.pr_uni u ++ brk(0,0) ++ str"<= [" ++
hov 0 (prlist_with_sep spc Univ.pr_uni leq) ++ str"]")
l
module EvarMap = struct
type t = EvarInfoMap.t * sort_constraints
let empty = EvarInfoMap.empty, UniverseMap.empty
let add (sigma,sm) k v = (EvarInfoMap.add sigma k v, sm)
let add_undefined (sigma,sm) k v = (EvarInfoMap.add_undefined sigma k v, sm)
let find (sigma,_) = EvarInfoMap.find sigma
let find_undefined (sigma,_) = EvarInfoMap.find_undefined sigma
let remove (sigma,sm) k = (EvarInfoMap.remove sigma k, sm)
let mem (sigma,_) = EvarInfoMap.mem sigma
let to_list (sigma,_) = EvarInfoMap.to_list sigma
let undefined_list (sigma,_) = EvarInfoMap.undefined_list sigma
let undefined_evars (sigma,sm) = (EvarInfoMap.undefined_evars sigma, sm)
let fold (sigma,_) = EvarInfoMap.fold sigma
let fold_undefined (sigma,_) = EvarInfoMap.fold_undefined sigma
let define (sigma,sm) k v = (EvarInfoMap.define sigma k v, sm)
let is_evar (sigma,_) = EvarInfoMap.is_evar sigma
let is_defined (sigma,_) = EvarInfoMap.is_defined sigma
let is_undefined (sigma,_) = EvarInfoMap.is_undefined sigma
let existential_value (sigma,_) = EvarInfoMap.existential_value sigma
let existential_type (sigma,_) = EvarInfoMap.existential_type sigma
let existential_opt_value (sigma,_) = EvarInfoMap.existential_opt_value sigma
let progress_evar_map (sigma1,sm1 as x) (sigma2,sm2 as y) = not (x == y) &&
(EvarInfoMap.exists_undefined sigma1
(fun k v -> assert (v.evar_body = Evar_empty);
EvarInfoMap.is_defined sigma2 k)
|| not (UniverseMap.equal (=) sm1 sm2))
let merge e e' = fold e' (fun n v sigma -> add sigma n v) e
end
(*******************************************************************)
Metamaps
(*******************************************************************)
(* Constraints for existential variables *)
(*******************************************************************)
type 'a freelisted = {
rebus : 'a;
freemetas : Intset.t }
(* Collects all metavars appearing in a constr *)
let metavars_of c =
let rec collrec acc c =
match kind_of_term c with
| Meta mv -> Intset.add mv acc
| _ -> fold_constr collrec acc c
in
collrec Intset.empty c
let mk_freelisted c =
{ rebus = c; freemetas = metavars_of c }
let map_fl f cfl = { cfl with rebus=f cfl.rebus }
Status of an instance found by unification wrt to the meta it solves :
- a supertype of the meta ( e.g. the solution to ? X < = T is a supertype of ? X )
- a subtype of the meta ( e.g. the solution to T < = ? X is a supertype of ? X )
- a term that can be eta - expanded n times while still being a solution
( e.g. the solution [ P ] to [ ? X u v = P u v ] can be eta - expanded twice )
- a supertype of the meta (e.g. the solution to ?X <= T is a supertype of ?X)
- a subtype of the meta (e.g. the solution to T <= ?X is a supertype of ?X)
- a term that can be eta-expanded n times while still being a solution
(e.g. the solution [P] to [?X u v = P u v] can be eta-expanded twice)
*)
type instance_constraint =
IsSuperType | IsSubType | ConvUpToEta of int | UserGiven
(* Status of the unification of the type of an instance against the type of
the meta it instantiates:
- CoerceToType means that the unification of types has not been done
and that a coercion can still be inserted: the meta should not be
substituted freely (this happens for instance given via the
"with" binding clause).
- TypeProcessed means that the information obtainable from the
unification of types has been extracted.
- TypeNotProcessed means that the unification of types has not been
done but it is known that no coercion may be inserted: the meta
can be substituted freely.
*)
type instance_typing_status =
CoerceToType | TypeNotProcessed | TypeProcessed
(* Status of an instance together with the status of its type unification *)
type instance_status = instance_constraint * instance_typing_status
(* Clausal environments *)
type clbinding =
| Cltyp of name * constr freelisted
| Clval of name * (constr freelisted * instance_status) * constr freelisted
let map_clb f = function
| Cltyp (na,cfl) -> Cltyp (na,map_fl f cfl)
| Clval (na,(cfl1,pb),cfl2) -> Clval (na,(map_fl f cfl1,pb),map_fl f cfl2)
(* name of defined is erased (but it is pretty-printed) *)
let clb_name = function
Cltyp(na,_) -> (na,false)
| Clval (na,_,_) -> (na,true)
(***********************)
module Metaset = Intset
let meta_exists p s = Metaset.fold (fun x b -> b || (p x)) s false
module Metamap = Intmap
let metamap_to_list m =
Metamap.fold (fun n v l -> (n,v)::l) m []
(*************************)
(* Unification state *)
type conv_pb = Reduction.conv_pb
type evar_constraint = conv_pb * Environ.env * constr * constr
type evar_map =
{ evars : EvarMap.t;
conv_pbs : evar_constraint list;
last_mods : ExistentialSet.t;
metas : clbinding Metamap.t }
* * Lifting primitive from EvarMap . * *
HH : The progress tactical now uses this function .
let progress_evar_map d1 d2 =
EvarMap.progress_evar_map d1.evars d2.evars
(* spiwack: tentative. It might very well not be the semantics we want
for merging evar_map *)
let merge d1 d2 = {
evars = EvarMap.merge d1.evars d2.evars ;
conv_pbs = List.rev_append d1.conv_pbs d2.conv_pbs ;
last_mods = ExistentialSet.union d1.last_mods d2.last_mods ;
metas = Metamap.fold (fun k m r -> Metamap.add k m r) d2.metas d1.metas
}
let add d e i = { d with evars=EvarMap.add d.evars e i }
let remove d e = { d with evars=EvarMap.remove d.evars e }
let find d e = EvarMap.find d.evars e
let find_undefined d e = EvarMap.find_undefined d.evars e
let mem d e = EvarMap.mem d.evars e
(* spiwack: this function loses information from the original evar_map
it might be an idea not to export it. *)
let to_list d = EvarMap.to_list d.evars
let undefined_list d = EvarMap.undefined_list d.evars
let undefined_evars d = { d with evars=EvarMap.undefined_evars d.evars }
(* spiwack: not clear what folding over an evar_map, for now we shall
simply fold over the inner evar_map. *)
let fold f d a = EvarMap.fold d.evars f a
let fold_undefined f d a = EvarMap.fold_undefined d.evars f a
let is_evar d e = EvarMap.is_evar d.evars e
let is_defined d e = EvarMap.is_defined d.evars e
let is_undefined d e = EvarMap.is_undefined d.evars e
let existential_value d e = EvarMap.existential_value d.evars e
let existential_type d e = EvarMap.existential_type d.evars e
let existential_opt_value d e = EvarMap.existential_opt_value d.evars e
(*** /Lifting... ***)
(* evar_map are considered empty disregarding histories *)
let is_empty d =
d.evars = EvarMap.empty &&
d.conv_pbs = [] &&
Metamap.is_empty d.metas
let subst_named_context_val s = map_named_val (subst_mps s)
let subst_evar_info s evi =
let subst_evb = function Evar_empty -> Evar_empty
| Evar_defined c -> Evar_defined (subst_mps s c) in
{ evi with
evar_concl = subst_mps s evi.evar_concl;
evar_hyps = subst_named_context_val s evi.evar_hyps;
evar_body = subst_evb evi.evar_body }
let subst_evar_defs_light sub evd =
assert (UniverseMap.is_empty (snd evd.evars));
assert (evd.conv_pbs = []);
{ evd with
metas = Metamap.map (map_clb (subst_mps sub)) evd.metas;
evars = EvarInfoMap.map (subst_evar_info sub) (fst evd.evars), (snd evd.evars)
}
let subst_evar_map = subst_evar_defs_light
(* spiwack: deprecated *)
let create_evar_defs sigma = { sigma with
conv_pbs=[]; last_mods=ExistentialSet.empty; metas=Metamap.empty }
(* spiwack: tentatively deprecated *)
let create_goal_evar_defs sigma = { sigma with
(* conv_pbs=[]; last_mods=ExistentialSet.empty; metas=Metamap.empty } *)
metas=Metamap.empty }
let empty = {
evars=EvarMap.empty;
conv_pbs=[];
last_mods = ExistentialSet.empty;
metas=Metamap.empty
}
let evars_reset_evd evd d = {d with evars = evd.evars}
let add_conv_pb pb d = {d with conv_pbs = pb::d.conv_pbs}
let evar_source evk d = (EvarMap.find d.evars evk).evar_source
(* define the existential of section path sp as the constr body *)
let define evk body evd =
{ evd with
evars = EvarMap.define evd.evars evk body;
last_mods =
match evd.conv_pbs with
| [] -> evd.last_mods
| _ -> ExistentialSet.add evk evd.last_mods }
let evar_declare hyps evk ty ?(src=(dummy_loc,InternalHole)) ?filter evd =
let filter =
if filter = None then
List.map (fun _ -> true) (named_context_of_val hyps)
else
(let filter = Option.get filter in
assert (List.length filter = List.length (named_context_of_val hyps));
filter)
in
{ evd with
evars = EvarMap.add_undefined evd.evars evk
{evar_hyps = hyps;
evar_concl = ty;
evar_body = Evar_empty;
evar_filter = filter;
evar_source = src;
evar_extra = Store.empty } }
let is_defined_evar evd (evk,_) = EvarMap.is_defined evd.evars evk
(* Does k corresponds to an (un)defined existential ? *)
let is_undefined_evar evd c = match kind_of_term c with
| Evar ev -> not (is_defined_evar evd ev)
| _ -> false
(* extracts conversion problems that satisfy predicate p *)
Note : conv_pbs not satisying p are stored back in reverse order
let extract_conv_pbs evd p =
let (pbs,pbs1) =
List.fold_left
(fun (pbs,pbs1) pb ->
if p pb then
(pb::pbs,pbs1)
else
(pbs,pb::pbs1))
([],[])
evd.conv_pbs
in
{evd with conv_pbs = pbs1; last_mods = ExistentialSet.empty},
pbs
let extract_changed_conv_pbs evd p =
extract_conv_pbs evd (p evd.last_mods)
let extract_all_conv_pbs evd =
extract_conv_pbs evd (fun _ -> true)
(* spiwack: should it be replaced by Evd.merge? *)
let evar_merge evd evars =
{ evd with evars = EvarMap.merge evd.evars evars.evars }
let evar_list evd c =
let rec evrec acc c =
match kind_of_term c with
| Evar (evk, _ as ev) when mem evd evk -> ev :: acc
| _ -> fold_constr evrec acc c in
evrec [] c
(**********************************************************)
(* Sort variables *)
let new_sort_variable ({ evars = (sigma,sm) } as d)=
let (u,scstr) = new_sort_var sm in
(Type u,{ d with evars = (sigma,scstr) } )
let is_sort_variable {evars=(_,sm)} s =
is_sort_var s sm
let whd_sort_variable {evars=(_,sm)} t = whd_sort_var sm t
let set_leq_sort_variable ({evars=(sigma,sm)}as d) u1 u2 =
{ d with evars = (sigma, set_leq u1 u2 sm) }
let define_sort_variable ({evars=(sigma,sm)}as d) u s =
{ d with evars = (sigma, set_sort_variable u s sm) }
let pr_sort_constraints {evars=(_,sm)} = pr_sort_cstrs sm
(**********************************************************)
(* Accessing metas *)
let meta_list evd = metamap_to_list evd.metas
let find_meta evd mv = Metamap.find mv evd.metas
let undefined_metas evd =
List.sort Pervasives.compare (map_succeed (function
| (n,Clval(_,_,typ)) -> failwith ""
| (n,Cltyp (_,typ)) -> n)
(meta_list evd))
let metas_of evd =
List.map (function
| (n,Clval(_,_,typ)) -> (n,typ.rebus)
| (n,Cltyp (_,typ)) -> (n,typ.rebus))
(meta_list evd)
let map_metas_fvalue f evd =
{ evd with metas =
Metamap.map
(function
| Clval(id,(c,s),typ) -> Clval(id,(mk_freelisted (f c.rebus),s),typ)
| x -> x) evd.metas }
let meta_opt_fvalue evd mv =
match Metamap.find mv evd.metas with
| Clval(_,b,_) -> Some b
| Cltyp _ -> None
let meta_defined evd mv =
match Metamap.find mv evd.metas with
| Clval _ -> true
| Cltyp _ -> false
let try_meta_fvalue evd mv =
match Metamap.find mv evd.metas with
| Clval(_,b,_) -> b
| Cltyp _ -> raise Not_found
let meta_fvalue evd mv =
try try_meta_fvalue evd mv
with Not_found -> anomaly "meta_fvalue: meta has no value"
let meta_value evd mv =
(fst (try_meta_fvalue evd mv)).rebus
let meta_ftype evd mv =
match Metamap.find mv evd.metas with
| Cltyp (_,b) -> b
| Clval(_,_,b) -> b
let meta_type evd mv = (meta_ftype evd mv).rebus
let meta_declare mv v ?(name=Anonymous) evd =
{ evd with metas = Metamap.add mv (Cltyp(name,mk_freelisted v)) evd.metas }
let meta_assign mv (v,pb) evd =
match Metamap.find mv evd.metas with
| Cltyp(na,ty) ->
{ evd with
metas = Metamap.add mv (Clval(na,(mk_freelisted v,pb),ty)) evd.metas }
| _ -> anomaly "meta_assign: already defined"
let meta_reassign mv (v,pb) evd =
match Metamap.find mv evd.metas with
| Clval(na,_,ty) ->
{ evd with
metas = Metamap.add mv (Clval(na,(mk_freelisted v,pb),ty)) evd.metas }
| _ -> anomaly "meta_reassign: not yet defined"
(* If the meta is defined then forget its name *)
let meta_name evd mv =
try fst (clb_name (Metamap.find mv evd.metas)) with Not_found -> Anonymous
let meta_with_name evd id =
let na = Name id in
let (mvl,mvnodef) =
Metamap.fold
(fun n clb (l1,l2 as l) ->
let (na',def) = clb_name clb in
if na = na' then if def then (n::l1,l2) else (n::l1,n::l2)
else l)
evd.metas ([],[]) in
match mvnodef, mvl with
| _,[] ->
errorlabstrm "Evd.meta_with_name"
(str"No such bound variable " ++ pr_id id ++ str".")
| ([n],_|_,[n]) ->
n
| _ ->
errorlabstrm "Evd.meta_with_name"
(str "Binder name \"" ++ pr_id id ++
strbrk "\" occurs more than once in clause.")
let meta_merge evd1 evd2 =
{evd2 with
metas = List.fold_left (fun m (n,v) -> Metamap.add n v m)
evd2.metas (metamap_to_list evd1.metas) }
type metabinding = metavariable * constr * instance_status
let retract_coercible_metas evd =
let mc,ml =
Metamap.fold (fun n v (mc,ml) ->
match v with
| Clval (na,(b,(UserGiven,CoerceToType as s)),typ) ->
(n,b.rebus,s)::mc, Metamap.add n (Cltyp (na,typ)) ml
| v ->
mc, Metamap.add n v ml)
evd.metas ([],Metamap.empty) in
mc, { evd with metas = ml }
let rec list_assoc_in_triple x = function
[] -> raise Not_found
| (a,b,_)::l -> if compare a x = 0 then b else list_assoc_in_triple x l
let subst_defined_metas bl c =
let rec substrec c = match kind_of_term c with
| Meta i -> substrec (list_assoc_in_triple i bl)
| _ -> map_constr substrec c
in try Some (substrec c) with Not_found -> None
(*******************************************************************)
type open_constr = evar_map * constr
(*******************************************************************)
(* The type constructor ['a sigma] adds an evar map to an object of
type ['a] *)
type 'a sigma = {
it : 'a ;
sigma : evar_map}
let sig_it x = x.it
let sig_sig x = x.sigma
(**********************************************************)
(* Failure explanation *)
type unsolvability_explanation = SeveralInstancesFound of int
(**********************************************************)
(* Pretty-printing *)
let pr_instance_status (sc,typ) =
begin match sc with
| IsSubType -> str " [or a subtype of it]"
| IsSuperType -> str " [or a supertype of it]"
| ConvUpToEta 0 -> mt ()
| UserGiven -> mt ()
| ConvUpToEta n -> str" [or an eta-expansion up to " ++ int n ++ str" of it]"
end ++
begin match typ with
| CoerceToType -> str " [up to coercion]"
| TypeNotProcessed -> mt ()
| TypeProcessed -> str " [type is checked]"
end
let pr_meta_map mmap =
let pr_name = function
Name id -> str"[" ++ pr_id id ++ str"]"
| _ -> mt() in
let pr_meta_binding = function
| (mv,Cltyp (na,b)) ->
hov 0
(pr_meta mv ++ pr_name na ++ str " : " ++
print_constr b.rebus ++ fnl ())
| (mv,Clval(na,(b,s),t)) ->
hov 0
(pr_meta mv ++ pr_name na ++ str " := " ++
print_constr b.rebus ++
str " : " ++ print_constr t.rebus ++
spc () ++ pr_instance_status s ++ fnl ())
in
prlist pr_meta_binding (metamap_to_list mmap)
let pr_decl ((id,b,_),ok) =
match b with
| None -> if ok then pr_id id else (str "{" ++ pr_id id ++ str "}")
| Some c -> str (if ok then "(" else "{") ++ pr_id id ++ str ":=" ++
print_constr c ++ str (if ok then ")" else "}")
let pr_evar_info evi =
let decls = List.combine (evar_context evi) (evar_filter evi) in
let phyps = prlist_with_sep pr_spc pr_decl (List.rev decls) in
let pty = print_constr evi.evar_concl in
let pb =
match evi.evar_body with
| Evar_empty -> mt ()
| Evar_defined c -> spc() ++ str"=> " ++ print_constr c
in
hov 2 (str"[" ++ phyps ++ spc () ++ str"|- " ++ pty ++ pb ++ str"]")
let pr_evar_map_t (evars,cstrs as sigma) =
let evs =
if evars = EvarInfoMap.empty then mt ()
else
str"EVARS:"++brk(0,1)++
h 0 (prlist_with_sep pr_fnl
(fun (ev,evi) ->
h 0 (str(string_of_existential ev)++str"=="++ pr_evar_info evi))
(EvarMap.to_list sigma))++fnl()
and cs =
if cstrs = UniverseMap.empty then mt ()
else pr_sort_cstrs cstrs++fnl()
in evs ++ cs
let pr_constraints pbs =
h 0
(prlist_with_sep pr_fnl (fun (pbty,_,t1,t2) ->
print_constr t1 ++ spc() ++
str (match pbty with
| Reduction.CONV -> "=="
| Reduction.CUMUL -> "<=") ++
spc() ++ print_constr t2) pbs)
let pr_evar_map evd =
let pp_evm =
if evd.evars = EvarMap.empty then mt() else
pr_evar_map_t evd.evars++fnl() in
let cstrs =
if evd.conv_pbs = [] then mt() else
str"CONSTRAINTS:"++brk(0,1)++pr_constraints evd.conv_pbs++fnl() in
let pp_met =
if evd.metas = Metamap.empty then mt() else
str"METAS:"++brk(0,1)++pr_meta_map evd.metas in
v 0 (pp_evm ++ cstrs ++ pp_met)
let pr_metaset metas =
str "[" ++ prlist_with_sep spc pr_meta (Metaset.elements metas) ++ str "]"
| null | https://raw.githubusercontent.com/herbelin/coq-hh/296d03d5049fea661e8bdbaf305ed4bf6d2001d2/pretyping/evd.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
The kinds of existential variable
The type of mappings for existential variables
This exception is raised by *.existential_value
*****************************************************************
Existentials.
*****************************************************************
Constraints for sort variables
*****************************************************************
instantiated sort var
*****************************************************************
*****************************************************************
Constraints for existential variables
*****************************************************************
Collects all metavars appearing in a constr
Status of the unification of the type of an instance against the type of
the meta it instantiates:
- CoerceToType means that the unification of types has not been done
and that a coercion can still be inserted: the meta should not be
substituted freely (this happens for instance given via the
"with" binding clause).
- TypeProcessed means that the information obtainable from the
unification of types has been extracted.
- TypeNotProcessed means that the unification of types has not been
done but it is known that no coercion may be inserted: the meta
can be substituted freely.
Status of an instance together with the status of its type unification
Clausal environments
name of defined is erased (but it is pretty-printed)
*********************
***********************
Unification state
spiwack: tentative. It might very well not be the semantics we want
for merging evar_map
spiwack: this function loses information from the original evar_map
it might be an idea not to export it.
spiwack: not clear what folding over an evar_map, for now we shall
simply fold over the inner evar_map.
** /Lifting... **
evar_map are considered empty disregarding histories
spiwack: deprecated
spiwack: tentatively deprecated
conv_pbs=[]; last_mods=ExistentialSet.empty; metas=Metamap.empty }
define the existential of section path sp as the constr body
Does k corresponds to an (un)defined existential ?
extracts conversion problems that satisfy predicate p
spiwack: should it be replaced by Evd.merge?
********************************************************
Sort variables
********************************************************
Accessing metas
If the meta is defined then forget its name
*****************************************************************
*****************************************************************
The type constructor ['a sigma] adds an evar map to an object of
type ['a]
********************************************************
Failure explanation
********************************************************
Pretty-printing | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Pp
open Util
open Names
open Nameops
open Term
open Termops
open Sign
open Environ
open Libnames
open Mod_subst
type obligation_definition_status = Define of bool | Expand
type hole_kind =
| ImplicitArg of global_reference * (int * identifier option) * bool
| BinderType of name
| QuestionMark of obligation_definition_status
| CasesType
| InternalHole
| TomatchTypeParameter of inductive * int
| GoalEvar
| ImpossibleCase
| MatchingVar of bool * identifier
type evar = existential_key
let string_of_existential evk = "?" ^ string_of_int evk
let existential_of_int evk = evk
type evar_body =
| Evar_empty
| Evar_defined of constr
type evar_info = {
evar_concl : constr;
evar_hyps : named_context_val;
evar_body : evar_body;
evar_filter : bool list;
evar_source : hole_kind located;
evar_extra : Store.t }
let make_evar hyps ccl = {
evar_concl = ccl;
evar_hyps = hyps;
evar_body = Evar_empty;
evar_filter = List.map (fun _ -> true) (named_context_of_val hyps);
evar_source = (dummy_loc,InternalHole);
evar_extra = Store.empty
}
let evar_concl evi = evi.evar_concl
let evar_hyps evi = evi.evar_hyps
let evar_context evi = named_context_of_val evi.evar_hyps
let evar_body evi = evi.evar_body
let evar_filter evi = evi.evar_filter
let evar_unfiltered_env evi = Global.env_of_context evi.evar_hyps
let evar_filtered_context evi =
snd (list_filter2 (fun b c -> b) (evar_filter evi,evar_context evi))
let evar_env evi =
List.fold_right push_named (evar_filtered_context evi)
(reset_context (Global.env()))
let eq_evar_info ei1 ei2 =
ei1 == ei2 ||
eq_constr ei1.evar_concl ei2.evar_concl &&
eq_named_context_val (ei1.evar_hyps) (ei2.evar_hyps) &&
ei1.evar_body = ei2.evar_body
spiwack : Revised hierarchy :
- ExistentialMap ( Maps of existential_keys )
- EvarInfoMap ( .t = evar_info ExistentialMap.t * evar_info ExistentialMap )
- EvarMap ( .t = EvarInfoMap.t * sort_constraints )
- evar_map ( exported )
- ExistentialMap ( Maps of existential_keys )
- EvarInfoMap ( .t = evar_info ExistentialMap.t * evar_info ExistentialMap )
- EvarMap ( .t = EvarInfoMap.t * sort_constraints )
- evar_map (exported)
*)
module ExistentialMap = Intmap
module ExistentialSet = Intset
exception NotInstantiatedEvar
module EvarInfoMap = struct
type t = evar_info ExistentialMap.t * evar_info ExistentialMap.t
let empty = ExistentialMap.empty, ExistentialMap.empty
let to_list (def,undef) =
Workaround for change in Map.fold behavior in ocaml 3.08.4
let l = ref [] in
ExistentialMap.iter (fun evk x -> l := (evk,x)::!l) def;
ExistentialMap.iter (fun evk x -> l := (evk,x)::!l) undef;
!l
let undefined_list (def,undef) =
Order is important : needs ocaml > = 3.08.4 from which " fold " is a
" fold_left "
"fold_left" *)
ExistentialMap.fold (fun evk evi l -> (evk,evi)::l) undef []
let undefined_evars (def,undef) = (ExistentialMap.empty,undef)
let find (def,undef) k =
try ExistentialMap.find k def
with Not_found -> ExistentialMap.find k undef
let find_undefined (def,undef) k = ExistentialMap.find k undef
let remove (def,undef) k =
(ExistentialMap.remove k def,ExistentialMap.remove k undef)
let mem (def,undef) k =
ExistentialMap.mem k def || ExistentialMap.mem k undef
let fold (def,undef) f a =
ExistentialMap.fold f def (ExistentialMap.fold f undef a)
let fold_undefined (def,undef) f a =
ExistentialMap.fold f undef a
let exists_undefined (def,undef) f =
ExistentialMap.fold (fun k v b -> b || f k v) undef false
let add (def,undef) evk newinfo =
if newinfo.evar_body = Evar_empty then
(def,ExistentialMap.add evk newinfo undef)
else
(ExistentialMap.add evk newinfo def,undef)
let add_undefined (def,undef) evk newinfo =
assert (newinfo.evar_body = Evar_empty);
(def,ExistentialMap.add evk newinfo undef)
let map f (def,undef) = (ExistentialMap.map f def, ExistentialMap.map f undef)
let define (def,undef) evk body =
let oldinfo =
try ExistentialMap.find evk undef
with Not_found -> anomaly "Evd.define: cannot define undeclared evar" in
let newinfo =
{ oldinfo with
evar_body = Evar_defined body } in
match oldinfo.evar_body with
| Evar_empty ->
(ExistentialMap.add evk newinfo def,ExistentialMap.remove evk undef)
| _ ->
anomaly "Evd.define: cannot define an evar twice"
let is_evar = mem
let is_defined (def,undef) evk = ExistentialMap.mem evk def
let is_undefined (def,undef) evk = ExistentialMap.mem evk undef
Formerly Instantiate module
let is_id_inst inst =
let is_id (id,c) = match kind_of_term c with
| Var id' -> id = id'
| _ -> false
in
List.for_all is_id inst
Vérifier que les instances des let - in sont compatibles ? ?
let instantiate_sign_including_let sign args =
let rec instrec = function
| ((id,b,_) :: sign, c::args) -> (id,c) :: (instrec (sign,args))
| ([],[]) -> []
| ([],_) | (_,[]) ->
anomaly "Signature and its instance do not match"
in
instrec (sign,args)
let instantiate_evar sign c args =
let inst = instantiate_sign_including_let sign args in
if is_id_inst inst then
c
else
replace_vars inst c
let existential_type sigma (n,args) =
let info =
try find sigma n
with Not_found ->
anomaly ("Evar "^(string_of_existential n)^" was not declared") in
let hyps = evar_filtered_context info in
instantiate_evar hyps info.evar_concl (Array.to_list args)
let existential_value sigma (n,args) =
let info = find sigma n in
let hyps = evar_filtered_context info in
match evar_body info with
| Evar_defined c ->
instantiate_evar hyps c (Array.to_list args)
| Evar_empty ->
raise NotInstantiatedEvar
let existential_opt_value sigma ev =
try Some (existential_value sigma ev)
with NotInstantiatedEvar -> None
end
type sort_var = Univ.universe
type sort_constraint =
( leq , geq )
| EqSort of sort_var
module UniverseMap =
Map.Make (struct type t = Univ.universe let compare = compare end)
type sort_constraints = sort_constraint UniverseMap.t
let rec canonical_find u scstr =
match UniverseMap.find u scstr with
EqSort u' -> canonical_find u' scstr
| c -> (u,c)
let whd_sort_var scstr t =
match kind_of_term t with
Sort(Type u) ->
(try
match canonical_find u scstr with
_, DefinedSort s -> mkSort s
| _ -> t
with Not_found -> t)
| _ -> t
let rec set_impredicative u s scstr =
match UniverseMap.find u scstr with
| DefinedSort s' ->
if family_of_sort s = family_of_sort s' then scstr
else failwith "sort constraint inconsistency"
| EqSort u' ->
UniverseMap.add u (DefinedSort s) (set_impredicative u' s scstr)
| SortVar(_,ul) ->
also set sorts lower than u as impredicative
UniverseMap.add u (DefinedSort s)
(List.fold_left (fun g u' -> set_impredicative u' s g) scstr ul)
let rec set_predicative u s scstr =
match UniverseMap.find u scstr with
| DefinedSort s' ->
if family_of_sort s = family_of_sort s' then scstr
else failwith "sort constraint inconsistency"
| EqSort u' ->
UniverseMap.add u (DefinedSort s) (set_predicative u' s scstr)
| SortVar(ul,_) ->
UniverseMap.add u (DefinedSort s)
(List.fold_left (fun g u' -> set_impredicative u' s g) scstr ul)
let var_of_sort = function
Type u -> u
| _ -> assert false
let is_sort_var s scstr =
match s with
Type u ->
(try
match canonical_find u scstr with
_, DefinedSort _ -> false
| _ -> true
with Not_found -> false)
| _ -> false
let new_sort_var cstr =
let u = Termops.new_univ() in
(u, UniverseMap.add u (SortVar([],[])) cstr)
let set_leq_sort (u1,(leq1,geq1)) (u2,(leq2,geq2)) scstr =
let rec search_rec (is_b, betw, not_betw) u1 =
if List.mem u1 betw then (true, betw, not_betw)
else if List.mem u1 not_betw then (is_b, betw, not_betw)
else if u1 = u2 then (true, u1::betw,not_betw) else
match UniverseMap.find u1 scstr with
EqSort u1' -> search_rec (is_b,betw,not_betw) u1'
| SortVar(leq,_) ->
let (is_b',betw',not_betw') =
List.fold_left search_rec (false,betw,not_betw) leq in
if is_b' then (true, u1::betw', not_betw')
else (false, betw', not_betw')
| DefinedSort _ -> (false,betw,u1::not_betw) in
let (is_betw,betw,_) = search_rec (false, [], []) u1 in
if is_betw then
UniverseMap.add u1 (SortVar(leq1@leq2,geq1@geq2))
(List.fold_left
(fun g u -> UniverseMap.add u (EqSort u1) g) scstr betw)
else
UniverseMap.add u1 (SortVar(u2::leq1,geq1))
(UniverseMap.add u2 (SortVar(leq2, u1::geq2)) scstr)
let set_leq s1 s2 scstr =
let u1 = var_of_sort s1 in
let u2 = var_of_sort s2 in
let (cu1,c1) = canonical_find u1 scstr in
let (cu2,c2) = canonical_find u2 scstr in
if cu1=cu2 then scstr
else
match c1,c2 with
(EqSort _, _ | _, EqSort _) -> assert false
| SortVar(leq1,geq1), SortVar(leq2,geq2) ->
set_leq_sort (cu1,(leq1,geq1)) (cu2,(leq2,geq2)) scstr
| _, DefinedSort(Prop _ as s) -> set_impredicative u1 s scstr
| _, DefinedSort(Type _) -> scstr
| DefinedSort(Type _ as s), _ -> set_predicative u2 s scstr
| DefinedSort(Prop _), _ -> scstr
let set_sort_variable s1 s2 scstr =
let u = var_of_sort s1 in
match s2 with
Prop _ -> set_impredicative u s2 scstr
| Type _ -> set_predicative u s2 scstr
let pr_sort_cstrs g =
let l = UniverseMap.fold (fun u c l -> (u,c)::l) g [] in
str "SORT CONSTRAINTS:" ++ fnl() ++
prlist_with_sep fnl (fun (u,c) ->
match c with
EqSort u' -> Univ.pr_uni u ++ str" == " ++ Univ.pr_uni u'
| DefinedSort s -> Univ.pr_uni u ++ str " := " ++ print_sort s
| SortVar(leq,geq) ->
str"[" ++ hov 0 (prlist_with_sep spc Univ.pr_uni geq) ++
str"] <= "++ Univ.pr_uni u ++ brk(0,0) ++ str"<= [" ++
hov 0 (prlist_with_sep spc Univ.pr_uni leq) ++ str"]")
l
module EvarMap = struct
type t = EvarInfoMap.t * sort_constraints
let empty = EvarInfoMap.empty, UniverseMap.empty
let add (sigma,sm) k v = (EvarInfoMap.add sigma k v, sm)
let add_undefined (sigma,sm) k v = (EvarInfoMap.add_undefined sigma k v, sm)
let find (sigma,_) = EvarInfoMap.find sigma
let find_undefined (sigma,_) = EvarInfoMap.find_undefined sigma
let remove (sigma,sm) k = (EvarInfoMap.remove sigma k, sm)
let mem (sigma,_) = EvarInfoMap.mem sigma
let to_list (sigma,_) = EvarInfoMap.to_list sigma
let undefined_list (sigma,_) = EvarInfoMap.undefined_list sigma
let undefined_evars (sigma,sm) = (EvarInfoMap.undefined_evars sigma, sm)
let fold (sigma,_) = EvarInfoMap.fold sigma
let fold_undefined (sigma,_) = EvarInfoMap.fold_undefined sigma
let define (sigma,sm) k v = (EvarInfoMap.define sigma k v, sm)
let is_evar (sigma,_) = EvarInfoMap.is_evar sigma
let is_defined (sigma,_) = EvarInfoMap.is_defined sigma
let is_undefined (sigma,_) = EvarInfoMap.is_undefined sigma
let existential_value (sigma,_) = EvarInfoMap.existential_value sigma
let existential_type (sigma,_) = EvarInfoMap.existential_type sigma
let existential_opt_value (sigma,_) = EvarInfoMap.existential_opt_value sigma
let progress_evar_map (sigma1,sm1 as x) (sigma2,sm2 as y) = not (x == y) &&
(EvarInfoMap.exists_undefined sigma1
(fun k v -> assert (v.evar_body = Evar_empty);
EvarInfoMap.is_defined sigma2 k)
|| not (UniverseMap.equal (=) sm1 sm2))
let merge e e' = fold e' (fun n v sigma -> add sigma n v) e
end
Metamaps
type 'a freelisted = {
rebus : 'a;
freemetas : Intset.t }
let metavars_of c =
let rec collrec acc c =
match kind_of_term c with
| Meta mv -> Intset.add mv acc
| _ -> fold_constr collrec acc c
in
collrec Intset.empty c
let mk_freelisted c =
{ rebus = c; freemetas = metavars_of c }
let map_fl f cfl = { cfl with rebus=f cfl.rebus }
Status of an instance found by unification wrt to the meta it solves :
- a supertype of the meta ( e.g. the solution to ? X < = T is a supertype of ? X )
- a subtype of the meta ( e.g. the solution to T < = ? X is a supertype of ? X )
- a term that can be eta - expanded n times while still being a solution
( e.g. the solution [ P ] to [ ? X u v = P u v ] can be eta - expanded twice )
- a supertype of the meta (e.g. the solution to ?X <= T is a supertype of ?X)
- a subtype of the meta (e.g. the solution to T <= ?X is a supertype of ?X)
- a term that can be eta-expanded n times while still being a solution
(e.g. the solution [P] to [?X u v = P u v] can be eta-expanded twice)
*)
type instance_constraint =
IsSuperType | IsSubType | ConvUpToEta of int | UserGiven
type instance_typing_status =
CoerceToType | TypeNotProcessed | TypeProcessed
type instance_status = instance_constraint * instance_typing_status
type clbinding =
| Cltyp of name * constr freelisted
| Clval of name * (constr freelisted * instance_status) * constr freelisted
let map_clb f = function
| Cltyp (na,cfl) -> Cltyp (na,map_fl f cfl)
| Clval (na,(cfl1,pb),cfl2) -> Clval (na,(map_fl f cfl1,pb),map_fl f cfl2)
let clb_name = function
Cltyp(na,_) -> (na,false)
| Clval (na,_,_) -> (na,true)
module Metaset = Intset
let meta_exists p s = Metaset.fold (fun x b -> b || (p x)) s false
module Metamap = Intmap
let metamap_to_list m =
Metamap.fold (fun n v l -> (n,v)::l) m []
type conv_pb = Reduction.conv_pb
type evar_constraint = conv_pb * Environ.env * constr * constr
type evar_map =
{ evars : EvarMap.t;
conv_pbs : evar_constraint list;
last_mods : ExistentialSet.t;
metas : clbinding Metamap.t }
* * Lifting primitive from EvarMap . * *
HH : The progress tactical now uses this function .
let progress_evar_map d1 d2 =
EvarMap.progress_evar_map d1.evars d2.evars
let merge d1 d2 = {
evars = EvarMap.merge d1.evars d2.evars ;
conv_pbs = List.rev_append d1.conv_pbs d2.conv_pbs ;
last_mods = ExistentialSet.union d1.last_mods d2.last_mods ;
metas = Metamap.fold (fun k m r -> Metamap.add k m r) d2.metas d1.metas
}
let add d e i = { d with evars=EvarMap.add d.evars e i }
let remove d e = { d with evars=EvarMap.remove d.evars e }
let find d e = EvarMap.find d.evars e
let find_undefined d e = EvarMap.find_undefined d.evars e
let mem d e = EvarMap.mem d.evars e
let to_list d = EvarMap.to_list d.evars
let undefined_list d = EvarMap.undefined_list d.evars
let undefined_evars d = { d with evars=EvarMap.undefined_evars d.evars }
let fold f d a = EvarMap.fold d.evars f a
let fold_undefined f d a = EvarMap.fold_undefined d.evars f a
let is_evar d e = EvarMap.is_evar d.evars e
let is_defined d e = EvarMap.is_defined d.evars e
let is_undefined d e = EvarMap.is_undefined d.evars e
let existential_value d e = EvarMap.existential_value d.evars e
let existential_type d e = EvarMap.existential_type d.evars e
let existential_opt_value d e = EvarMap.existential_opt_value d.evars e
let is_empty d =
d.evars = EvarMap.empty &&
d.conv_pbs = [] &&
Metamap.is_empty d.metas
let subst_named_context_val s = map_named_val (subst_mps s)
let subst_evar_info s evi =
let subst_evb = function Evar_empty -> Evar_empty
| Evar_defined c -> Evar_defined (subst_mps s c) in
{ evi with
evar_concl = subst_mps s evi.evar_concl;
evar_hyps = subst_named_context_val s evi.evar_hyps;
evar_body = subst_evb evi.evar_body }
let subst_evar_defs_light sub evd =
assert (UniverseMap.is_empty (snd evd.evars));
assert (evd.conv_pbs = []);
{ evd with
metas = Metamap.map (map_clb (subst_mps sub)) evd.metas;
evars = EvarInfoMap.map (subst_evar_info sub) (fst evd.evars), (snd evd.evars)
}
let subst_evar_map = subst_evar_defs_light
let create_evar_defs sigma = { sigma with
conv_pbs=[]; last_mods=ExistentialSet.empty; metas=Metamap.empty }
let create_goal_evar_defs sigma = { sigma with
metas=Metamap.empty }
let empty = {
evars=EvarMap.empty;
conv_pbs=[];
last_mods = ExistentialSet.empty;
metas=Metamap.empty
}
let evars_reset_evd evd d = {d with evars = evd.evars}
let add_conv_pb pb d = {d with conv_pbs = pb::d.conv_pbs}
let evar_source evk d = (EvarMap.find d.evars evk).evar_source
let define evk body evd =
{ evd with
evars = EvarMap.define evd.evars evk body;
last_mods =
match evd.conv_pbs with
| [] -> evd.last_mods
| _ -> ExistentialSet.add evk evd.last_mods }
let evar_declare hyps evk ty ?(src=(dummy_loc,InternalHole)) ?filter evd =
let filter =
if filter = None then
List.map (fun _ -> true) (named_context_of_val hyps)
else
(let filter = Option.get filter in
assert (List.length filter = List.length (named_context_of_val hyps));
filter)
in
{ evd with
evars = EvarMap.add_undefined evd.evars evk
{evar_hyps = hyps;
evar_concl = ty;
evar_body = Evar_empty;
evar_filter = filter;
evar_source = src;
evar_extra = Store.empty } }
let is_defined_evar evd (evk,_) = EvarMap.is_defined evd.evars evk
let is_undefined_evar evd c = match kind_of_term c with
| Evar ev -> not (is_defined_evar evd ev)
| _ -> false
Note : conv_pbs not satisying p are stored back in reverse order
let extract_conv_pbs evd p =
let (pbs,pbs1) =
List.fold_left
(fun (pbs,pbs1) pb ->
if p pb then
(pb::pbs,pbs1)
else
(pbs,pb::pbs1))
([],[])
evd.conv_pbs
in
{evd with conv_pbs = pbs1; last_mods = ExistentialSet.empty},
pbs
let extract_changed_conv_pbs evd p =
extract_conv_pbs evd (p evd.last_mods)
let extract_all_conv_pbs evd =
extract_conv_pbs evd (fun _ -> true)
let evar_merge evd evars =
{ evd with evars = EvarMap.merge evd.evars evars.evars }
let evar_list evd c =
let rec evrec acc c =
match kind_of_term c with
| Evar (evk, _ as ev) when mem evd evk -> ev :: acc
| _ -> fold_constr evrec acc c in
evrec [] c
let new_sort_variable ({ evars = (sigma,sm) } as d)=
let (u,scstr) = new_sort_var sm in
(Type u,{ d with evars = (sigma,scstr) } )
let is_sort_variable {evars=(_,sm)} s =
is_sort_var s sm
let whd_sort_variable {evars=(_,sm)} t = whd_sort_var sm t
let set_leq_sort_variable ({evars=(sigma,sm)}as d) u1 u2 =
{ d with evars = (sigma, set_leq u1 u2 sm) }
let define_sort_variable ({evars=(sigma,sm)}as d) u s =
{ d with evars = (sigma, set_sort_variable u s sm) }
let pr_sort_constraints {evars=(_,sm)} = pr_sort_cstrs sm
let meta_list evd = metamap_to_list evd.metas
let find_meta evd mv = Metamap.find mv evd.metas
let undefined_metas evd =
List.sort Pervasives.compare (map_succeed (function
| (n,Clval(_,_,typ)) -> failwith ""
| (n,Cltyp (_,typ)) -> n)
(meta_list evd))
let metas_of evd =
List.map (function
| (n,Clval(_,_,typ)) -> (n,typ.rebus)
| (n,Cltyp (_,typ)) -> (n,typ.rebus))
(meta_list evd)
let map_metas_fvalue f evd =
{ evd with metas =
Metamap.map
(function
| Clval(id,(c,s),typ) -> Clval(id,(mk_freelisted (f c.rebus),s),typ)
| x -> x) evd.metas }
let meta_opt_fvalue evd mv =
match Metamap.find mv evd.metas with
| Clval(_,b,_) -> Some b
| Cltyp _ -> None
let meta_defined evd mv =
match Metamap.find mv evd.metas with
| Clval _ -> true
| Cltyp _ -> false
let try_meta_fvalue evd mv =
match Metamap.find mv evd.metas with
| Clval(_,b,_) -> b
| Cltyp _ -> raise Not_found
let meta_fvalue evd mv =
try try_meta_fvalue evd mv
with Not_found -> anomaly "meta_fvalue: meta has no value"
let meta_value evd mv =
(fst (try_meta_fvalue evd mv)).rebus
let meta_ftype evd mv =
match Metamap.find mv evd.metas with
| Cltyp (_,b) -> b
| Clval(_,_,b) -> b
let meta_type evd mv = (meta_ftype evd mv).rebus
let meta_declare mv v ?(name=Anonymous) evd =
{ evd with metas = Metamap.add mv (Cltyp(name,mk_freelisted v)) evd.metas }
let meta_assign mv (v,pb) evd =
match Metamap.find mv evd.metas with
| Cltyp(na,ty) ->
{ evd with
metas = Metamap.add mv (Clval(na,(mk_freelisted v,pb),ty)) evd.metas }
| _ -> anomaly "meta_assign: already defined"
let meta_reassign mv (v,pb) evd =
match Metamap.find mv evd.metas with
| Clval(na,_,ty) ->
{ evd with
metas = Metamap.add mv (Clval(na,(mk_freelisted v,pb),ty)) evd.metas }
| _ -> anomaly "meta_reassign: not yet defined"
let meta_name evd mv =
try fst (clb_name (Metamap.find mv evd.metas)) with Not_found -> Anonymous
let meta_with_name evd id =
let na = Name id in
let (mvl,mvnodef) =
Metamap.fold
(fun n clb (l1,l2 as l) ->
let (na',def) = clb_name clb in
if na = na' then if def then (n::l1,l2) else (n::l1,n::l2)
else l)
evd.metas ([],[]) in
match mvnodef, mvl with
| _,[] ->
errorlabstrm "Evd.meta_with_name"
(str"No such bound variable " ++ pr_id id ++ str".")
| ([n],_|_,[n]) ->
n
| _ ->
errorlabstrm "Evd.meta_with_name"
(str "Binder name \"" ++ pr_id id ++
strbrk "\" occurs more than once in clause.")
let meta_merge evd1 evd2 =
{evd2 with
metas = List.fold_left (fun m (n,v) -> Metamap.add n v m)
evd2.metas (metamap_to_list evd1.metas) }
type metabinding = metavariable * constr * instance_status
let retract_coercible_metas evd =
let mc,ml =
Metamap.fold (fun n v (mc,ml) ->
match v with
| Clval (na,(b,(UserGiven,CoerceToType as s)),typ) ->
(n,b.rebus,s)::mc, Metamap.add n (Cltyp (na,typ)) ml
| v ->
mc, Metamap.add n v ml)
evd.metas ([],Metamap.empty) in
mc, { evd with metas = ml }
let rec list_assoc_in_triple x = function
[] -> raise Not_found
| (a,b,_)::l -> if compare a x = 0 then b else list_assoc_in_triple x l
let subst_defined_metas bl c =
let rec substrec c = match kind_of_term c with
| Meta i -> substrec (list_assoc_in_triple i bl)
| _ -> map_constr substrec c
in try Some (substrec c) with Not_found -> None
type open_constr = evar_map * constr
type 'a sigma = {
it : 'a ;
sigma : evar_map}
let sig_it x = x.it
let sig_sig x = x.sigma
type unsolvability_explanation = SeveralInstancesFound of int
let pr_instance_status (sc,typ) =
begin match sc with
| IsSubType -> str " [or a subtype of it]"
| IsSuperType -> str " [or a supertype of it]"
| ConvUpToEta 0 -> mt ()
| UserGiven -> mt ()
| ConvUpToEta n -> str" [or an eta-expansion up to " ++ int n ++ str" of it]"
end ++
begin match typ with
| CoerceToType -> str " [up to coercion]"
| TypeNotProcessed -> mt ()
| TypeProcessed -> str " [type is checked]"
end
let pr_meta_map mmap =
let pr_name = function
Name id -> str"[" ++ pr_id id ++ str"]"
| _ -> mt() in
let pr_meta_binding = function
| (mv,Cltyp (na,b)) ->
hov 0
(pr_meta mv ++ pr_name na ++ str " : " ++
print_constr b.rebus ++ fnl ())
| (mv,Clval(na,(b,s),t)) ->
hov 0
(pr_meta mv ++ pr_name na ++ str " := " ++
print_constr b.rebus ++
str " : " ++ print_constr t.rebus ++
spc () ++ pr_instance_status s ++ fnl ())
in
prlist pr_meta_binding (metamap_to_list mmap)
let pr_decl ((id,b,_),ok) =
match b with
| None -> if ok then pr_id id else (str "{" ++ pr_id id ++ str "}")
| Some c -> str (if ok then "(" else "{") ++ pr_id id ++ str ":=" ++
print_constr c ++ str (if ok then ")" else "}")
let pr_evar_info evi =
let decls = List.combine (evar_context evi) (evar_filter evi) in
let phyps = prlist_with_sep pr_spc pr_decl (List.rev decls) in
let pty = print_constr evi.evar_concl in
let pb =
match evi.evar_body with
| Evar_empty -> mt ()
| Evar_defined c -> spc() ++ str"=> " ++ print_constr c
in
hov 2 (str"[" ++ phyps ++ spc () ++ str"|- " ++ pty ++ pb ++ str"]")
let pr_evar_map_t (evars,cstrs as sigma) =
let evs =
if evars = EvarInfoMap.empty then mt ()
else
str"EVARS:"++brk(0,1)++
h 0 (prlist_with_sep pr_fnl
(fun (ev,evi) ->
h 0 (str(string_of_existential ev)++str"=="++ pr_evar_info evi))
(EvarMap.to_list sigma))++fnl()
and cs =
if cstrs = UniverseMap.empty then mt ()
else pr_sort_cstrs cstrs++fnl()
in evs ++ cs
let pr_constraints pbs =
h 0
(prlist_with_sep pr_fnl (fun (pbty,_,t1,t2) ->
print_constr t1 ++ spc() ++
str (match pbty with
| Reduction.CONV -> "=="
| Reduction.CUMUL -> "<=") ++
spc() ++ print_constr t2) pbs)
let pr_evar_map evd =
let pp_evm =
if evd.evars = EvarMap.empty then mt() else
pr_evar_map_t evd.evars++fnl() in
let cstrs =
if evd.conv_pbs = [] then mt() else
str"CONSTRAINTS:"++brk(0,1)++pr_constraints evd.conv_pbs++fnl() in
let pp_met =
if evd.metas = Metamap.empty then mt() else
str"METAS:"++brk(0,1)++pr_meta_map evd.metas in
v 0 (pp_evm ++ cstrs ++ pp_met)
let pr_metaset metas =
str "[" ++ prlist_with_sep spc pr_meta (Metaset.elements metas) ++ str "]"
|
2375571bf3a921d81223b85bc9b602ce1f9b38696cba28972ac74d18f00a5d1a | ianmbloom/gudni | Bezier.hs | {-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE PatternSynonyms #-}
| Functions on quadratic curves
module Graphics.Gudni.Figure.Bezier
( Bezier(..)
, pattern Bez
, maxStepsFromAccuracy
, splitBezier
, inverseArcLength
, eval
)
where
import Graphics.Gudni.Figure.Space
import Graphics.Gudni.Figure.Point
import Graphics.Gudni.Figure.ArcLength
import Numeric.Interval
import Linear
import Linear.Affine
import Linear
newtype Bezier s = Bezier {unBezier :: V3 (Point2 s)}
pattern Bez x y z = Bezier (V3 x y z)
instance Space s => HasSpace (Bezier s) where
type SpaceOf (Bezier s) = s
eval :: Num s => Bezier s -> s -> Point2 s
eval (Bezier (V3 p0 p1 p2)) t = let mt = 1 - t in
p0 ^* (mt * mt) + (p1 ^* (mt * 2) + p2 ^* t) ^* t
| Arc length of a single quadratic segment .
From
-- This computation is based on an analytical formula. Since that formula suffers
-- from numerical instability when the curve is very close to a straight line, we
detect that case and fall back to Legendre - Gauss quadrature .
arcLength runtime increases ~50x without the SPECIALIZE
{ - # SPECIALIZE arcLength : : - > SubSpace # - }
instance Space s => HasArcLength (Bezier s) where
arcLength (Bezier (V3 p0 p1 p2)) = let
d2 = p0 - 2.0 * p1 + p2
a = quadrance d2
d1 = p1 - p0
c = quadrance d1
in if a < 5e-4 * c
then
-- This case happens for nearly straight Béziers.
--
Calculate arclength using Legendre - Gauss quadrature using formula from Behdad
in https:--github.com / Pomax / BezierInfo-2 / issues/77
let
v0 = norm
(-0.492943519233745 *^ p0
+ 0.430331482911935 *^ p1
+ 0.0626120363218102 *^ p2)
v1 = norm ((p2 - p0) ^* 0.4444444444444444)
v2 = norm
(-0.0626120363218102 *^ p0
- 0.430331482911935 *^ p1
+ 0.492943519233745 *^ p2)
in v0 + v1 + v2
else
let
b = 2.0 * dot d2 d1
sabc = sqrt (a + b + c)
a2 = a ** (-0.5)
a32 = a2 ^ 3
c2 = 2.0 * sqrt c
ba_c2 = b * a2 + c2
v0 = 0.25 * a2 * a2 * b * (2.0 * sabc - c2) + sabc
in if ba_c2 < 1e-13 -- TODO: justify and fine-tune this exact constant.
then v0 -- This case happens for Béziers with a sharp kink.
else
v0 + 0.25
* a32
* (4.0 * c * a - b * b)
* log (((2.0 * a + b) * a2 + 2.0 * sabc) / ba_c2)
# INLINE splitBezier #
splitBezier :: (Floating s, Ord s) => Bezier s -> s -> (Bezier s, Bezier s)
splitBezier (Bez p0 p1 p2) t = (Bez p0 c1 pm, Bez pm c2 p2) where
c1 = lerp t p1 p0
c2 = lerp t p2 p1
pm = lerp t c2 c1
| @inverseArcLength ε bz l@ returns a parameter @t@ such that the
curve bz has length @l@ between its start point and More
-- precisely, the length is @ l ± ε@, for the specified accuracy.
{ - # SPECIALIZE inverseArcLength : : Int - > Maybe Float - > Float - > Float # - }
{ - # SPECIALIZE inverseArcLength : : Int - > Maybe Double - > > Double - > Double # - }
inverseArcLength :: (Space s) => Int -> Maybe s -> Bezier s -> s -> s
inverseArcLength max_steps m_accuracy bz goal_length =
go max_steps (0...1) 0
where
go n range last_length =
let
mid_t = midpoint range
mid_length = arcLength (fst (splitBezier bz mid_t))
in if n == 0 || closeEnough mid_length
then -- finish up by linear interpolation
if last_length < mid_length
then inf range + (mid_t - inf range) * (goal_length - last_length) / (mid_length - last_length)
else mid_t + (sup range - mid_t) * (goal_length - mid_length) / (last_length - mid_length)
else
let new_range = if mid_length > goal_length
then inf range ... mid_t
else mid_t ... sup range
in go (n-1) new_range mid_length
closeEnough l = case m_accuracy of
Nothing -> False
Just accuracy -> abs (l - goal_length) < accuracy
maxStepsFromAccuracy :: (Floating s, RealFrac s) => s -> Int
maxStepsFromAccuracy accuracy = ceiling (-1 * log accuracy / log 2)
| null | https://raw.githubusercontent.com/ianmbloom/gudni/fa69f1bf08c194effca05753afe5455ebae51234/src/Graphics/Gudni/Figure/Bezier.hs | haskell | # LANGUAGE TypeFamilies #
# LANGUAGE PatternSynonyms #
This computation is based on an analytical formula. Since that formula suffers
from numerical instability when the curve is very close to a straight line, we
This case happens for nearly straight Béziers.
github.com / Pomax / BezierInfo-2 / issues/77
TODO: justify and fine-tune this exact constant.
This case happens for Béziers with a sharp kink.
precisely, the length is @ l ± ε@, for the specified accuracy.
finish up by linear interpolation |
| Functions on quadratic curves
module Graphics.Gudni.Figure.Bezier
( Bezier(..)
, pattern Bez
, maxStepsFromAccuracy
, splitBezier
, inverseArcLength
, eval
)
where
import Graphics.Gudni.Figure.Space
import Graphics.Gudni.Figure.Point
import Graphics.Gudni.Figure.ArcLength
import Numeric.Interval
import Linear
import Linear.Affine
import Linear
newtype Bezier s = Bezier {unBezier :: V3 (Point2 s)}
pattern Bez x y z = Bezier (V3 x y z)
instance Space s => HasSpace (Bezier s) where
type SpaceOf (Bezier s) = s
eval :: Num s => Bezier s -> s -> Point2 s
eval (Bezier (V3 p0 p1 p2)) t = let mt = 1 - t in
p0 ^* (mt * mt) + (p1 ^* (mt * 2) + p2 ^* t) ^* t
| Arc length of a single quadratic segment .
From
detect that case and fall back to Legendre - Gauss quadrature .
arcLength runtime increases ~50x without the SPECIALIZE
{ - # SPECIALIZE arcLength : : - > SubSpace # - }
instance Space s => HasArcLength (Bezier s) where
arcLength (Bezier (V3 p0 p1 p2)) = let
d2 = p0 - 2.0 * p1 + p2
a = quadrance d2
d1 = p1 - p0
c = quadrance d1
in if a < 5e-4 * c
then
Calculate arclength using Legendre - Gauss quadrature using formula from Behdad
let
v0 = norm
(-0.492943519233745 *^ p0
+ 0.430331482911935 *^ p1
+ 0.0626120363218102 *^ p2)
v1 = norm ((p2 - p0) ^* 0.4444444444444444)
v2 = norm
(-0.0626120363218102 *^ p0
- 0.430331482911935 *^ p1
+ 0.492943519233745 *^ p2)
in v0 + v1 + v2
else
let
b = 2.0 * dot d2 d1
sabc = sqrt (a + b + c)
a2 = a ** (-0.5)
a32 = a2 ^ 3
c2 = 2.0 * sqrt c
ba_c2 = b * a2 + c2
v0 = 0.25 * a2 * a2 * b * (2.0 * sabc - c2) + sabc
else
v0 + 0.25
* a32
* (4.0 * c * a - b * b)
* log (((2.0 * a + b) * a2 + 2.0 * sabc) / ba_c2)
# INLINE splitBezier #
splitBezier :: (Floating s, Ord s) => Bezier s -> s -> (Bezier s, Bezier s)
splitBezier (Bez p0 p1 p2) t = (Bez p0 c1 pm, Bez pm c2 p2) where
c1 = lerp t p1 p0
c2 = lerp t p2 p1
pm = lerp t c2 c1
| @inverseArcLength ε bz l@ returns a parameter @t@ such that the
curve bz has length @l@ between its start point and More
{ - # SPECIALIZE inverseArcLength : : Int - > Maybe Float - > Float - > Float # - }
{ - # SPECIALIZE inverseArcLength : : Int - > Maybe Double - > > Double - > Double # - }
inverseArcLength :: (Space s) => Int -> Maybe s -> Bezier s -> s -> s
inverseArcLength max_steps m_accuracy bz goal_length =
go max_steps (0...1) 0
where
go n range last_length =
let
mid_t = midpoint range
mid_length = arcLength (fst (splitBezier bz mid_t))
in if n == 0 || closeEnough mid_length
if last_length < mid_length
then inf range + (mid_t - inf range) * (goal_length - last_length) / (mid_length - last_length)
else mid_t + (sup range - mid_t) * (goal_length - mid_length) / (last_length - mid_length)
else
let new_range = if mid_length > goal_length
then inf range ... mid_t
else mid_t ... sup range
in go (n-1) new_range mid_length
closeEnough l = case m_accuracy of
Nothing -> False
Just accuracy -> abs (l - goal_length) < accuracy
maxStepsFromAccuracy :: (Floating s, RealFrac s) => s -> Int
maxStepsFromAccuracy accuracy = ceiling (-1 * log accuracy / log 2)
|
d032b482528c09dc1980326862ed7ad9abfd65817d2aa6388e894968a5289867 | BranchTaken/Hemlock | deq.ml | open Rudiments0
type 'a t =
uns * 'a Stream.t * 'a Stream.t * uns * 'a Stream.t * 'a Stream.t
Increment size for rebuilding ; must be either 2 or 3 . Reference : Double - ended queues section in
* Purely Functional Data Structures by .
* Purely Functional Data Structures by Chris Okasaki. *)
let c = 2L
let empty = (
0L, lazy Stream.Nil, lazy Stream.Nil,
0L, lazy Stream.Nil, lazy Stream.Nil
)
let length (lf, _, _, lr, _, _) =
lf + lr
let is_empty (lf, _, _, lr, _, _) =
lf + lr = 0L
let exec1 = function
| lazy (Stream.Cons(_, s')) -> s'
| s -> s
let exec2 s =
exec1 (exec1 s)
let rec rotate_rev (f, r, a) =
lazy begin
match f with
| lazy Stream.Nil -> Lazy.force (Stream.concat (Stream.rev r) a)
| lazy (Stream.Cons(elm, f')) -> begin
let r' = Stream.drop c r in
let a' = Stream.concat (Stream.rev (Stream.take c r)) a in
Lazy.force (Stream.push elm (rotate_rev (f', r', a')))
end
end
let rec rotate_drop f j r =
lazy begin
match j < c, f with
| true, _ -> Lazy.force (rotate_rev (f, (Stream.drop j r), Stream.empty))
| false, lazy Stream.Nil -> not_reached ()
| false, lazy (Stream.Cons(elm, f')) ->
Lazy.force (Stream.push elm (rotate_drop f' (j - c) (Stream.drop c r)))
end
let check t =
let lf, f, _, lr, r, _ = t in
if lf > (c * lr) + 1L then
let i = (lf + lr) / 2L in
let j = lf + lr - i in
let f' = Stream.take i f in
let r' = rotate_drop r i f in
(i, f', f', j, r', r')
else if lr > (c * lf) + 1L then
let j = (lf + lr) / 2L in
let i = lf + lr - j in
let r' = Stream.take j r in
let f' = rotate_drop f j r in
(i, f', f', j, r', r')
else
t
let hd (_, f, _, _, r, _) =
match f, r with
| lazy Stream.Nil, lazy Stream.Nil -> not_reached ()
| lazy Stream.Nil, lazy (Stream.Cons(elm, _)) -> elm
| lazy (Stream.Cons(elm, _)), _ -> elm
let tl (lf, f, sf, lr, r, sr) =
match f, r with
| lazy Stream.Nil, lazy Stream.Nil -> not_reached ()
| lazy Stream.Nil, lazy (Stream.Cons(_, _)) -> empty
| lazy (Stream.Cons(_, f')), _ -> begin
let lf' = lf - 1L in
let sf' = exec2 sf in
let sr' = exec2 sr in
check (lf', f', sf', lr, r, sr')
end
let rev (lf, f, sf, lr, r, sr) =
(lr, r, sr, lf, f, sf)
let back t =
hd (rev t)
let front t =
rev (tl (rev t))
let push elm (lf, f, sf, lr, r, sr) =
let lf' = lf + 1L in
let f' = Stream.push elm f in
let sf' = exec1 sf in
let sr' = exec1 sr in
check (lf', f', sf', lr, r, sr')
let push_back elm t =
rev (push elm (rev t))
let pop t =
hd t, tl t
let pop_back t =
back t, front t
let pp pp_elm (_lf, f, _sf, _lr, r, _sr) formatter =
let rec fn s formatter = begin
match s with
| lazy Stream.Nil -> formatter
| lazy (Cons(elm, lazy Stream.Nil)) -> formatter |> pp_elm elm
| lazy (Cons(elm, s')) ->
formatter
|> pp_elm elm
|> Fmt.fmt ", "
|> fn s'
end in
formatter
|> Fmt.fmt "("
|> fn f
|> Fmt.fmt " | "
|> fn (Stream.rev r)
|> Fmt.fmt ")"
| null | https://raw.githubusercontent.com/BranchTaken/Hemlock/f3604ceda4f75cf18b6ee2b1c2f3c5759ad495a5/bootstrap/src/basis/deq.ml | ocaml | open Rudiments0
type 'a t =
uns * 'a Stream.t * 'a Stream.t * uns * 'a Stream.t * 'a Stream.t
Increment size for rebuilding ; must be either 2 or 3 . Reference : Double - ended queues section in
* Purely Functional Data Structures by .
* Purely Functional Data Structures by Chris Okasaki. *)
let c = 2L
let empty = (
0L, lazy Stream.Nil, lazy Stream.Nil,
0L, lazy Stream.Nil, lazy Stream.Nil
)
let length (lf, _, _, lr, _, _) =
lf + lr
let is_empty (lf, _, _, lr, _, _) =
lf + lr = 0L
let exec1 = function
| lazy (Stream.Cons(_, s')) -> s'
| s -> s
let exec2 s =
exec1 (exec1 s)
let rec rotate_rev (f, r, a) =
lazy begin
match f with
| lazy Stream.Nil -> Lazy.force (Stream.concat (Stream.rev r) a)
| lazy (Stream.Cons(elm, f')) -> begin
let r' = Stream.drop c r in
let a' = Stream.concat (Stream.rev (Stream.take c r)) a in
Lazy.force (Stream.push elm (rotate_rev (f', r', a')))
end
end
let rec rotate_drop f j r =
lazy begin
match j < c, f with
| true, _ -> Lazy.force (rotate_rev (f, (Stream.drop j r), Stream.empty))
| false, lazy Stream.Nil -> not_reached ()
| false, lazy (Stream.Cons(elm, f')) ->
Lazy.force (Stream.push elm (rotate_drop f' (j - c) (Stream.drop c r)))
end
let check t =
let lf, f, _, lr, r, _ = t in
if lf > (c * lr) + 1L then
let i = (lf + lr) / 2L in
let j = lf + lr - i in
let f' = Stream.take i f in
let r' = rotate_drop r i f in
(i, f', f', j, r', r')
else if lr > (c * lf) + 1L then
let j = (lf + lr) / 2L in
let i = lf + lr - j in
let r' = Stream.take j r in
let f' = rotate_drop f j r in
(i, f', f', j, r', r')
else
t
let hd (_, f, _, _, r, _) =
match f, r with
| lazy Stream.Nil, lazy Stream.Nil -> not_reached ()
| lazy Stream.Nil, lazy (Stream.Cons(elm, _)) -> elm
| lazy (Stream.Cons(elm, _)), _ -> elm
let tl (lf, f, sf, lr, r, sr) =
match f, r with
| lazy Stream.Nil, lazy Stream.Nil -> not_reached ()
| lazy Stream.Nil, lazy (Stream.Cons(_, _)) -> empty
| lazy (Stream.Cons(_, f')), _ -> begin
let lf' = lf - 1L in
let sf' = exec2 sf in
let sr' = exec2 sr in
check (lf', f', sf', lr, r, sr')
end
let rev (lf, f, sf, lr, r, sr) =
(lr, r, sr, lf, f, sf)
let back t =
hd (rev t)
let front t =
rev (tl (rev t))
let push elm (lf, f, sf, lr, r, sr) =
let lf' = lf + 1L in
let f' = Stream.push elm f in
let sf' = exec1 sf in
let sr' = exec1 sr in
check (lf', f', sf', lr, r, sr')
let push_back elm t =
rev (push elm (rev t))
let pop t =
hd t, tl t
let pop_back t =
back t, front t
let pp pp_elm (_lf, f, _sf, _lr, r, _sr) formatter =
let rec fn s formatter = begin
match s with
| lazy Stream.Nil -> formatter
| lazy (Cons(elm, lazy Stream.Nil)) -> formatter |> pp_elm elm
| lazy (Cons(elm, s')) ->
formatter
|> pp_elm elm
|> Fmt.fmt ", "
|> fn s'
end in
formatter
|> Fmt.fmt "("
|> fn f
|> Fmt.fmt " | "
|> fn (Stream.rev r)
|> Fmt.fmt ")"
| |
041d97abed799e72caad35a7ca37074deea511a6c73aa7e4ba8f32a8a6e7a952 | cxphoe/SICP-solutions | compiler.rkt | (load "ev-operations\\expression.rkt")
(load "compiler-instruction-sequence.rkt")
(load "compiler-label.rkt")
(load "compiler-lexical-address.rkt")
(load "compiler-open-code.rkt")
(load "scan-out-defines.rkt")
; log:
; >> an original compiler
> > adopt implementation about open code in ex-5.38
; >> adopt implementation about lexical address in ex-5.39 ~ ex-5.44
; and change the implementation about open code
; >> adopt implementation of scan-out-defines
; >> adopt implementation of checking rebound open code operators
; >> use expression.rkt from directory <ev-operations>
; >> extend the compile-procedure-call to allow compiled code can
; call interpreted procedure
; >> fix a bug in compile-procedure-call that will create a out-of-order
; instruction sequences
(define (test text)
(for-each (lambda (x)
(if (pair? x)
(begin (display " ")))
(display x)
(newline))
(caddr (compile text 'val 'return '()))))
(define (compile exp target linkage compile-env) ; changed
(cond ((self-evaluating? exp)
(compile-self-evaluating exp target linkage))
((open-code? exp compile-env)
(compile-open-code exp target linkage compile-env))
((quoted? exp) (compile-quoted exp target linkage))
((variable? exp)
(compile-variable exp target linkage compile-env))
((assignment? exp)
(compile-assignment exp target linkage compile-env))
((definition? exp)
(compile-definition exp target linkage compile-env))
((if? exp)
(compile-if exp target linkage compile-env))
((lambda? exp)
(compile-lambda exp target linkage compile-env))
((begin? exp)
(compile-sequence (begin-actions exp) target linkage compile-env))
((cond? exp) (compile (cond->if exp) target linkage compile-env))
((let? exp) (compile (let->combination exp)
target linkage compile-env))
((application? exp)
(compile-application exp target linkage compile-env))
(else
(error "Unknown expression type -- COMPILE" exp))))
(define (compile-linkage linkage)
(cond ((eq? linkage 'return)
(make-instruction-sequence '(continue) '()
'((goto (reg continue)))))
((eq? linkage 'next)
(empty-instruction-sequence))
(else
(make-instruction-sequence '() '()
`((goto (label ,linkage)))))))
(define (end-with-linkage linkage instruction-sequence)
(preserving '(continue)
instruction-sequence
(compile-linkage linkage)))
(define (compile-self-evaluating exp target linkage)
(end-with-linkage linkage
(make-instruction-sequence
'() (list target)
`((assign ,target (const ,exp))))))
(define (compile-quoted exp target linkage)
(end-with-linkage linkage
(make-instruction-sequence '() (list target)
`((assign ,target (const ,(text-of-quotation exp)))))))
; variable
(define (compile-variable exp target linkage compile-env)
(let ((address (find-variable exp compile-env))
(op 'lookup-variable-value))
(if (not (eq? address 'not-found))
(begin (set! op 'lexical-address-lookup)
(set! exp address)))
(end-with-linkage linkage
(make-instruction-sequence '(env) (list target)
`((assign ,target
(op ,op)
(const ,exp)
(reg env)))))))
; assignment
(define (compile-assignment exp target linkage compile-env)
(let* ((var (assignment-variable exp))
(get-value-code
(compile (assignment-value exp) 'val 'next compile-env))
(address (find-variable var compile-env))
(op 'set-variable-value!))
(if (not (eq? address 'not-found))
(begin (set! op 'lexical-address-set!)
(set! var address)))
(end-with-linkage linkage
(preserving '(env)
get-value-code
(make-instruction-sequence '(env val) (list target)
`((perform (op ,op)
(const ,var)
(reg val)
(reg env))
(assign ,target (const ok))))))))
; define
(define (compile-definition exp target linkage compile-env)
; the interval definition was transformed, so definition don't
; to extend compile-env
(let ((var (definition-variable exp))
(get-value-code
(compile (definition-value exp) 'val 'next compile-env)))
(end-with-linkage linkage
(preserving '(env)
get-value-code
(make-instruction-sequence '(env val) (list target)
`((perform (op define-variable!)
(const ,var)
(reg val)
(reg env))
(assign ,target (const ok))))))))
; if:
; <compiling if-predicate with val as target and next as linkage>
; (test (op false?) (reg val))
; (branch (label false-branch))
; true-branch
; <compiling result of if-consequent with given target and linkage,
; or with after-if as it linkage>
; false-branch
< compiling result of if - alternative with target and linkage >
; after-if
(define (compile-if exp target linkage compile-env)
(let ((t-branch (make-label 'true-branch))
(f-branch (make-label 'false-branch))
(after-if (make-label 'after-if)))
(let ((consequent-linkage
(if (eq? linkage 'next) after-if linkage)))
(let ((p-code (compile (if-predicate exp) 'val 'next compile-env))
(c-code (compile (if-consequent exp)
target
consequent-linkage
compile-env))
(a-code
(compile (if-alternative exp) target linkage compile-env)))
(preserving '(env continue)
p-code
(append-instruction-sequences
(make-instruction-sequence '(val) '()
`((test (op false?) (reg val))
(branch (label ,f-branch))))
(parallel-instruction-sequences
(append-instruction-sequences t-branch c-code)
(append-instruction-sequences f-branch a-code))
after-if))))))
; sequence
(define (compile-sequence seq target linkage compile-env)
(if (last-exp? seq)
(compile (first-exp seq) target linkage compile-env)
(preserving '(env continue)
(compile (first-exp seq) target 'next compile-env)
(compile-sequence (rest-exps seq) target linkage compile-env))))
; complied procedure
(define (make-compiled-procedure entry env)
(list 'compiled-procedure entry env)) ; save the entry and current env
(define (compiled-procedure? proc)
(tagged-list? proc 'compiled-procedure))
(define (compiled-procedure-entry c-proc) (cadr c-proc))
(define (compiled-procedure-env c-proc) (caddr c-proc))
; lambda:
; <construct procedure and assign it to target>
< code turn to linkage or ( goto ( label after - lambda ) )
; <compiling result of lambda body>
; after-lambda
(define (compile-lambda exp target linkage compile-env)
(let ((proc-entry (make-label 'entry))
(after-lambda (make-label 'after-lambda)))
(let ((lambda-linkage
(if (eq? linkage 'next) after-lambda linkage)))
(append-instruction-sequences
(tack-on-instruction-sequence
(end-with-linkage lambda-linkage
(make-instruction-sequence '(env) (list target)
`((assign ,target
(op make-compiled-procedure)
(label ,proc-entry)
(reg env)))))
(compile-lambda-body exp proc-entry compile-env))
after-lambda))))
(define (compile-lambda-body exp proc-entry compile-env)
(let ((formals (lambda-parameters exp)))
(append-instruction-sequences
(make-instruction-sequence '(env proc argl) '(env)
`(,proc-entry
(assign env (op compiled-procedure-env) (reg proc))
(assign env
(op extend-environment)
(const ,formals)
(reg argl)
(reg env))))
(compile-sequence (scan-out-defines (lambda-body exp))
'val 'return
(cons formals compile-env)))))
(define (compile-application exp target linkage compile-env)
(let ((proc-code (compile (operator exp) 'proc 'next compile-env))
(operand-codes
(map (lambda (operand) (compile operand 'val 'next compile-env))
(operands exp))))
(preserving '(env continue)
proc-code
(preserving '(proc continue)
(construct-arglist operand-codes)
(compile-procedure-call target linkage)))))
< compiling result of last operand with as its target >
; (assign argl (op list) (reg val))
< compiling result of next operand with as its target >
; ...
< compiling result of first opernad with as its target >
( assign argl ( op cons ) ( reg val ) ( reg argl ) )
(define (construct-arglist operand-codes)
(let ((operand-codes (reverse operand-codes)))
(if (null? operand-codes)
(make-instruction-sequence '() '(argl)
'((assign argl (const ()))))
(let ((code-to-get-last-arg
(append-instruction-sequences
(car operand-codes)
(make-instruction-sequence '(val) '(argl)
'((assign argl (op list) (reg val)))))))
(if (null? (cdr operand-codes))
code-to-get-last-arg
(preserving '(env)
code-to-get-last-arg
(code-to-get-rest-args (cdr operand-codes))))))))
(define (code-to-get-rest-args operand-codes)
(let ((code-for-next-arg
(preserving '(argl)
(car operand-codes)
(make-instruction-sequence
'(val argl) '(argl)
'((assign argl (op cons) (reg val) (reg argl)))))))
(if (null? (cdr operand-codes))
code-for-next-arg
(preserving '(env)
code-for-next-arg
(code-to-get-rest-args (cdr operand-codes))))))
; procedure apply:
; (test (op primitive-procedure?) (reg proc))
; (branch (label primitive-branch))
; compiled-branch
; <codes applying the compiled procedure to given target and linkage>
; primitive-branch
; (assign <target>
; (op apply-primitive-pricedure)
; (reg proc)
( reg argl ) )
; <linkage>
; after-call
(define (compile-procedure-call target linkage)
(let ((primitive-branch (make-label 'primitive-branch))
(compound-branch (make-label 'compound-branch))
(compiled-branch (make-label 'compiled-branch)); create branch
(after-call (make-label 'after-call)))
(let ((compiled-linkage
(if (eq? linkage 'next) after-call linkage)))
(append-instruction-sequences
(make-instruction-sequence '(proc) '()
`((test (op primitive-procedure?) (reg proc))
(branch (label ,primitive-branch))
(test (op compound-procedure?) (reg proc)) ; add test
(branch (label ,compound-branch)))) ;
(parallel-instruction-sequences
(append-instruction-sequences
compiled-branch
(compile-proc-appl target compiled-linkage))
(parallel-instruction-sequences
(append-instruction-sequences ;
compound-branch ; compound branch
(compound-apply target compiled-linkage)) ;
(append-instruction-sequences
primitive-branch
(primitive-apply target linkage)) ; I have extracted the primitive apply
))
after-call))))
(define all-regs '(env proc val argl continue))
(define (primitive-apply target linkage)
(end-with-linkage linkage
(make-instruction-sequence '(proc argl) (list target)
`((assign
,target
(op apply-primitive-procedure)
(reg proc)
(reg argl))))))
(define (compound-apply target linkage)
(cond ((and (eq? target 'val) (not (eq? linkage 'return)))
(make-instruction-sequence '(proc) all-regs
`((assign continue (label ,linkage))
(save continue)
(goto (reg compapp)))))
((and (not (eq? target 'val))
(not (eq? linkage 'return)))
(let ((proc-return (make-label 'proc-return)))
(make-instruction-sequence '(proc) all-regs
`((assign continue (label ,proc-return))
(save continue)
(goto (reg compapp))
,proc-return
(assign ,target (reg val))
(goto (label ,linkage))))))
((and (eq? target 'val) (eq? linkage 'return))
(make-instruction-sequence '(proc continue) all-regs
`((save continue)
(goto (reg compapp)))))
((and (not (eq? target 'val)) (eq? linkage 'return))
(error "return linkage, target not val -- COMPILE" target))))
(define (compile-proc-appl target linkage)
(cond ((and (eq? target 'val) (not (eq? linkage 'return)))
(make-instruction-sequence '(proc) all-regs
`((assign continue (label ,linkage))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val)))))
((and (not (eq? target 'val))
(not (eq? linkage 'return)))
(let ((proc-return (make-label 'proc-return)))
(make-instruction-sequence '(proc) all-regs
`((assign continue (label ,proc-return))
(assign val (op compiled-procedure-entry)
(reg proc))
(goto (reg val))
,proc-return
(assign ,target (reg val))
(goto (label ,linkage))))))
((and (eq? target 'val) (eq? linkage 'return))
(make-instruction-sequence '(proc continue) all-regs
'((assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val)))))
((and (not (eq? target 'val)) (eq? linkage 'return))
(error "return linkage, target not val -- COMPILE" target))))
| null | https://raw.githubusercontent.com/cxphoe/SICP-solutions/d35bb688db0320f6efb3b3bde1a14ce21da319bd/Chapter%205-Computing%20with%20Register%20Machines/5.%20Compile/compiler.rkt | racket | log:
>> an original compiler
>> adopt implementation about lexical address in ex-5.39 ~ ex-5.44
and change the implementation about open code
>> adopt implementation of scan-out-defines
>> adopt implementation of checking rebound open code operators
>> use expression.rkt from directory <ev-operations>
>> extend the compile-procedure-call to allow compiled code can
call interpreted procedure
>> fix a bug in compile-procedure-call that will create a out-of-order
instruction sequences
changed
variable
assignment
define
the interval definition was transformed, so definition don't
to extend compile-env
if:
<compiling if-predicate with val as target and next as linkage>
(test (op false?) (reg val))
(branch (label false-branch))
true-branch
<compiling result of if-consequent with given target and linkage,
or with after-if as it linkage>
false-branch
after-if
sequence
complied procedure
save the entry and current env
lambda:
<construct procedure and assign it to target>
<compiling result of lambda body>
after-lambda
(assign argl (op list) (reg val))
...
procedure apply:
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch))
compiled-branch
<codes applying the compiled procedure to given target and linkage>
primitive-branch
(assign <target>
(op apply-primitive-pricedure)
(reg proc)
<linkage>
after-call
create branch
add test
compound branch
I have extracted the primitive apply | (load "ev-operations\\expression.rkt")
(load "compiler-instruction-sequence.rkt")
(load "compiler-label.rkt")
(load "compiler-lexical-address.rkt")
(load "compiler-open-code.rkt")
(load "scan-out-defines.rkt")
> > adopt implementation about open code in ex-5.38
(define (test text)
(for-each (lambda (x)
(if (pair? x)
(begin (display " ")))
(display x)
(newline))
(caddr (compile text 'val 'return '()))))
(cond ((self-evaluating? exp)
(compile-self-evaluating exp target linkage))
((open-code? exp compile-env)
(compile-open-code exp target linkage compile-env))
((quoted? exp) (compile-quoted exp target linkage))
((variable? exp)
(compile-variable exp target linkage compile-env))
((assignment? exp)
(compile-assignment exp target linkage compile-env))
((definition? exp)
(compile-definition exp target linkage compile-env))
((if? exp)
(compile-if exp target linkage compile-env))
((lambda? exp)
(compile-lambda exp target linkage compile-env))
((begin? exp)
(compile-sequence (begin-actions exp) target linkage compile-env))
((cond? exp) (compile (cond->if exp) target linkage compile-env))
((let? exp) (compile (let->combination exp)
target linkage compile-env))
((application? exp)
(compile-application exp target linkage compile-env))
(else
(error "Unknown expression type -- COMPILE" exp))))
(define (compile-linkage linkage)
(cond ((eq? linkage 'return)
(make-instruction-sequence '(continue) '()
'((goto (reg continue)))))
((eq? linkage 'next)
(empty-instruction-sequence))
(else
(make-instruction-sequence '() '()
`((goto (label ,linkage)))))))
(define (end-with-linkage linkage instruction-sequence)
(preserving '(continue)
instruction-sequence
(compile-linkage linkage)))
(define (compile-self-evaluating exp target linkage)
(end-with-linkage linkage
(make-instruction-sequence
'() (list target)
`((assign ,target (const ,exp))))))
(define (compile-quoted exp target linkage)
(end-with-linkage linkage
(make-instruction-sequence '() (list target)
`((assign ,target (const ,(text-of-quotation exp)))))))
(define (compile-variable exp target linkage compile-env)
(let ((address (find-variable exp compile-env))
(op 'lookup-variable-value))
(if (not (eq? address 'not-found))
(begin (set! op 'lexical-address-lookup)
(set! exp address)))
(end-with-linkage linkage
(make-instruction-sequence '(env) (list target)
`((assign ,target
(op ,op)
(const ,exp)
(reg env)))))))
(define (compile-assignment exp target linkage compile-env)
(let* ((var (assignment-variable exp))
(get-value-code
(compile (assignment-value exp) 'val 'next compile-env))
(address (find-variable var compile-env))
(op 'set-variable-value!))
(if (not (eq? address 'not-found))
(begin (set! op 'lexical-address-set!)
(set! var address)))
(end-with-linkage linkage
(preserving '(env)
get-value-code
(make-instruction-sequence '(env val) (list target)
`((perform (op ,op)
(const ,var)
(reg val)
(reg env))
(assign ,target (const ok))))))))
(define (compile-definition exp target linkage compile-env)
(let ((var (definition-variable exp))
(get-value-code
(compile (definition-value exp) 'val 'next compile-env)))
(end-with-linkage linkage
(preserving '(env)
get-value-code
(make-instruction-sequence '(env val) (list target)
`((perform (op define-variable!)
(const ,var)
(reg val)
(reg env))
(assign ,target (const ok))))))))
< compiling result of if - alternative with target and linkage >
(define (compile-if exp target linkage compile-env)
(let ((t-branch (make-label 'true-branch))
(f-branch (make-label 'false-branch))
(after-if (make-label 'after-if)))
(let ((consequent-linkage
(if (eq? linkage 'next) after-if linkage)))
(let ((p-code (compile (if-predicate exp) 'val 'next compile-env))
(c-code (compile (if-consequent exp)
target
consequent-linkage
compile-env))
(a-code
(compile (if-alternative exp) target linkage compile-env)))
(preserving '(env continue)
p-code
(append-instruction-sequences
(make-instruction-sequence '(val) '()
`((test (op false?) (reg val))
(branch (label ,f-branch))))
(parallel-instruction-sequences
(append-instruction-sequences t-branch c-code)
(append-instruction-sequences f-branch a-code))
after-if))))))
(define (compile-sequence seq target linkage compile-env)
(if (last-exp? seq)
(compile (first-exp seq) target linkage compile-env)
(preserving '(env continue)
(compile (first-exp seq) target 'next compile-env)
(compile-sequence (rest-exps seq) target linkage compile-env))))
(define (make-compiled-procedure entry env)
(define (compiled-procedure? proc)
(tagged-list? proc 'compiled-procedure))
(define (compiled-procedure-entry c-proc) (cadr c-proc))
(define (compiled-procedure-env c-proc) (caddr c-proc))
< code turn to linkage or ( goto ( label after - lambda ) )
(define (compile-lambda exp target linkage compile-env)
(let ((proc-entry (make-label 'entry))
(after-lambda (make-label 'after-lambda)))
(let ((lambda-linkage
(if (eq? linkage 'next) after-lambda linkage)))
(append-instruction-sequences
(tack-on-instruction-sequence
(end-with-linkage lambda-linkage
(make-instruction-sequence '(env) (list target)
`((assign ,target
(op make-compiled-procedure)
(label ,proc-entry)
(reg env)))))
(compile-lambda-body exp proc-entry compile-env))
after-lambda))))
(define (compile-lambda-body exp proc-entry compile-env)
(let ((formals (lambda-parameters exp)))
(append-instruction-sequences
(make-instruction-sequence '(env proc argl) '(env)
`(,proc-entry
(assign env (op compiled-procedure-env) (reg proc))
(assign env
(op extend-environment)
(const ,formals)
(reg argl)
(reg env))))
(compile-sequence (scan-out-defines (lambda-body exp))
'val 'return
(cons formals compile-env)))))
(define (compile-application exp target linkage compile-env)
(let ((proc-code (compile (operator exp) 'proc 'next compile-env))
(operand-codes
(map (lambda (operand) (compile operand 'val 'next compile-env))
(operands exp))))
(preserving '(env continue)
proc-code
(preserving '(proc continue)
(construct-arglist operand-codes)
(compile-procedure-call target linkage)))))
< compiling result of last operand with as its target >
< compiling result of next operand with as its target >
< compiling result of first opernad with as its target >
( assign argl ( op cons ) ( reg val ) ( reg argl ) )
(define (construct-arglist operand-codes)
(let ((operand-codes (reverse operand-codes)))
(if (null? operand-codes)
(make-instruction-sequence '() '(argl)
'((assign argl (const ()))))
(let ((code-to-get-last-arg
(append-instruction-sequences
(car operand-codes)
(make-instruction-sequence '(val) '(argl)
'((assign argl (op list) (reg val)))))))
(if (null? (cdr operand-codes))
code-to-get-last-arg
(preserving '(env)
code-to-get-last-arg
(code-to-get-rest-args (cdr operand-codes))))))))
(define (code-to-get-rest-args operand-codes)
(let ((code-for-next-arg
(preserving '(argl)
(car operand-codes)
(make-instruction-sequence
'(val argl) '(argl)
'((assign argl (op cons) (reg val) (reg argl)))))))
(if (null? (cdr operand-codes))
code-for-next-arg
(preserving '(env)
code-for-next-arg
(code-to-get-rest-args (cdr operand-codes))))))
( reg argl ) )
(define (compile-procedure-call target linkage)
(let ((primitive-branch (make-label 'primitive-branch))
(compound-branch (make-label 'compound-branch))
(after-call (make-label 'after-call)))
(let ((compiled-linkage
(if (eq? linkage 'next) after-call linkage)))
(append-instruction-sequences
(make-instruction-sequence '(proc) '()
`((test (op primitive-procedure?) (reg proc))
(branch (label ,primitive-branch))
(parallel-instruction-sequences
(append-instruction-sequences
compiled-branch
(compile-proc-appl target compiled-linkage))
(parallel-instruction-sequences
(append-instruction-sequences
primitive-branch
))
after-call))))
(define all-regs '(env proc val argl continue))
(define (primitive-apply target linkage)
(end-with-linkage linkage
(make-instruction-sequence '(proc argl) (list target)
`((assign
,target
(op apply-primitive-procedure)
(reg proc)
(reg argl))))))
(define (compound-apply target linkage)
(cond ((and (eq? target 'val) (not (eq? linkage 'return)))
(make-instruction-sequence '(proc) all-regs
`((assign continue (label ,linkage))
(save continue)
(goto (reg compapp)))))
((and (not (eq? target 'val))
(not (eq? linkage 'return)))
(let ((proc-return (make-label 'proc-return)))
(make-instruction-sequence '(proc) all-regs
`((assign continue (label ,proc-return))
(save continue)
(goto (reg compapp))
,proc-return
(assign ,target (reg val))
(goto (label ,linkage))))))
((and (eq? target 'val) (eq? linkage 'return))
(make-instruction-sequence '(proc continue) all-regs
`((save continue)
(goto (reg compapp)))))
((and (not (eq? target 'val)) (eq? linkage 'return))
(error "return linkage, target not val -- COMPILE" target))))
(define (compile-proc-appl target linkage)
(cond ((and (eq? target 'val) (not (eq? linkage 'return)))
(make-instruction-sequence '(proc) all-regs
`((assign continue (label ,linkage))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val)))))
((and (not (eq? target 'val))
(not (eq? linkage 'return)))
(let ((proc-return (make-label 'proc-return)))
(make-instruction-sequence '(proc) all-regs
`((assign continue (label ,proc-return))
(assign val (op compiled-procedure-entry)
(reg proc))
(goto (reg val))
,proc-return
(assign ,target (reg val))
(goto (label ,linkage))))))
((and (eq? target 'val) (eq? linkage 'return))
(make-instruction-sequence '(proc continue) all-regs
'((assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val)))))
((and (not (eq? target 'val)) (eq? linkage 'return))
(error "return linkage, target not val -- COMPILE" target))))
|
b49d6e89f03cde34863f63e3ac98d7cbe131c8574b7701fe2ae15705d75b023b | rhaberkorn/ermacs | em_scan.erl | %%%----------------------------------------------------------------------
%%% File : em_scan.erl
Author : < >
%%% Purpose : Scanner for leex-style DFAs.
Created : 1 May 2001 by < >
%%%----------------------------------------------------------------------
-module(em_scan).
-author('').
-record(scanner, {initial_state, dfa_fn, action_fn}).
Token record . The actual lexeme , if returned by the scanner , is
%% discarded - all that's taken from the user-written "actions" is the
%% token type. Instead we just keep the start/finish positions in a
%% cord.
%%
%% Not retaining line/column information. Hopefully that's convenient
%% to derive later.
-record(token,
{
%% type chosen by scanner. There is also a special type:
' em_skipped ' , when the scanner returns ' ' but
%% we record it anyway.
type,
%% start position in cord
start,
%% finish position in cord (point *after* the last character)
finish,
number of characters beyond the end of the lexeme that
%% the scanner state machine examined, recorded to track
%% dependency
lookahead,
%% for book keeping, saying whether the token is known to
%% need re-scanning
dirty=false
}).
-compile(export_all).
%%-export([Function/Arity, ...]).
%% Bogus line number to pass to leex/yecc, because I don't want to
%% track lines at this low level. It's not safe to use an atom, but
%% hopefully -42 looks deliberate enough to prompt a grep :-)
-define(line, -42). %% Confusing number appearing where line # should be :-)
make_scanner(State0, DFA, Action) ->
#scanner{initial_state=State0,
dfa_fn=DFA,
action_fn=Action}.
make_scheme_scanner() -> make_leex_scanner(em_scheme_scan).
make_erlang_scanner() -> make_leex_scanner(em_erlang_scan).
make_test_scanner() -> make_leex_scanner(em_test_scan).
make_leex_scanner(Mod) ->
make_scanner(Mod:yystate(),
{Mod, yystate},
{Mod, yyaction}).
scan_annotation(Scanner, _S0, Cord, RText, Start, End) ->
Walker = cord:walker(Cord),
case edit_scan(Scanner, Walker) of
{ok, Toks} ->
{ok, Toks};
{error, Reason} ->
{ok, bad_scan}
end.
test_test(Str) ->
case test_string(Str) of
{ok, Toks} ->
{ok, lists:map(fun(T) -> element(1, T) end,
Toks)};
X ->
X
end.
erlang_test(Str) ->
case erlang_string(Str) of
{ok, Toks} ->
{ok, lists:map(fun(T) -> element(1, T) end,
Toks)};
X ->
X
end.
scheme_test(Str) ->
case scheme_string(Str) of
{ok, Toks} ->
{ok, lists:map(fun(T) -> element(1, T) end,
Toks)};
X ->
X
end.
test_string(Str) ->
Cord = list_to_binary(Str),
Scan = make_test_scanner(),
edit_scan(Scan, cord:walker(Cord)).
scheme_string(Str) ->
Cord = list_to_binary(Str),
Scan = make_scheme_scanner(),
edit_scan(Scan, cord:walker(Cord)).
erlang_string(Str) ->
Cord = list_to_binary(Str),
Scan = make_erlang_scanner(),
edit_scan(Scan, cord:walker(Cord)).
%% Returns: {ok, [#token]} | {error, Reason}
edit_scan(Scn, Walker) ->
edit_scan(Scn, Walker, 1, []).
edit_scan(Scn, Walker, Pos) ->
edit_scan(Scn, Walker, 1, []).
edit_scan(Scn, W0, Pos, Acc) ->
case token(Scn, W0) of
{done, eof} ->
{ok, lists:reverse(Acc)};
{done, Result, W1} ->
Token = make_token(Pos, Result),
edit_scan(Scn, W1, Token#token.finish, [Token|Acc]);
{error, Reason} ->
{error, Reason}
end.
make_skipped_token(Pos, Len, LookAhead) ->
#token{type=em_skipped,
start=Pos,
finish=Pos+Len,
lookahead=LookAhead}.
tokens(Scn , ) - >
tokens(Scn , , [ ] ) .
tokens(Scn , W0 , Acc ) - >
% case token(Scn, W0) of
% {done, {ok, T, Acs}, W1} ->
% tokens(Scn, W1, [T|Acc]);
{ done , , Acs } , W1 } - >
tokens(Scn , W1 , Acc ) ;
% {done, eof} ->
% {ok, lists:reverse(Acc)};
% {error, Reason} ->
% {error, Reason}
% end.
token(Scn, Walker) ->
State0 = Scn#scanner.initial_state,
token(Scn, Walker, State0, [], 0, reject, 0).
token(Scn, W0, S0, Tcs0, Tlen0, A0, Alen0) ->
ActionF = Scn#scanner.action_fn,
DFA_F = Scn#scanner.dfa_fn,
{Ics, Tcs1, W1} = case cord:walker_next(W0) of
{done, WEOF} ->
{eof, Tcs0, WEOF};
{Ch, Wnext} ->
{[Ch], [Ch|Tcs0], Wnext}
end,
case DFA_F(S0, Ics, ?line, Tlen0, A0, Alen0) of
{A1,Alen1,[],L1} -> % accepting end state
TcsFwd = lists:reverse(Tcs1),
token_cont(Scn,TcsFwd,W1,[],ActionF(A1,Alen1,TcsFwd,?line));
{A1,Alen1,[],L1,S1} -> % after accepting state
token(Scn,W1,S1,Tcs1,Alen1,A1,Alen1);
{A1,Alen1,Ics1,L1,S1} -> % accepting state with leftover
% chars.. sounds like a time
% to act.
TcsFwd = lists:reverse(Tcs1),
Acs = yypre(TcsFwd, Alen1),
token_cont(Scn,Acs,W1,Ics1,ActionF(A1,Alen1,TcsFwd,?line));
{A1,Alen1,Tlen1,[],L1,S1} -> % after a non-accepting state
token(Scn,W1,S1,Tcs1,Tlen1,A1,Alen1);
{reject,Alen1,Tlen1,eof,L1,S1} ->
{done,eof};
{reject,Alen1,Tlen1,Ics1,L1,S1} ->
{done,
{error,{illegal,yypre(Tcs1, Tlen1+1)}},
Ics1};
{A1,Alen1,Tlen1,Ics1,L1,S1} ->
TcsFwd = lists:reverse(Tcs1),
{Acs, Rest} = yysplit(TcsFwd, Alen1),
token_cont(Scn,Acs,W1,Rest,ActionF(A1,Alen1,TcsFwd,?line))
end.
token_cont(Scn, Acs, W, Rest, {token, T}) ->
{done, {ok, T, Acs, length_of(Rest)}, pushback(W, Rest)};
token_cont(Scn, Acs, W, Rest, {end_token, T}) ->
{done, {ok, T, Acs, length_of(Rest)}, pushback(W, Rest)};
token_cont(Scn, Acs, W, Rest, SkipToken) ->
{done, {skip_token, Acs, length_of(Rest)}, pushback(W, Rest)};
token_cont(Scn, Acs, W, Rest, {error, S}) ->
{done, {error, {user,S}}, pushback(W, Rest)}.
adjust_pos(C, L, [$\n|T]) -> adjust_pos(0, L+1, T);
adjust_pos(C, L, [_|T]) -> adjust_pos(C+1, L, T);
adjust_pos(C, L, []) -> {C, L}.
length_of(eof) -> 0;
length_of(List) -> length(List).
pushback(W, eof) ->
W;
pushback(W, Chars) ->
lists:foldr(fun(C, Wn) -> cord:walker_push(C, Wn) end,
W,
Chars).
yyrev([H|T], Acc) -> yyrev(T, [H|Acc]);
yyrev([], Acc) -> Acc.
yypre([H|T], N) when N > 0 -> [H|yypre(T, N-1)];
yypre(L, N) -> [].
yysuf([H|T], N) when N > 0 -> yysuf(T, N-1);
yysuf(L, 0) -> L.
yysplit(L, N) -> yysplit(L, N, []).
yysplit([H|T], N, Acc) when N > 0 -> yysplit(T, N-1, [H|Acc]);
yysplit(L, 0, Acc) -> {lists:reverse(Acc), L}.
%%%%%
Experimentation with incremental parsing ( working )
str0() -> "-bar+ +foo-".
toks0() ->
{ok, Toks} = test_string(str0()),
Toks.
%% Hand-hacked version of Toks0 with the space character deleted and
%% its token marked as dirty. When properly re-scanned, this should be
the same as ( basis of the test case )
dirty_toks() -> [OK_A,OK_B,OK_C,Changed0|Following0] = toks0(),
Changed1 = Changed0#token{dirty=true},
Following1 = lists:map(fun(T) ->
Start = T#token.start,
Finish = T#token.finish,
T#token{start=Start-1,
finish=Finish-1}
end,
Following0),
[OK_A,OK_B,OK_C,Changed1|Following1].
%% for: "bar++foo"
%% The space has been changed (now length 0) and is marked dirty.
str1() -> str0() -- " ".
toks1() ->
{ok, Toks} = test_string(str1()),
Toks.
rescan_test() ->
Scn = make_test_scanner(),
Dirty = mark_dirty(dirty_toks()),
Cord = cord:new(str1()),
Result = rescan(Scn, Cord, Dirty),
{Result == toks1(), Result, Dirty}.
%% What should happen with this simple algorithm and test case:
1 . We see that a token is dirty .
2 . We scan backwards for dependencies ( by seeing what has a look - ahead
%% that reaches the dirty token, or another token that does, etc)
3 . From the earliest dependency , we start re - scanning everything
%% until we scan a token which leaves the state of the lexer the same as
%% it was previously (i.e. so the following token is known to be
%% unchanged)
%%
So , how is the state of the lexer defined ? In it seems to me
%% that the internal scanner state is always the same at the start of
%% each token (barring anything magical done in actions - which for
%% now I ignore). So, I think it's safe to assume that a token will be
unchanged if both the chars in its lexeme and the ones reached by
%% its look-ahead are the same. For "tricky stuff" it may be necessary
%% to capture the process dictionary and include (some of) it in the
%% state.
%%
%% So I will terminate when I reach a token beyond the changed text
%% which is starting in the same place.
%%
NB : We should n't need to go * too * far backwards when marking
%% dependencies in languages I can think of, because of common
zero - lookahead tokens like : , ; ( ) ... etc and most other
tokens will just be 1 - lookahead .
re_lex(Toks0) ->
Toks1 = mark_dirty(Toks0).
mark_dirty(Toks) ->
mark_dirty(Toks, []).
mark_dirty([H|T], Acc) when H#token.dirty == true ->
mark_dirty1([H|T], H#token.start, Acc);
mark_dirty([H|T], Acc) ->
mark_dirty(T, [H|Acc]);
mark_dirty([], Acc) ->
lists:reverse(Acc).
mark_dirty1(OK, DirtyPos, Toks0) ->
F = fun(Tok, DP) ->
case (Tok#token.finish-1) + Tok#token.lookahead of
P when P >= DP ->
{Tok#token{dirty=true},
Tok#token.start};
_ ->
{Tok, DP}
end
end,
{Toks1, _} = lists:mapfoldl(F, DirtyPos, Toks0),
lists:reverse(Toks1) ++ OK.
Rescan dirty tokens .
rescan(Scn, Cord, []) ->
[];
rescan(Scn, Cord, [H|T]) when H#token.dirty == false ->
[H|rescan(Scn, Cord, T)];
rescan(Scn, Cord, [H|T]) when H#token.dirty == true ->
Pos = H#token.start,
{_, Region} = cord:split(Cord, Pos-1),
Walker = cord:walker(Region),
rescan_dirty(Scn, Walker, Pos, [H|T]).
%% rescan_dirty(Toks)
%%
The first token is dirty . Scan until we get back to a sane state
rescan_dirty(Scn, W0, Pos, [Tok|Toks]) ->
Start = Tok#token.start,
io:format("(Pos = ~p) Rescanning ~p~n", [Pos, Tok]),
case token(Scn, W0) of
{done, eof} ->
[];
{done, Result, W1} ->
Token = make_token(Pos, Result),
[Token|rescan_dirty_cont(Scn, W1, Token#token.finish, Toks)];
{error, Reason} ->
%% FIXME: should make an error-token and carry on
{error, Reason}
end.
rescan_dirty_cont(Scn, W, Pos, []) ->
[];
rescan_dirty_cont(Scn, W, Pos, Rest) ->
Next = hd(Rest),
if
%% This token no longer exists!
Next#token.finish =< Pos ->
io:format("(Pos = ~p) Discaring token: ~p~n", [Pos, Next]),
rescan_dirty_cont(Scn, W, Pos, tl(Rest));
%% We need to carry on if the token is known to be dirty, or
%% if we aren't at the same place that it was scanned from
%% before
Next#token.dirty == true;
Next#token.start /= Pos ->
rescan_dirty(Scn, W, Pos, Rest);
true ->
Rest
end.
make_token(Pos, {ok, T, Acs, LookAhead}) ->
Type = element(1, T),
Len = length(Acs),
#token{type=Type,
start=Pos,
finish=Pos+Len,
lookahead=LookAhead};
make_token(Pos, {skip_token, Acs, LookAhead}) ->
Len = length(Acs),
#token{type=em_skipped,
start=Pos,
finish=Pos+Len,
lookahead=LookAhead}.
make_error_token(Pos) ->
#token{type=em_error,
start=Pos,
finish=Pos+1,
lookahead=1}.
| null | https://raw.githubusercontent.com/rhaberkorn/ermacs/35c8f9b83ae85e25c646882be6ea6d340a88b05b/mods/src/em_scan.erl | erlang | ----------------------------------------------------------------------
File : em_scan.erl
Purpose : Scanner for leex-style DFAs.
----------------------------------------------------------------------
discarded - all that's taken from the user-written "actions" is the
token type. Instead we just keep the start/finish positions in a
cord.
Not retaining line/column information. Hopefully that's convenient
to derive later.
type chosen by scanner. There is also a special type:
we record it anyway.
start position in cord
finish position in cord (point *after* the last character)
the scanner state machine examined, recorded to track
dependency
for book keeping, saying whether the token is known to
need re-scanning
-export([Function/Arity, ...]).
Bogus line number to pass to leex/yecc, because I don't want to
track lines at this low level. It's not safe to use an atom, but
hopefully -42 looks deliberate enough to prompt a grep :-)
Confusing number appearing where line # should be :-)
Returns: {ok, [#token]} | {error, Reason}
case token(Scn, W0) of
{done, {ok, T, Acs}, W1} ->
tokens(Scn, W1, [T|Acc]);
{done, eof} ->
{ok, lists:reverse(Acc)};
{error, Reason} ->
{error, Reason}
end.
accepting end state
after accepting state
accepting state with leftover
chars.. sounds like a time
to act.
after a non-accepting state
Hand-hacked version of Toks0 with the space character deleted and
its token marked as dirty. When properly re-scanned, this should be
for: "bar++foo"
The space has been changed (now length 0) and is marked dirty.
What should happen with this simple algorithm and test case:
that reaches the dirty token, or another token that does, etc)
until we scan a token which leaves the state of the lexer the same as
it was previously (i.e. so the following token is known to be
unchanged)
that the internal scanner state is always the same at the start of
each token (barring anything magical done in actions - which for
now I ignore). So, I think it's safe to assume that a token will be
its look-ahead are the same. For "tricky stuff" it may be necessary
to capture the process dictionary and include (some of) it in the
state.
So I will terminate when I reach a token beyond the changed text
which is starting in the same place.
dependencies in languages I can think of, because of common
rescan_dirty(Toks)
FIXME: should make an error-token and carry on
This token no longer exists!
We need to carry on if the token is known to be dirty, or
if we aren't at the same place that it was scanned from
before | Author : < >
Created : 1 May 2001 by < >
-module(em_scan).
-author('').
-record(scanner, {initial_state, dfa_fn, action_fn}).
Token record . The actual lexeme , if returned by the scanner , is
-record(token,
{
' em_skipped ' , when the scanner returns ' ' but
type,
start,
finish,
number of characters beyond the end of the lexeme that
lookahead,
dirty=false
}).
-compile(export_all).
make_scanner(State0, DFA, Action) ->
#scanner{initial_state=State0,
dfa_fn=DFA,
action_fn=Action}.
make_scheme_scanner() -> make_leex_scanner(em_scheme_scan).
make_erlang_scanner() -> make_leex_scanner(em_erlang_scan).
make_test_scanner() -> make_leex_scanner(em_test_scan).
make_leex_scanner(Mod) ->
make_scanner(Mod:yystate(),
{Mod, yystate},
{Mod, yyaction}).
scan_annotation(Scanner, _S0, Cord, RText, Start, End) ->
Walker = cord:walker(Cord),
case edit_scan(Scanner, Walker) of
{ok, Toks} ->
{ok, Toks};
{error, Reason} ->
{ok, bad_scan}
end.
test_test(Str) ->
case test_string(Str) of
{ok, Toks} ->
{ok, lists:map(fun(T) -> element(1, T) end,
Toks)};
X ->
X
end.
erlang_test(Str) ->
case erlang_string(Str) of
{ok, Toks} ->
{ok, lists:map(fun(T) -> element(1, T) end,
Toks)};
X ->
X
end.
scheme_test(Str) ->
case scheme_string(Str) of
{ok, Toks} ->
{ok, lists:map(fun(T) -> element(1, T) end,
Toks)};
X ->
X
end.
test_string(Str) ->
Cord = list_to_binary(Str),
Scan = make_test_scanner(),
edit_scan(Scan, cord:walker(Cord)).
scheme_string(Str) ->
Cord = list_to_binary(Str),
Scan = make_scheme_scanner(),
edit_scan(Scan, cord:walker(Cord)).
erlang_string(Str) ->
Cord = list_to_binary(Str),
Scan = make_erlang_scanner(),
edit_scan(Scan, cord:walker(Cord)).
edit_scan(Scn, Walker) ->
edit_scan(Scn, Walker, 1, []).
edit_scan(Scn, Walker, Pos) ->
edit_scan(Scn, Walker, 1, []).
edit_scan(Scn, W0, Pos, Acc) ->
case token(Scn, W0) of
{done, eof} ->
{ok, lists:reverse(Acc)};
{done, Result, W1} ->
Token = make_token(Pos, Result),
edit_scan(Scn, W1, Token#token.finish, [Token|Acc]);
{error, Reason} ->
{error, Reason}
end.
make_skipped_token(Pos, Len, LookAhead) ->
#token{type=em_skipped,
start=Pos,
finish=Pos+Len,
lookahead=LookAhead}.
tokens(Scn , ) - >
tokens(Scn , , [ ] ) .
tokens(Scn , W0 , Acc ) - >
{ done , , Acs } , W1 } - >
tokens(Scn , W1 , Acc ) ;
token(Scn, Walker) ->
State0 = Scn#scanner.initial_state,
token(Scn, Walker, State0, [], 0, reject, 0).
token(Scn, W0, S0, Tcs0, Tlen0, A0, Alen0) ->
ActionF = Scn#scanner.action_fn,
DFA_F = Scn#scanner.dfa_fn,
{Ics, Tcs1, W1} = case cord:walker_next(W0) of
{done, WEOF} ->
{eof, Tcs0, WEOF};
{Ch, Wnext} ->
{[Ch], [Ch|Tcs0], Wnext}
end,
case DFA_F(S0, Ics, ?line, Tlen0, A0, Alen0) of
TcsFwd = lists:reverse(Tcs1),
token_cont(Scn,TcsFwd,W1,[],ActionF(A1,Alen1,TcsFwd,?line));
token(Scn,W1,S1,Tcs1,Alen1,A1,Alen1);
TcsFwd = lists:reverse(Tcs1),
Acs = yypre(TcsFwd, Alen1),
token_cont(Scn,Acs,W1,Ics1,ActionF(A1,Alen1,TcsFwd,?line));
token(Scn,W1,S1,Tcs1,Tlen1,A1,Alen1);
{reject,Alen1,Tlen1,eof,L1,S1} ->
{done,eof};
{reject,Alen1,Tlen1,Ics1,L1,S1} ->
{done,
{error,{illegal,yypre(Tcs1, Tlen1+1)}},
Ics1};
{A1,Alen1,Tlen1,Ics1,L1,S1} ->
TcsFwd = lists:reverse(Tcs1),
{Acs, Rest} = yysplit(TcsFwd, Alen1),
token_cont(Scn,Acs,W1,Rest,ActionF(A1,Alen1,TcsFwd,?line))
end.
token_cont(Scn, Acs, W, Rest, {token, T}) ->
{done, {ok, T, Acs, length_of(Rest)}, pushback(W, Rest)};
token_cont(Scn, Acs, W, Rest, {end_token, T}) ->
{done, {ok, T, Acs, length_of(Rest)}, pushback(W, Rest)};
token_cont(Scn, Acs, W, Rest, SkipToken) ->
{done, {skip_token, Acs, length_of(Rest)}, pushback(W, Rest)};
token_cont(Scn, Acs, W, Rest, {error, S}) ->
{done, {error, {user,S}}, pushback(W, Rest)}.
adjust_pos(C, L, [$\n|T]) -> adjust_pos(0, L+1, T);
adjust_pos(C, L, [_|T]) -> adjust_pos(C+1, L, T);
adjust_pos(C, L, []) -> {C, L}.
length_of(eof) -> 0;
length_of(List) -> length(List).
pushback(W, eof) ->
W;
pushback(W, Chars) ->
lists:foldr(fun(C, Wn) -> cord:walker_push(C, Wn) end,
W,
Chars).
yyrev([H|T], Acc) -> yyrev(T, [H|Acc]);
yyrev([], Acc) -> Acc.
yypre([H|T], N) when N > 0 -> [H|yypre(T, N-1)];
yypre(L, N) -> [].
yysuf([H|T], N) when N > 0 -> yysuf(T, N-1);
yysuf(L, 0) -> L.
yysplit(L, N) -> yysplit(L, N, []).
yysplit([H|T], N, Acc) when N > 0 -> yysplit(T, N-1, [H|Acc]);
yysplit(L, 0, Acc) -> {lists:reverse(Acc), L}.
Experimentation with incremental parsing ( working )
str0() -> "-bar+ +foo-".
toks0() ->
{ok, Toks} = test_string(str0()),
Toks.
the same as ( basis of the test case )
dirty_toks() -> [OK_A,OK_B,OK_C,Changed0|Following0] = toks0(),
Changed1 = Changed0#token{dirty=true},
Following1 = lists:map(fun(T) ->
Start = T#token.start,
Finish = T#token.finish,
T#token{start=Start-1,
finish=Finish-1}
end,
Following0),
[OK_A,OK_B,OK_C,Changed1|Following1].
str1() -> str0() -- " ".
toks1() ->
{ok, Toks} = test_string(str1()),
Toks.
rescan_test() ->
Scn = make_test_scanner(),
Dirty = mark_dirty(dirty_toks()),
Cord = cord:new(str1()),
Result = rescan(Scn, Cord, Dirty),
{Result == toks1(), Result, Dirty}.
1 . We see that a token is dirty .
2 . We scan backwards for dependencies ( by seeing what has a look - ahead
3 . From the earliest dependency , we start re - scanning everything
So , how is the state of the lexer defined ? In it seems to me
unchanged if both the chars in its lexeme and the ones reached by
NB : We should n't need to go * too * far backwards when marking
zero - lookahead tokens like : , ; ( ) ... etc and most other
tokens will just be 1 - lookahead .
re_lex(Toks0) ->
Toks1 = mark_dirty(Toks0).
mark_dirty(Toks) ->
mark_dirty(Toks, []).
mark_dirty([H|T], Acc) when H#token.dirty == true ->
mark_dirty1([H|T], H#token.start, Acc);
mark_dirty([H|T], Acc) ->
mark_dirty(T, [H|Acc]);
mark_dirty([], Acc) ->
lists:reverse(Acc).
mark_dirty1(OK, DirtyPos, Toks0) ->
F = fun(Tok, DP) ->
case (Tok#token.finish-1) + Tok#token.lookahead of
P when P >= DP ->
{Tok#token{dirty=true},
Tok#token.start};
_ ->
{Tok, DP}
end
end,
{Toks1, _} = lists:mapfoldl(F, DirtyPos, Toks0),
lists:reverse(Toks1) ++ OK.
Rescan dirty tokens .
rescan(Scn, Cord, []) ->
[];
rescan(Scn, Cord, [H|T]) when H#token.dirty == false ->
[H|rescan(Scn, Cord, T)];
rescan(Scn, Cord, [H|T]) when H#token.dirty == true ->
Pos = H#token.start,
{_, Region} = cord:split(Cord, Pos-1),
Walker = cord:walker(Region),
rescan_dirty(Scn, Walker, Pos, [H|T]).
The first token is dirty . Scan until we get back to a sane state
rescan_dirty(Scn, W0, Pos, [Tok|Toks]) ->
Start = Tok#token.start,
io:format("(Pos = ~p) Rescanning ~p~n", [Pos, Tok]),
case token(Scn, W0) of
{done, eof} ->
[];
{done, Result, W1} ->
Token = make_token(Pos, Result),
[Token|rescan_dirty_cont(Scn, W1, Token#token.finish, Toks)];
{error, Reason} ->
{error, Reason}
end.
rescan_dirty_cont(Scn, W, Pos, []) ->
[];
rescan_dirty_cont(Scn, W, Pos, Rest) ->
Next = hd(Rest),
if
Next#token.finish =< Pos ->
io:format("(Pos = ~p) Discaring token: ~p~n", [Pos, Next]),
rescan_dirty_cont(Scn, W, Pos, tl(Rest));
Next#token.dirty == true;
Next#token.start /= Pos ->
rescan_dirty(Scn, W, Pos, Rest);
true ->
Rest
end.
make_token(Pos, {ok, T, Acs, LookAhead}) ->
Type = element(1, T),
Len = length(Acs),
#token{type=Type,
start=Pos,
finish=Pos+Len,
lookahead=LookAhead};
make_token(Pos, {skip_token, Acs, LookAhead}) ->
Len = length(Acs),
#token{type=em_skipped,
start=Pos,
finish=Pos+Len,
lookahead=LookAhead}.
make_error_token(Pos) ->
#token{type=em_error,
start=Pos,
finish=Pos+1,
lookahead=1}.
|
180b55e76098d88fa8fecc1df9b98f98b92f6c447caf319e44729cbe5e8a9d0b | HunterYIboHu/htdp2-solution | ex357-eval-definition1.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-intermediate-lambda-reader.ss" "lang")((modname ex357-eval-definition1) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
An AL ( short for association list ) is [ List - of Association ] .
An Association is a list of two items :
; (cons Symbol (cons Number '())).
(define-struct add [left right])
; An Add is a structure:
( make - add BSL - func - expr BSL - func - expr )
(define-struct mul [left right])
; An Mul is a structure:
( make - mul BSL - func - expr BSL - func - expr )
(define-struct func [name args body])
; An Func is a structure:
; (make-func Symbol [List-of Symbol] BSL-func-expr)
BSL - expr is one of :
; - Number
; - Add
; - Mul
BSL - var - expr is one of :
; - Number
; - Symbol
; - Add
; - Mul
BSL - func - expr is one of :
; - Number
; - Symbol
; - Add
; - Mul
; - Func
;; constants
(define WRONG "Invalid function apply!")
(define expr-1 `(k ,(make-add 1 1)))
(define expr-2 (make-mul 5 `(k ,(make-add 1 1))))
(define expr-3 (make-mul '(i 5)
`(k ,(make-add 1 1))))
(define expr-6 (make-add 'x 3))
(define expr-7 (make-mul 1/2 (make-mul 'x 3)))
(define expr-8 (make-add (make-mul 'x 'x)
(make-mul 'y 'y)))
;; functions
BSL - func - expr Symbol Symbol BSL - func - expr - > Number
; produces the value of given expr, the f represents the function's name;
; x represents the function's parameter, b represents the function's body.
it signal errors when the two case happended one :
; - encounters variable
; - function application does not refer to f.
(check-expect (eval-definition1 expr-1 'k 'a (make-mul 'a 2)) 4)
(check-expect (eval-definition1 expr-2 'k 'a (make-mul 'a 2)) 20)
(check-error (eval-definition1 expr-1 'i 'a (make-mul 'a 2)) WRONG)
(check-error (eval-definition1 expr-6 'i 'a (make-mul 'a 2)) WRONG)
(define (eval-definition1 ex f x b)
BSL - func - expr - > Number
; using arguments of outside function to simpfy the application.
(define (apply-func expr)
(eval-definition1 expr f x b))
[ Number Number - > Number ] BSL - func - expr BSL - func - expr - > Number
iter the given two pieces of data .
(define (iter f left right)
(f (apply-func left) (apply-func right))))
(cond [(cons? ex)
(if (symbol=? (first ex) f)
(apply-func (subst b x (second ex)))
(error WRONG))]
[(symbol? ex) (error WRONG)]
[(number? ex) ex]
[(add? ex) (iter + (add-left ex) (add-right ex))]
[(mul? ex) (iter * (mul-left ex) (mul-right ex))])))
;; auxiliary functions
; BSL-var-expr Symbol Number -> BSL-var-expr
; produces an expression with all occurrences of x in ex replaced by v.
(check-expect (subst expr-6 'x 10) (make-add 10 3))
(check-expect (subst expr-7 'x 5) (make-mul 1/2 (make-mul 5 3)))
(check-expect (subst expr-8 'y 5) (make-add (make-mul 'x 'x)
(make-mul 5 5)))
(define (subst ex x v)
(cond [(symbol? ex)
(if (symbol=? ex x) v ex)]
[(number? ex) ex]
[(add? ex) (make-add (subst (add-left ex) x v)
(subst (add-right ex) x v))]
[(mul? ex) (make-mul (subst (mul-left ex) x v)
(subst (mul-right ex) x v))]))
| null | https://raw.githubusercontent.com/HunterYIboHu/htdp2-solution/6182b4c2ef650ac7059f3c143f639d09cd708516/Chapter4/Section21-Refining-Interpreters/ex357-eval-definition1.rkt | racket | about the language level of this file in a form that our tools can easily process.
(cons Symbol (cons Number '())).
An Add is a structure:
An Mul is a structure:
An Func is a structure:
(make-func Symbol [List-of Symbol] BSL-func-expr)
- Number
- Add
- Mul
- Number
- Symbol
- Add
- Mul
- Number
- Symbol
- Add
- Mul
- Func
constants
functions
produces the value of given expr, the f represents the function's name;
x represents the function's parameter, b represents the function's body.
- encounters variable
- function application does not refer to f.
using arguments of outside function to simpfy the application.
auxiliary functions
BSL-var-expr Symbol Number -> BSL-var-expr
produces an expression with all occurrences of x in ex replaced by v. | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex357-eval-definition1) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
An AL ( short for association list ) is [ List - of Association ] .
An Association is a list of two items :
(define-struct add [left right])
( make - add BSL - func - expr BSL - func - expr )
(define-struct mul [left right])
( make - mul BSL - func - expr BSL - func - expr )
(define-struct func [name args body])
BSL - expr is one of :
BSL - var - expr is one of :
BSL - func - expr is one of :
(define WRONG "Invalid function apply!")
(define expr-1 `(k ,(make-add 1 1)))
(define expr-2 (make-mul 5 `(k ,(make-add 1 1))))
(define expr-3 (make-mul '(i 5)
`(k ,(make-add 1 1))))
(define expr-6 (make-add 'x 3))
(define expr-7 (make-mul 1/2 (make-mul 'x 3)))
(define expr-8 (make-add (make-mul 'x 'x)
(make-mul 'y 'y)))
BSL - func - expr Symbol Symbol BSL - func - expr - > Number
it signal errors when the two case happended one :
(check-expect (eval-definition1 expr-1 'k 'a (make-mul 'a 2)) 4)
(check-expect (eval-definition1 expr-2 'k 'a (make-mul 'a 2)) 20)
(check-error (eval-definition1 expr-1 'i 'a (make-mul 'a 2)) WRONG)
(check-error (eval-definition1 expr-6 'i 'a (make-mul 'a 2)) WRONG)
(define (eval-definition1 ex f x b)
BSL - func - expr - > Number
(define (apply-func expr)
(eval-definition1 expr f x b))
[ Number Number - > Number ] BSL - func - expr BSL - func - expr - > Number
iter the given two pieces of data .
(define (iter f left right)
(f (apply-func left) (apply-func right))))
(cond [(cons? ex)
(if (symbol=? (first ex) f)
(apply-func (subst b x (second ex)))
(error WRONG))]
[(symbol? ex) (error WRONG)]
[(number? ex) ex]
[(add? ex) (iter + (add-left ex) (add-right ex))]
[(mul? ex) (iter * (mul-left ex) (mul-right ex))])))
(check-expect (subst expr-6 'x 10) (make-add 10 3))
(check-expect (subst expr-7 'x 5) (make-mul 1/2 (make-mul 5 3)))
(check-expect (subst expr-8 'y 5) (make-add (make-mul 'x 'x)
(make-mul 5 5)))
(define (subst ex x v)
(cond [(symbol? ex)
(if (symbol=? ex x) v ex)]
[(number? ex) ex]
[(add? ex) (make-add (subst (add-left ex) x v)
(subst (add-right ex) x v))]
[(mul? ex) (make-mul (subst (mul-left ex) x v)
(subst (mul-right ex) x v))]))
|
deebed1911a0d57137a650b58381905bb0db1c6101f71511e5d774d724cc734c | igarnier/vplot | utils.ml | open Numerics.Float64
type float_ref = { mutable x : float }
let min (f : float) (f' : float) = if f < f' then f else f'
let max (f : float) (f' : float) = if f < f' then f' else f
let vector_range (data : Vec.t) =
let len = Vec.length data in
let minv = { x = max_float } in
let maxv = { x = -.max_float } in
for i = 0 to len - 1 do
let v = Vec.get data i in
minv.x <- min minv.x v ;
maxv.x <- max maxv.x v
done ;
(minv.x, maxv.x)
let data_range (data : Mat.t) =
let xdata = Mat.dim1 data in
let ydata = Mat.dim2 data in
let minv = { x = max_float } in
let maxv = { x = -.max_float } in
for i = 0 to xdata - 1 do
for j = 0 to ydata - 1 do
let v = Mat.get data i j in
minv.x <- min minv.x v ;
maxv.x <- max maxv.x v
done
done ;
(minv.x, maxv.x)
let interpolate a b n =
if n < 2 then invalid_arg "interpolate: not enough interpolation steps" ;
let d = (b -. a) /. float (n - 1) in
let rec loop x i = if i = n - 1 then [b] else x :: loop (x +. d) (i + 1) in
loop a 0
let linspace start finish steps =
if steps <= 0 then invalid_arg "linspace: steps <= 0" ;
if steps = 1 then [| start |]
else
let delta = (finish -. start) /. float (steps - 1) in
Array.init steps (fun i -> start +. (float i *. delta))
let rec _all_elements_equal x tl =
match tl with [] -> true | y :: tl -> y = x && _all_elements_equal x tl
let all_elements_equal l =
match l with [] | [_] -> true | x :: tl -> _all_elements_equal x tl
let ( ++ ) f g x = g (f x)
| null | https://raw.githubusercontent.com/igarnier/vplot/146467257f110f71d48415fc3ddaf0f46a71035a/lib/utils.ml | ocaml | open Numerics.Float64
type float_ref = { mutable x : float }
let min (f : float) (f' : float) = if f < f' then f else f'
let max (f : float) (f' : float) = if f < f' then f' else f
let vector_range (data : Vec.t) =
let len = Vec.length data in
let minv = { x = max_float } in
let maxv = { x = -.max_float } in
for i = 0 to len - 1 do
let v = Vec.get data i in
minv.x <- min minv.x v ;
maxv.x <- max maxv.x v
done ;
(minv.x, maxv.x)
let data_range (data : Mat.t) =
let xdata = Mat.dim1 data in
let ydata = Mat.dim2 data in
let minv = { x = max_float } in
let maxv = { x = -.max_float } in
for i = 0 to xdata - 1 do
for j = 0 to ydata - 1 do
let v = Mat.get data i j in
minv.x <- min minv.x v ;
maxv.x <- max maxv.x v
done
done ;
(minv.x, maxv.x)
let interpolate a b n =
if n < 2 then invalid_arg "interpolate: not enough interpolation steps" ;
let d = (b -. a) /. float (n - 1) in
let rec loop x i = if i = n - 1 then [b] else x :: loop (x +. d) (i + 1) in
loop a 0
let linspace start finish steps =
if steps <= 0 then invalid_arg "linspace: steps <= 0" ;
if steps = 1 then [| start |]
else
let delta = (finish -. start) /. float (steps - 1) in
Array.init steps (fun i -> start +. (float i *. delta))
let rec _all_elements_equal x tl =
match tl with [] -> true | y :: tl -> y = x && _all_elements_equal x tl
let all_elements_equal l =
match l with [] | [_] -> true | x :: tl -> _all_elements_equal x tl
let ( ++ ) f g x = g (f x)
| |
1fde5a4ffb31b01fb43f707e968e0037d15bf9c28985c4e6df96298d5c0d08a6 | clojure/core.typed | fn.clj | Copyright ( c ) , contributors .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns ^:skip-wiki clojure.core.typed.checker.check.special.fn
(:require [clojure.core.typed :as t]
[clojure.core.typed.checker.jvm.parse-unparse :as prs]
[clojure.core.typed.checker.filter-ops :as fo]
[clojure.core.typed.checker.object-rep :as or]
[clojure.core.typed.checker.filter-rep :as fl]
[clojure.core.typed.checker.free-ops :as free-ops]
[clojure.core.typed.checker.check.fn :as fn]
[clojure.core.typed.checker.dvar-env :as dvar]
[clojure.core.typed.checker.type-ctors :as c]
[clojure.core.typed.checker.lex-env :as lex]
[clojure.core.typed.checker.check.utils :as cu]
[clojure.core.typed.checker.type-rep :as r]
[clojure.core.typed.checker.utils :as u]
[clojure.core.typed.ast-utils :as ast-u]
[clojure.core.typed.checker.check.fn-method-one :as fn-method-one]
[clojure.core.typed.checker.check.fn-methods :as fn-methods]
[clojure.core.typed.checker.check-below :as below]
[clojure.core.typed.analyzer.common :as ana2]))
(declare wrap-poly)
(defn check-anon [{:keys [methods] :as expr} {:keys [doms rngs rests drests]}
{:keys [frees-with-bnds dvar]}]
{:pre [(#{:fn} (:op expr))]}
(assert (apply = (map count [doms rngs rests drests rngs methods]))
(mapv count [doms rngs rests drests rngs methods]))
;(prn "check-anon")
;(prn "doms" doms)
(let [; only ever at most one rest type. Enforced by the t/fn macro.
_ (assert (#{0 1} (count (remove nil? (concat rests drests)))))
; fixed entries are indexed by their domain count,
; :rest entry has variable arity.
fixed-expecteds (into {}
(map (fn [dom rng rest drest]
[(if (or rest drest)
:rest
(count dom))
{:dom dom
:rng rng
:rest rest
:drest drest}])
doms
rngs
rests
drests))
cmethod-specs
(mapv
(fn [method]
(let [{:keys [dom rng rest drest]
:as expecteds}
(get fixed-expecteds (if (ast-u/method-rest-param method)
:rest
(count (ast-u/method-required-params method))))
_ (assert expecteds)]
;(prn "dom" (count dom))
;(prn "method args" (-> method ast-u/method-required-params count))
(fn-method-one/check-fn-method1
method
(r/make-Function dom (or (when (r/Result? rng)
(r/Result-type* rng))
r/-any)
:rest rest
:drest drest
:filter (when (r/Result? rng)
(r/Result-filter* rng))
:object (when (r/Result? rng)
(r/Result-object* rng))
:flow (when (r/Result? rng)
(r/Result-flow* rng)))
:ignore-rng (not rng))))
methods)
[fs cmethods] ((juxt #(map :ftype %)
#(mapv :cmethod %))
cmethod-specs)
_ (assert (seq fs) fs)
_ (assert (every? r/Function? fs) fs)
ret-type (r/ret (wrap-poly (apply r/make-FnIntersection fs) frees-with-bnds dvar)
(fo/-FS fl/-top fl/-bot))]
(assoc expr
:methods cmethods
::t/cmethods cmethods
u/expr-type ret-type)))
(defn gen-defaults [{:keys [methods] :as expr}]
(let [;; :infer-locals are enabled for this namespace, this
;; var dereference is the dynamic type
infer-locals?
(-> (cu/expr-ns expr)
find-ns
meta
:core.typed
:experimental
(contains? :infer-locals))]
(apply merge-with (comp vec concat)
(for [method methods]
(let [fixed-arity (ast-u/fixed-arity method)
variadic? (ast-u/variadic-method? method)]
{:doms [(vec (repeat fixed-arity (if infer-locals?
(r/-unchecked nil)
r/-any)))]
:rngs [nil]
:rests [(when variadic?
(if infer-locals?
(r/-unchecked nil)
r/-any))]
:drests [nil]})))))
(defn all-defaults? [fn-anns poly]
(let [defaults (and
(every? (fn [{:keys [dom]}]
(every? :default dom))
fn-anns)
(every? (comp :default :rng) fn-anns)
(every? (fn [{:keys [rest]}]
(or (:default rest)
(nil? rest)))
fn-anns)
(every? (comp not :drest) fn-anns))]
(and (not poly)
defaults)))
(defn prepare-expecteds [expr fn-anns]
(binding [prs/*parse-type-in-ns* (cu/expr-ns expr)]
{:doms
(->> fn-anns
(map :dom)
(mapv (fn [dom]
(mapv (fn [{:keys [type default]}]
(prs/parse-type type))
dom))))
:rngs (->> fn-anns
(map :rng)
(mapv (fn [{:keys [type default]}]
(when-not default
(r/make-Result (prs/parse-type type)
(fo/-FS fl/-infer-top
fl/-infer-top)
or/-no-object
(r/-flow fl/-infer-top))))))
:rests (->> fn-anns
(map :rest)
(mapv (fn [{:keys [type default] :as has-rest}]
(when has-rest
(prs/parse-type type)))))
:drests (->> fn-anns
(map :drest)
(mapv (fn [{:keys [pretype bound] :as has-drest}]
(when has-drest
(r/DottedPretype1-maker
(prs/parse-type pretype)
bound)))))}))
(defn self-type [{:keys [doms rngs rests drests] :as expecteds}]
(apply r/make-FnIntersection
(map (fn [dom rng rest drest]
{:pre [((some-fn nil? r/Result?) rng)
((some-fn nil? r/Type?) rest)
((some-fn nil? r/DottedPretype?) drest)
(every? r/Type? dom)]
:post [(r/Function? %)]}
(r/make-Function dom (or (when rng (r/Result-type* rng)) r/-any)
:rest rest :drest drest))
doms rngs rests drests)))
(defn parse-poly [bnds]
{:pre [((some-fn nil? vector?) bnds)]}
(prs/parse-unknown-binder bnds))
(defn wrap-poly [ifn frees-with-bnds dvar]
(if (and (empty? frees-with-bnds)
(not dvar))
ifn
(if dvar
(c/PolyDots* (map first (concat frees-with-bnds [dvar]))
(map second (concat frees-with-bnds [dvar]))
ifn)
(c/Poly* (map first frees-with-bnds)
(map second frees-with-bnds)
ifn))))
(defn check-core-fn-no-expected
[check fexpr]
{:pre [(#{:fn} (:op fexpr))]
:post [(#{:fn} (:op %))
(r/TCResult? (u/expr-type %))]}
;(prn "check-core-fn-no-expected")
(let [self-name (cu/fn-self-name fexpr)
_ (assert ((some-fn nil? symbol?) self-name))
flat-expecteds (gen-defaults fexpr)]
(lex/with-locals (when self-name
(let [this-type (self-type flat-expecteds)
;_ (prn "this-type" this-type)
]
{self-name this-type}))
(check-anon
fexpr
flat-expecteds
nil))))
(defn check-special-fn
[check {statements :statements fexpr :ret :as expr} expected]
{:pre [((some-fn nil? r/TCResult?) expected)
(#{3} (count statements))]}
;(prn "check-special-fn")
(binding [prs/*parse-type-in-ns* (cu/expr-ns expr)]
(let [fexpr (-> fexpr
ana2/analyze-outer-root
ana2/run-pre-passes)
statements (update statements 2 ana2/run-passes)
[_ _ fn-ann-expr :as statements] statements
_ (assert (#{:fn} (:op fexpr))
((juxt :op :form) fexpr))
fn-anns-quoted (ast-u/map-expr-at fn-ann-expr :ann)
;_ (prn "fn-anns-quoted" fn-anns-quoted)
poly-quoted (ast-u/map-expr-at fn-ann-expr :poly)
;; always quoted
fn-anns (second fn-anns-quoted)
;; always quoted
poly (second poly-quoted)
_ (assert (vector? fn-anns) (pr-str fn-anns))
self-name (cu/fn-self-name fexpr)
_ (assert ((some-fn nil? symbol?) self-name)
self-name)
;_ (prn "self-name" self-name)
[frees-with-bnds dvar] (parse-poly poly)
new-bnded-frees (into {} (map (fn [[n bnd]] [(r/make-F n) bnd]) frees-with-bnds))
new-dotted (when dvar [(r/make-F (first dvar))])
flat-expecteds
(free-ops/with-bounded-frees new-bnded-frees
(dvar/with-dotted new-dotted
(prepare-expecteds expr fn-anns)))
;_ (prn "flat-expecteds" flat-expecteds)
_ (assert ((some-fn nil? vector?) poly))
good-expected? (fn [expected]
{:pre [((some-fn nil? r/TCResult?) expected)]
:post [(boolean? %)]}
(boolean
(when expected
(seq (fn-methods/function-types (r/ret-t expected))))))
;; If we have an unannotated fn macro and a good expected type, use the expected
;; type via check-fn, otherwise check against the expected type after a call to check-anon.
cfexpr
(if (and (all-defaults? fn-anns poly)
(good-expected? expected))
(do ;(prn "using check-fn")
(fn/check-fn fexpr expected))
(let [;_ (prn "using anon-fn")
cfexpr (lex/with-locals (when self-name
(let [this-type (self-type flat-expecteds)
;_ (prn "this-type" this-type)
]
{self-name this-type}))
(free-ops/with-bounded-frees new-bnded-frees
(dvar/with-dotted new-dotted
(check-anon
fexpr
flat-expecteds
{:frees-with-bnds frees-with-bnds
:dvar dvar}))))]
(update cfexpr u/expr-type below/maybe-check-below expected)))]
(assoc expr
:statements statements
:ret cfexpr
u/expr-type (u/expr-type cfexpr)))))
| null | https://raw.githubusercontent.com/clojure/core.typed/f5b7d00bbb29d09000d7fef7cca5b40416c9fa91/typed/checker.jvm/src/clojure/core/typed/checker/check/special/fn.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
(prn "check-anon")
(prn "doms" doms)
only ever at most one rest type. Enforced by the t/fn macro.
fixed entries are indexed by their domain count,
:rest entry has variable arity.
(prn "dom" (count dom))
(prn "method args" (-> method ast-u/method-required-params count))
:infer-locals are enabled for this namespace, this
var dereference is the dynamic type
(prn "check-core-fn-no-expected")
_ (prn "this-type" this-type)
(prn "check-special-fn")
_ (prn "fn-anns-quoted" fn-anns-quoted)
always quoted
always quoted
_ (prn "self-name" self-name)
_ (prn "flat-expecteds" flat-expecteds)
If we have an unannotated fn macro and a good expected type, use the expected
type via check-fn, otherwise check against the expected type after a call to check-anon.
(prn "using check-fn")
_ (prn "using anon-fn")
_ (prn "this-type" this-type) | Copyright ( c ) , contributors .
(ns ^:skip-wiki clojure.core.typed.checker.check.special.fn
(:require [clojure.core.typed :as t]
[clojure.core.typed.checker.jvm.parse-unparse :as prs]
[clojure.core.typed.checker.filter-ops :as fo]
[clojure.core.typed.checker.object-rep :as or]
[clojure.core.typed.checker.filter-rep :as fl]
[clojure.core.typed.checker.free-ops :as free-ops]
[clojure.core.typed.checker.check.fn :as fn]
[clojure.core.typed.checker.dvar-env :as dvar]
[clojure.core.typed.checker.type-ctors :as c]
[clojure.core.typed.checker.lex-env :as lex]
[clojure.core.typed.checker.check.utils :as cu]
[clojure.core.typed.checker.type-rep :as r]
[clojure.core.typed.checker.utils :as u]
[clojure.core.typed.ast-utils :as ast-u]
[clojure.core.typed.checker.check.fn-method-one :as fn-method-one]
[clojure.core.typed.checker.check.fn-methods :as fn-methods]
[clojure.core.typed.checker.check-below :as below]
[clojure.core.typed.analyzer.common :as ana2]))
(declare wrap-poly)
(defn check-anon [{:keys [methods] :as expr} {:keys [doms rngs rests drests]}
{:keys [frees-with-bnds dvar]}]
{:pre [(#{:fn} (:op expr))]}
(assert (apply = (map count [doms rngs rests drests rngs methods]))
(mapv count [doms rngs rests drests rngs methods]))
_ (assert (#{0 1} (count (remove nil? (concat rests drests)))))
fixed-expecteds (into {}
(map (fn [dom rng rest drest]
[(if (or rest drest)
:rest
(count dom))
{:dom dom
:rng rng
:rest rest
:drest drest}])
doms
rngs
rests
drests))
cmethod-specs
(mapv
(fn [method]
(let [{:keys [dom rng rest drest]
:as expecteds}
(get fixed-expecteds (if (ast-u/method-rest-param method)
:rest
(count (ast-u/method-required-params method))))
_ (assert expecteds)]
(fn-method-one/check-fn-method1
method
(r/make-Function dom (or (when (r/Result? rng)
(r/Result-type* rng))
r/-any)
:rest rest
:drest drest
:filter (when (r/Result? rng)
(r/Result-filter* rng))
:object (when (r/Result? rng)
(r/Result-object* rng))
:flow (when (r/Result? rng)
(r/Result-flow* rng)))
:ignore-rng (not rng))))
methods)
[fs cmethods] ((juxt #(map :ftype %)
#(mapv :cmethod %))
cmethod-specs)
_ (assert (seq fs) fs)
_ (assert (every? r/Function? fs) fs)
ret-type (r/ret (wrap-poly (apply r/make-FnIntersection fs) frees-with-bnds dvar)
(fo/-FS fl/-top fl/-bot))]
(assoc expr
:methods cmethods
::t/cmethods cmethods
u/expr-type ret-type)))
(defn gen-defaults [{:keys [methods] :as expr}]
infer-locals?
(-> (cu/expr-ns expr)
find-ns
meta
:core.typed
:experimental
(contains? :infer-locals))]
(apply merge-with (comp vec concat)
(for [method methods]
(let [fixed-arity (ast-u/fixed-arity method)
variadic? (ast-u/variadic-method? method)]
{:doms [(vec (repeat fixed-arity (if infer-locals?
(r/-unchecked nil)
r/-any)))]
:rngs [nil]
:rests [(when variadic?
(if infer-locals?
(r/-unchecked nil)
r/-any))]
:drests [nil]})))))
(defn all-defaults? [fn-anns poly]
(let [defaults (and
(every? (fn [{:keys [dom]}]
(every? :default dom))
fn-anns)
(every? (comp :default :rng) fn-anns)
(every? (fn [{:keys [rest]}]
(or (:default rest)
(nil? rest)))
fn-anns)
(every? (comp not :drest) fn-anns))]
(and (not poly)
defaults)))
(defn prepare-expecteds [expr fn-anns]
(binding [prs/*parse-type-in-ns* (cu/expr-ns expr)]
{:doms
(->> fn-anns
(map :dom)
(mapv (fn [dom]
(mapv (fn [{:keys [type default]}]
(prs/parse-type type))
dom))))
:rngs (->> fn-anns
(map :rng)
(mapv (fn [{:keys [type default]}]
(when-not default
(r/make-Result (prs/parse-type type)
(fo/-FS fl/-infer-top
fl/-infer-top)
or/-no-object
(r/-flow fl/-infer-top))))))
:rests (->> fn-anns
(map :rest)
(mapv (fn [{:keys [type default] :as has-rest}]
(when has-rest
(prs/parse-type type)))))
:drests (->> fn-anns
(map :drest)
(mapv (fn [{:keys [pretype bound] :as has-drest}]
(when has-drest
(r/DottedPretype1-maker
(prs/parse-type pretype)
bound)))))}))
(defn self-type [{:keys [doms rngs rests drests] :as expecteds}]
(apply r/make-FnIntersection
(map (fn [dom rng rest drest]
{:pre [((some-fn nil? r/Result?) rng)
((some-fn nil? r/Type?) rest)
((some-fn nil? r/DottedPretype?) drest)
(every? r/Type? dom)]
:post [(r/Function? %)]}
(r/make-Function dom (or (when rng (r/Result-type* rng)) r/-any)
:rest rest :drest drest))
doms rngs rests drests)))
(defn parse-poly [bnds]
{:pre [((some-fn nil? vector?) bnds)]}
(prs/parse-unknown-binder bnds))
(defn wrap-poly [ifn frees-with-bnds dvar]
(if (and (empty? frees-with-bnds)
(not dvar))
ifn
(if dvar
(c/PolyDots* (map first (concat frees-with-bnds [dvar]))
(map second (concat frees-with-bnds [dvar]))
ifn)
(c/Poly* (map first frees-with-bnds)
(map second frees-with-bnds)
ifn))))
(defn check-core-fn-no-expected
[check fexpr]
{:pre [(#{:fn} (:op fexpr))]
:post [(#{:fn} (:op %))
(r/TCResult? (u/expr-type %))]}
(let [self-name (cu/fn-self-name fexpr)
_ (assert ((some-fn nil? symbol?) self-name))
flat-expecteds (gen-defaults fexpr)]
(lex/with-locals (when self-name
(let [this-type (self-type flat-expecteds)
]
{self-name this-type}))
(check-anon
fexpr
flat-expecteds
nil))))
(defn check-special-fn
[check {statements :statements fexpr :ret :as expr} expected]
{:pre [((some-fn nil? r/TCResult?) expected)
(#{3} (count statements))]}
(binding [prs/*parse-type-in-ns* (cu/expr-ns expr)]
(let [fexpr (-> fexpr
ana2/analyze-outer-root
ana2/run-pre-passes)
statements (update statements 2 ana2/run-passes)
[_ _ fn-ann-expr :as statements] statements
_ (assert (#{:fn} (:op fexpr))
((juxt :op :form) fexpr))
fn-anns-quoted (ast-u/map-expr-at fn-ann-expr :ann)
poly-quoted (ast-u/map-expr-at fn-ann-expr :poly)
fn-anns (second fn-anns-quoted)
poly (second poly-quoted)
_ (assert (vector? fn-anns) (pr-str fn-anns))
self-name (cu/fn-self-name fexpr)
_ (assert ((some-fn nil? symbol?) self-name)
self-name)
[frees-with-bnds dvar] (parse-poly poly)
new-bnded-frees (into {} (map (fn [[n bnd]] [(r/make-F n) bnd]) frees-with-bnds))
new-dotted (when dvar [(r/make-F (first dvar))])
flat-expecteds
(free-ops/with-bounded-frees new-bnded-frees
(dvar/with-dotted new-dotted
(prepare-expecteds expr fn-anns)))
_ (assert ((some-fn nil? vector?) poly))
good-expected? (fn [expected]
{:pre [((some-fn nil? r/TCResult?) expected)]
:post [(boolean? %)]}
(boolean
(when expected
(seq (fn-methods/function-types (r/ret-t expected))))))
cfexpr
(if (and (all-defaults? fn-anns poly)
(good-expected? expected))
(fn/check-fn fexpr expected))
cfexpr (lex/with-locals (when self-name
(let [this-type (self-type flat-expecteds)
]
{self-name this-type}))
(free-ops/with-bounded-frees new-bnded-frees
(dvar/with-dotted new-dotted
(check-anon
fexpr
flat-expecteds
{:frees-with-bnds frees-with-bnds
:dvar dvar}))))]
(update cfexpr u/expr-type below/maybe-check-below expected)))]
(assoc expr
:statements statements
:ret cfexpr
u/expr-type (u/expr-type cfexpr)))))
|
23b2196f01317c405577837fd70fe2c92c06f70379e7d7fbd621d3dd2f2903e6 | VisionsGlobalEmpowerment/webchange | events.cljs | (ns webchange.events
(:require
[re-frame.core :as re-frame]
[webchange.db :as db]
[day8.re-frame.tracing :refer-macros [fn-traced defn-traced]]
[day8.re-frame.http-fx]
[ajax.core :refer [json-request-format json-response-format]]
[webchange.error-message.state :as error-message]))
(re-frame/reg-event-db
::initialize-db
(fn-traced [_ _]
db/default-db))
(re-frame/reg-event-db
::change-viewport
(fn [db [_ value]]
(assoc db :viewport value)))
(re-frame/reg-event-db
::set-loading-progress
(fn [db [_ scene-id value]]
(assoc-in db [:scene-loading-progress scene-id] value)))
(re-frame/reg-event-db
::set-scene-loaded
(fn [db [_ scene-id value]]
(assoc-in db [:scene-loading-complete scene-id] value)))
(re-frame/reg-event-fx
::login
(fn [{:keys [db]} [_ credentials]] ;; credentials = {:email ... :password ...}
{:db (assoc-in db [:loading :login] true)
:http-xhrio {:method :post
:uri "/api/users/login"
:params {:user credentials} ;; {:user {:email ... :password ...}}
:format (json-request-format) ;; make sure it's json
:response-format (json-response-format {:keywords? true}) ;; json response and all keys to keywords
:on-success [::login-success] ;; trigger login-success
:on-failure [:api-request-error :login]}})) ;; trigger api-request-error with :login
(re-frame/reg-event-fx
::login-success
(fn [{:keys [db]} [_ {user :user}]]
{:db (update-in db [:user] merge user)
:dispatch-n (list [:complete-request :login])}))
(re-frame/reg-event-fx
::init-current-school
(fn [{:keys [db]} _]
{:db (assoc-in db [:loading :current-school] true)
:http-xhrio {:method :get
:uri "/api/schools/current"
:format (json-request-format)
:response-format (json-response-format {:keywords? true})
:on-success [::init-current-school-success]
:on-failure [:api-request-error :current-school]}}))
(re-frame/reg-event-fx
::init-current-school-success
(fn [{:keys [db]} [_ {school-id :id}]]
{:db (assoc db :school-id school-id)
:dispatch-n (list [:complete-request :current-school])}))
(re-frame/reg-event-fx
::init-current-user
(fn [{:keys [db]} _]
{:db (assoc-in db [:loading :current-user] true)
:http-xhrio {:method :get
:uri "/api/users/current"
:format (json-request-format)
:response-format (json-response-format {:keywords? true})
:on-success [::init-current-user-success]}}))
(re-frame/reg-event-fx
::init-current-user-success
(fn [{:keys [db]} [_ user]]
{:db (update-in db [:user] merge user)
:dispatch-n (list [:complete-request :current-user])}))
(re-frame/reg-cofx
:current-user
(fn [{:keys [db] :as co-effects}]
(->> (get db :user)
(assoc co-effects :current-user))))
;; -- Request Handlers -----------------------------------------------------------
;;
(re-frame/reg-event-db
:complete-request ;; when we complete a request we need to clean up
(fn-traced [db [_ request-type]] ;; few things so that our ui is nice and tidy
(assoc-in db [:loading request-type] false)))
(re-frame/reg-event-fx
:api-request-error ;; triggered when we get request-error from the server
(fn-traced [{:keys [db]} [_ request-type response]] ;; destructure to obtain request-type and response
{:db (assoc-in db [:errors request-type] (get-in response [:response :errors])) ;; save in db so that we can display it to the user
:dispatch-n (list [:complete-request request-type]
[::error-message/show request-type (get-in response [:response :errors])])}))
(re-frame/reg-event-fx
::set-active-route
(fn-traced [{:keys [db]} [_ params]]
{:db (assoc db :active-route params)}))
(re-frame/reg-event-fx
::redirect
(fn-traced [{:keys [db]} [_ & args]]
{:redirect args}))
(re-frame/reg-event-fx
::location
(fn-traced [{:keys [db]} [_ & args]]
{:location args}))
(re-frame/reg-fx
:callback
(fn [data]
(let [[callback & params] (if (sequential? data) data [data])]
(when (fn? callback)
(apply callback params)))))
| null | https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/70dd9b1d1c7c6d39ae744eacf040dd95019b6479/src/cljs/webchange/events.cljs | clojure | credentials = {:email ... :password ...}
{:user {:email ... :password ...}}
make sure it's json
json response and all keys to keywords
trigger login-success
trigger api-request-error with :login
-- Request Handlers -----------------------------------------------------------
when we complete a request we need to clean up
few things so that our ui is nice and tidy
triggered when we get request-error from the server
destructure to obtain request-type and response
save in db so that we can display it to the user | (ns webchange.events
(:require
[re-frame.core :as re-frame]
[webchange.db :as db]
[day8.re-frame.tracing :refer-macros [fn-traced defn-traced]]
[day8.re-frame.http-fx]
[ajax.core :refer [json-request-format json-response-format]]
[webchange.error-message.state :as error-message]))
(re-frame/reg-event-db
::initialize-db
(fn-traced [_ _]
db/default-db))
(re-frame/reg-event-db
::change-viewport
(fn [db [_ value]]
(assoc db :viewport value)))
(re-frame/reg-event-db
::set-loading-progress
(fn [db [_ scene-id value]]
(assoc-in db [:scene-loading-progress scene-id] value)))
(re-frame/reg-event-db
::set-scene-loaded
(fn [db [_ scene-id value]]
(assoc-in db [:scene-loading-complete scene-id] value)))
(re-frame/reg-event-fx
::login
{:db (assoc-in db [:loading :login] true)
:http-xhrio {:method :post
:uri "/api/users/login"
(re-frame/reg-event-fx
::login-success
(fn [{:keys [db]} [_ {user :user}]]
{:db (update-in db [:user] merge user)
:dispatch-n (list [:complete-request :login])}))
(re-frame/reg-event-fx
::init-current-school
(fn [{:keys [db]} _]
{:db (assoc-in db [:loading :current-school] true)
:http-xhrio {:method :get
:uri "/api/schools/current"
:format (json-request-format)
:response-format (json-response-format {:keywords? true})
:on-success [::init-current-school-success]
:on-failure [:api-request-error :current-school]}}))
(re-frame/reg-event-fx
::init-current-school-success
(fn [{:keys [db]} [_ {school-id :id}]]
{:db (assoc db :school-id school-id)
:dispatch-n (list [:complete-request :current-school])}))
(re-frame/reg-event-fx
::init-current-user
(fn [{:keys [db]} _]
{:db (assoc-in db [:loading :current-user] true)
:http-xhrio {:method :get
:uri "/api/users/current"
:format (json-request-format)
:response-format (json-response-format {:keywords? true})
:on-success [::init-current-user-success]}}))
(re-frame/reg-event-fx
::init-current-user-success
(fn [{:keys [db]} [_ user]]
{:db (update-in db [:user] merge user)
:dispatch-n (list [:complete-request :current-user])}))
(re-frame/reg-cofx
:current-user
(fn [{:keys [db] :as co-effects}]
(->> (get db :user)
(assoc co-effects :current-user))))
(re-frame/reg-event-db
(assoc-in db [:loading request-type] false)))
(re-frame/reg-event-fx
:dispatch-n (list [:complete-request request-type]
[::error-message/show request-type (get-in response [:response :errors])])}))
(re-frame/reg-event-fx
::set-active-route
(fn-traced [{:keys [db]} [_ params]]
{:db (assoc db :active-route params)}))
(re-frame/reg-event-fx
::redirect
(fn-traced [{:keys [db]} [_ & args]]
{:redirect args}))
(re-frame/reg-event-fx
::location
(fn-traced [{:keys [db]} [_ & args]]
{:location args}))
(re-frame/reg-fx
:callback
(fn [data]
(let [[callback & params] (if (sequential? data) data [data])]
(when (fn? callback)
(apply callback params)))))
|
fa601517fcf1f664d0b8955ec5c9155f49f7045f68157f39c30b4c23fc776c5f | nikvdp/bbb | dep_edn_alias.clj | (ns bbb.dep-edn-alias
(:require [clj.native-image]))
(defn tools-deps-entrypoint [{:keys [main-ns]}]
(clj.native-image/-main main-ns
"--initialize-at-build-time"
"--allow-incomplete-classpath"))
| null | https://raw.githubusercontent.com/nikvdp/bbb/2e08ea6ee4f0b750af735a80538fba4fdcf6af74/src/bbb/dep_edn_alias.clj | clojure | (ns bbb.dep-edn-alias
(:require [clj.native-image]))
(defn tools-deps-entrypoint [{:keys [main-ns]}]
(clj.native-image/-main main-ns
"--initialize-at-build-time"
"--allow-incomplete-classpath"))
| |
2f70a70f5c18f1a3815cd6976e597f87a7d2f4c6bf63d1e0d961be11764c1a26 | cljdoc/cljdoc | sanitize.clj | (ns cljdoc.render.sanitize
"Sanitize HTML
Goals
- disallow the blatantly dangerous, for example: `<script>` `onclick`, etc.
- allow valid html generated from markdown styling
- adoc generator includes `class` and very limited `style` attributes
- md generator includes minimal `class`
Of Interest
- Authors writing markdown can include arbitrary HTML in their docs.
It is just the nature of the adoc and md beasts.
- We don't expect authors will typically want to, but if they wish, they
can include `class` and `style` attributes in their arbitrary HTML that
match what our markdown to HTML generators produce.
Or more precisely, what our sanitizer allows through.
- Not that they'd necessarly want to, but we don't want authors using cljdoc site
stylings (currently tachyons) in their arbitrary HTML in their docs.
Strategies
- Start with a GitHub-like sanitizer config then tweak.
- Adoc. I've taken an oldish adoc user manual (the one I included in cljdoc-exerciser)
and analyzed the html produced by cljdoc.
This should give us an idea of what we should allow through.
This is pretty simple for most things, a little more complex for classes.
- Md. Much simpler, barely includes any class and no style.
- If a class attribute specifies an un-allowed css class, we'll
just strip that un-allowed css class.
- Log changes made by sanitizer to tags, attributes and attribute values.
This will be server side only for now, but will help us with any support and to tweak
our sanitizer config if necessary.
Technical choice:
- Chose java-html-sanitizer
- Also considered JSoup clean, because we are already using JSoup.
It did not have all the features of java-html-sanitizer, and right or wrong, I like
that the OWASP folks have a single focus library, it makes me think they spent lots
of time thinking about how to sanitize."
(:require [clojure.string :as string]
[clojure.tools.logging :as log])
(:import (org.owasp.html AttributePolicy
ElementPolicy
FilterUrlByProtocolAttributePolicy
Handler
HtmlSanitizer
HtmlSanitizer$Policy
HtmlStreamEventProcessor$Processors
HtmlStreamEventReceiver
HtmlStreamRenderer
HtmlPolicyBuilder
HtmlPolicyBuilder$AttributeBuilder
PolicyFactory))
(:require [clojure.string :as string]))
(set! *warn-on-reflection* true)
;; helpers for awkward interop
(defn- allow-tags
^HtmlPolicyBuilder [^HtmlPolicyBuilder builder & tags]
(.allowElements builder (into-array String tags)))
(defn- allow-attributes
^HtmlPolicyBuilder$AttributeBuilder [^HtmlPolicyBuilder builder & attrs]
(.allowAttributes builder (into-array String attrs)))
(defn- with-protocols
^HtmlPolicyBuilder$AttributeBuilder [^HtmlPolicyBuilder$AttributeBuilder builder & protocols]
(.matching builder (FilterUrlByProtocolAttributePolicy. protocols)))
(defn- on-tags
^HtmlPolicyBuilder [^HtmlPolicyBuilder$AttributeBuilder builder & tags]
(.onElements builder (into-array String tags)))
(defn- matching-vals
^HtmlPolicyBuilder$AttributeBuilder [^HtmlPolicyBuilder$AttributeBuilder builder & expected-values]
(-> builder
(.matching (proxy [AttributePolicy] []
(apply [tag-name attribute-name value]
(when (some (fn [test-value]
(if (string? test-value)
(= test-value value)
(re-matches test-value value)))
expected-values)
value))))))
(defn- class-matches? [t v]
(if (string? t)
(= t v)
(re-matches t v)))
(defn- sanitize-classes
"sanitize class-combos where a class-combo is:
[marker-class optional-class...]
where marker-class and optional-class can be a string or regular expression.
We match a class-combo on marker-class and then check that any other classes match optional-classes.
This seems to work well for our current use case.
Adjust as necessary if/when that stops being the case."
[policy & class-combos]
;; adoc roles can, I think, appear in any class attribute.
;; note that there are deprecated adoc roles such as colors (ex. `red` `background-green` etc) and
` big ` and ` small ` , we can add support for these if it makes sense to cljdoc and its users .
(let [global-classes ["underline" "overline" "line-through" "nobreak" "nowrap" "pre-wrap"]]
(-> policy
(allow-attributes "class")
(.matching (proxy [AttributePolicy] []
(apply [tag-name attribute-name value]
(let [cur-classes (string/split value #" +")
matching-combo (reduce (fn [_acc class-combo]
(let [marker-class (first class-combo)]
(when (some #(class-matches? marker-class %) cur-classes)
(reduced class-combo))))
nil
class-combos)
valid-classes (concat matching-combo global-classes)
[valid invalid] (reduce (fn [[valid invalid] cur-class]
(if (some #(class-matches? % cur-class) valid-classes)
[(conj valid cur-class) invalid]
[valid (conj invalid cur-class)]))
[[] []]
cur-classes)]
(if (seq invalid)
(when (seq valid)
(string/join " " valid))
value))))))))
(defn- allow-tag-with-attribute-value
"If tag does not include required-attribute with required-value, it will be dropped.
We deal with this at the tag level (rather than the attribute level) to allow dropping
a tag based on its attributes (rather than just dropping the attribute only)."
^HtmlPolicyBuilder [^HtmlPolicyBuilder builder tag required-attribute required-value]
(-> builder
(.allowElements (proxy [ElementPolicy] []
(apply [tag-name av-pairs]
(let [avs (->> av-pairs (partition 2) (map vec) (into {}))
actual-value (get avs required-attribute nil)]
(when (= required-value actual-value)
tag-name))))
(into-array String [tag]))))
(def ^:private ^PolicyFactory policy
(-> (HtmlPolicyBuilder.)
;; github pipeline sanitization ref:
;; -pipeline/blob/0e3d84eb13845e0d2521ef0dc13c9c51b88e5087/lib/html/pipeline/sanitization_filter.rb#L44-L106
(allow-tags
;; from github pipeline
"a" "abbr" "b" "bdo" "blockquote" "br" "caption" "cite" "code"
"dd" "del" "details" "dfn" "div" "dl" "dt" "em" "figcaption"
"figure" "h1" "h2" "h3" "h4" "h5" "h6" "h7" "h8" "hr"
"i" "img" "ins" "kbd" "li" "mark" "ol" "p" "pre" "q" "rp" "rt" "ruby"
"s" "samp" "small" "span" "strike" "strong" "sub" "summary" "sup"
"table" "tbody" "td" "tfoot" "th" "thead" "time" "tr" "tt" "ul" "var" "wbr"
;; adoc extras
"col" "colgroup" "input" "u")
(allow-attributes
;; from (former?) github pipeline, seems a bit permissive, but if gh was happy, probably fine
"abbr" "accept" "accept-charset"
"accesskey" "action" "align" "alt"
"aria-describedby" "aria-hidden" "aria-label" "aria-labelledby"
"axis" "border" "cellpadding" "cellspacing" "char"
"charoff" "charset" "charset" "checked" "clear"
"color" "cols" "colspan"
"compact" "coords" "datetime" "describedby"
"dir" "disabled" "enctype" "for"
"frame" "headers" "height" "hidden"
"hreflang" "hspace" "ismap"
"itemprop" "label" "label" "labelledby"
"lang" "maxlength" "media"
"method" "multiple" "name" "nohref"
"noshade" "nowrap" "open" "progress" "prompt" "readonly" "rel"
"rev" "role" "rows" "rowspan" "rules"
"scope" "selected" "shape" "size"
"span" "start" "summary" "tabindex"
"target" "title" "type" "usemap" "valign"
"value" "vspace" "width")
(.globally)
;; id attribute
assuming HTML5 ids are safe which is basically no spaces and more than 1 char .
(allow-attributes "id")
(matching-vals #"\S+")
(.globally)
;;
;; protocols, config inspired by github pipeline
;;
;; superset of all allowed protocols
(.allowUrlProtocols (into-array String ["http" "https" "mailto" "xmpp" "irc" "ircs" "viewsource"]))
(allow-attributes "href")
(with-protocols "http" "https" "mailto" "xmpp" "irc" "ircs" "viewsource")
(on-tags "a")
(allow-attributes "src" "longdesc")
(with-protocols "http" "https")
(on-tags "img")
(allow-attributes "cite")
(with-protocols "http" "https")
(on-tags "blockquote" "del" "ins" "q")
;;
;; specific attribute config
;;
for md wikilink support
(allow-attributes "data-source")
(matching-vals "wikilink")
(on-tags "a")
;; for code block callouts
(allow-attributes "data-value")
(on-tags "i")
;; mimic from github pipeline
(allow-attributes "itemscope" "itemtype")
(on-tags "div")
;; style restrictions for adoc
(allow-attributes "style")
(matching-vals #"width: \d+(\.\d+)?%;?")
(on-tags "col" "table")
;; adoc can show checkboxes, but that's the only input type that we should allow
(allow-tag-with-attribute-value "input" "type" "checkbox")
(allow-attributes "data-item-complete"
"checked")
(on-tags "input")
;; adoc allows reverse order lists
(allow-attributes "reversed")
(on-tags "ol")
;; allow data-lang on code blocks for formatting support
(allow-attributes "data-lang")
(on-tags "code")
;;
;; class - we'd like markdown styles to get through but not for
;; our users to do their own styling.
;; - assume adoc unless commented with md
;; - letting classes through allows us the freedom to style elements - but only if we want to.
;; - if some combo of classes aren't gettting through that is required for some sort of desired
;; styling, probably something I just missed, adjust as necessary
;;
;; Ref:
;;
;; currently not allowing (have not looked into)
;; - audioblock
;; - clearfix
;; - fa-* ;; font awesome classses, we don't currently use these
;; - float-group
;; - icon-caution
;; - icon-important
;; - icon-note
;; - icon-tip
;; - icon-warning
;; - toc-right
;; - videoblock
;; and I think these relate to highlighting featues which we do not use
;; - highlight
;; - linenos
;; - linenotable
;; - linenums
;; - prettyprint
;; I think these are maybe obsolete? or obscure?
;; - output
;; - subheader
;; - toc2
;; - tr.even
(sanitize-classes
["md-anchor"] ;; md
["anchor"]
["bare"]
["footnote"]
["image"]
["link"])
(on-tags "a")
(sanitize-classes
["button"]
["caret"]
["conum"]
["menu"]
["menuref"]
["menuitem"]
["submenu"])
(on-tags "b")
(sanitize-classes ["title"])
(on-tags "caption")
(sanitize-classes
[#"language-[-+_.a-zA-Z0-9]+"] ;; md & adoc
["code"])
(on-tags "code")
(sanitize-classes
["admonitionblock" #"(caution|important|note|tip|warning)"]
["attribution"]
["colist" "arabic"] ;; -- arabic only ??
["content"]
["details"]
["dlist" "gloassary"]
["exampleblock"]
["footnote"]
["hdlist"]
["imageblock" "left" "right" "thumb" "text-center" "text-right" "text-left"]
["listingblock"]
["literal"]
["literalblock"]
["olist" #"(arabic|decimal|lower(alpha|greek|roman)|upper(alpha|roman))"]
["openblock" "partintro"]
["paragraph" "lead"]
["qlist" "qanda"]
["quoteblock" "abstract"]
[#"sect[0-6]"]
["sectionbody"]
["sidebarblock"]
["stemblock"]
["title"]
["toc"]
["ulist" #"(bibliography|checklist|square)"]
["verseblock"])
(on-tags "div")
(sanitize-classes
["hdlist1"])
(on-tags "dt")
(sanitize-classes
["path"]
["term"])
(on-tags "em")
(sanitize-classes
["float"]
["sect0"])
(on-tags "h1")
(sanitize-classes
["float"])
(on-tags "h2" "h3" "h4" "h5" "h6")
;; for callout numbers and and potentially icons on admonitions
(sanitize-classes
["conum"]
["caret"]
["icon-important"]
["icon-warning"]
["icon-caution"]
["icon-tip"]
["icon-note"])
(on-tags "i")
(sanitize-classes
["arabic"]
["decimal"]
["loweralpha"]
["upperalpha"]
["lowergreek"]
["lowerroman"]
["upperroman"]
["no-bullet"]
["unnumbered"]
["unstyled"])
(on-tags "ol")
(sanitize-classes
["tableblock"]
["quoteblock"])
(on-tags "p")
(sanitize-classes
["content"]
["highlight"])
(on-tags "pre")
(sanitize-classes
["alt"]
["icon"]
["image" "left" "right"]
["keyseq"]
["menuseq"])
(on-tags "span")
(sanitize-classes
["footnote"]
["footnoteref"])
(on-tags "sup")
(sanitize-classes
["tableblock"
#"frame-(all|sides|ends|none)"
#"grid-(all|cols|rows|none)"
#"stripes-(even|odd|all|hover)"
"fit-content" "stretch" "unstyled"])
(on-tags "table")
(sanitize-classes
["content"]
["hdlist1"]
["hdlist2"]
["icon"]
["tableblock" #"halign-(left|center|right)" #"valign-(top|middle|bottom)"])
(on-tags "td" "th")
(sanitize-classes
["bibliography"]
["checklist"]
["circle"]
["disc"]
["inline"]
["none"]
["no-bullet"]
[#"sectlevel[0-6]"]
["square"]
["unstyled"])
(on-tags "ul")
(.toFactory)))
(defn clean*
"The java-html-sanitizer HtmlChangeReporter only supports reporting on discarded tags and attributes, and
not attribute values.
We essentially mimic its strategy here but support reporting on attribute values.
The strategy is:
- what the policy removed will not be rendered
- so, compare tag, by tag what is passed to policy vs what is actually rendered
This little lower-level complexity removes multiple higher-level work-arounds.
Careful in here, Java lists are mutable, so make copies."
[html]
(if (not html)
{:cleaned ""
:changes []}
(let [changes (atom [])
change-tracker (atom {})
out (StringBuilder. (count html))
renderer (HtmlStreamRenderer/create out Handler/DO_NOTHING)
wrapped-renderer (proxy [HtmlStreamEventReceiver] []
(openDocument [] (.openDocument renderer))
(closeDocument [] (.closeDocument renderer))
(openTag [tag av-pairs]
(reset! change-tracker {:rendered-tag tag
:rendered-av-pairs (into [] av-pairs)})
(.openTag renderer tag av-pairs))
(closeTag [tag-name] (.closeTag renderer tag-name))
(text [text] (.text renderer text)))
wrapped-policy (.apply policy wrapped-renderer)
wrapped-policy (proxy [HtmlSanitizer$Policy] []
(openDocument [] (.openDocument wrapped-policy))
(closeDocument [] (.closeDocument wrapped-policy))
(openTag [tag av-pairs]
(let [orig-av-pairs (into [] av-pairs)]
(reset! change-tracker {})
(.openTag wrapped-policy tag av-pairs)
(let [{:keys [rendered-tag rendered-av-pairs]} @change-tracker]
(reset! change-tracker {})
(if (not= rendered-tag tag)
(swap! changes conj {:type :removed
:tag tag
:attributes (partition 2 orig-av-pairs)})
(when (not= orig-av-pairs rendered-av-pairs)
(swap! changes conj {:type :modified
:tag tag
:old-attributes (partition 2 orig-av-pairs)
:new-attributes (partition 2 rendered-av-pairs)}))))))
(closeTag [tag-name] (.closeTag wrapped-policy tag-name))
(text [text] (.text wrapped-policy text)))]
(HtmlSanitizer/sanitize
html
wrapped-policy
HtmlStreamEventProcessor$Processors/IDENTITY)
{:cleaned (.toString out)
:changes @changes})))
(defn- triage-changes
"Attach a log level to changes."
[changes]
(for [c changes]
(if (= :removed (:type c))
(assoc c :level :info)
(let [new-attributes (->> c
:new-attributes
(map vec)
(into {}))
;; drive from old attributes, we don't care much if:
;; - the sanitizer has added attributes
;; - the sanitizer has changed attribute values by encoding only
;; - the new and old attribute values are the same
interesting-changes (->> (:old-attributes c)
(remove (fn [[old-attr old-value]]
(let [new-value (get new-attributes old-attr nil)]
(or (= old-value new-value)
;; assume that href/src, if present in both old and new is an encoding change
(and new-value (some #{old-attr} ["href" "src" "longdesc" "cite"])))))))]
(if (seq interesting-changes)
(assoc c :level :info)
(assoc c :level :debug))))))
(defn- log-changes [changes]
(doseq [{:keys [level] :as c} changes]
(log/log level (pr-str (dissoc c :level)))))
(defn clean
"Returns cleaned html string for given `html`.
Changes are logged:
- I don't see a need to format to text, just log the edn for now
- Some changes are uninteresting, like attribute addditions or simple escaping of urls,
these are currently logged anyway but at debug, rather than info level."
[html]
(let [{:keys [cleaned changes]} (clean* html)]
(-> changes
distinct ;; duplicates findings do not add value
triage-changes
log-changes)
cleaned))
(comment
(clean* "<div style=\"width: 10.3%;\">hiya</div>")
(clean* "<h1 bad='foo' id='ok' class='float boat'>")
(clean* "<hippo bad='foo' apple>")
(clean* "<img src='booya.png'>")
(clean* "<img src='mailto:'>")
(clean* "<a href='view-source:asciidoctor.org' target='_blank' rel='noopener'>Asciidoctor homepage</a>")
(clean* "<a href='mailto:'>hey</a>")
;; only using single quotes because they are easier on the eyes, sanitizer converts
(clean "<h1 id='3'>hi</h1> <script>alert('hey');</script>")
(clean "<q cite=''>hey</cite>")
(clean* "<h1 id='***'>boo</h1>")
(clean "<input>")
(clean "<input type='text' checked chucked>")
(clean "<input type='checkbox' checked chucked>")
(clean* "<a href='view-source:asciidoctor.org' target='_blank' rel='noopener'>Asciidoctor homepage</a>")
(clean* "<a href='mailto:'>hey</a>")
(clean "<a href=''>hey</a>");; => "hey"
(clean "<a href=' '>hey</a>");; => "hey"
(clean "<a class='amd-anchor foo' href='#' nope='dope'>hmm</a>")
(clean "<a class='md-anchor foo underline' href='#'>hmm</a>")
(clean "<a class='underline md-anchor foo' href='#'>hmm</a>")
(clean "<caption class='title'>Yup</caption>")
(clean "<caption class='underline'>Yup</caption>")
(clean "<caption>Yup</caption>")
(clean "<code class='code'>boo</code>")
(clean "<code class='language-foo.ffoo'>boo</code>")
(clean "<img src='().png'>")
(clean "<img src='().png' uhno>")
(distinct [8 1 22 1 3 8])
(clean "<img src='mailto:'>")
(clean "<table style='width: 13.5%;'></table>")
(clean "<table style='width: 10px;'></table>")
(clean "<table style='not: allowed;'>");; => "<table></table>"
(clean "<div class=\"ok foo nice\">hey ho</div>")
(clean "<table class='tableblock frame-ends grid-all unstyled2'>")
(clean "<a class=\"md-anchor\" href=\"#\">iii</a>")
(clean "<a class=\"language-foopack.roo\" href=\"#\">iii</a>")
(clean* "<a href=\"-clj/sponsor/4/website\" target=\"_blank\">boo</a>")
(clean* "<a href=\"-clj/sponsor/0/website\" target=\"_blank\"><img src=\"-clj/sponsor/0/avatar.svg\"></a>")
(spit "leetest-cleaned.html" (clean (slurp "leetest.html"))))
| null | https://raw.githubusercontent.com/cljdoc/cljdoc/b3e0b98adbd8290159582971fcfb59f9a4140967/src/cljdoc/render/sanitize.clj | clojure | helpers for awkward interop
adoc roles can, I think, appear in any class attribute.
note that there are deprecated adoc roles such as colors (ex. `red` `background-green` etc) and
github pipeline sanitization ref:
-pipeline/blob/0e3d84eb13845e0d2521ef0dc13c9c51b88e5087/lib/html/pipeline/sanitization_filter.rb#L44-L106
from github pipeline
adoc extras
from (former?) github pipeline, seems a bit permissive, but if gh was happy, probably fine
id attribute
protocols, config inspired by github pipeline
superset of all allowed protocols
specific attribute config
for code block callouts
mimic from github pipeline
style restrictions for adoc
adoc can show checkboxes, but that's the only input type that we should allow
adoc allows reverse order lists
allow data-lang on code blocks for formatting support
class - we'd like markdown styles to get through but not for
our users to do their own styling.
- assume adoc unless commented with md
- letting classes through allows us the freedom to style elements - but only if we want to.
- if some combo of classes aren't gettting through that is required for some sort of desired
styling, probably something I just missed, adjust as necessary
Ref:
currently not allowing (have not looked into)
- audioblock
- clearfix
- fa-* ;; font awesome classses, we don't currently use these
- float-group
- icon-caution
- icon-important
- icon-note
- icon-tip
- icon-warning
- toc-right
- videoblock
and I think these relate to highlighting featues which we do not use
- highlight
- linenos
- linenotable
- linenums
- prettyprint
I think these are maybe obsolete? or obscure?
- output
- subheader
- toc2
- tr.even
md
md & adoc
-- arabic only ??
for callout numbers and and potentially icons on admonitions
drive from old attributes, we don't care much if:
- the sanitizer has added attributes
- the sanitizer has changed attribute values by encoding only
- the new and old attribute values are the same
assume that href/src, if present in both old and new is an encoding change
duplicates findings do not add value
\">hiya</div>")
only using single quotes because they are easier on the eyes, sanitizer converts
=> "hey"
=> "hey"
=> "<table></table>" | (ns cljdoc.render.sanitize
"Sanitize HTML
Goals
- disallow the blatantly dangerous, for example: `<script>` `onclick`, etc.
- allow valid html generated from markdown styling
- adoc generator includes `class` and very limited `style` attributes
- md generator includes minimal `class`
Of Interest
- Authors writing markdown can include arbitrary HTML in their docs.
It is just the nature of the adoc and md beasts.
- We don't expect authors will typically want to, but if they wish, they
can include `class` and `style` attributes in their arbitrary HTML that
match what our markdown to HTML generators produce.
Or more precisely, what our sanitizer allows through.
- Not that they'd necessarly want to, but we don't want authors using cljdoc site
stylings (currently tachyons) in their arbitrary HTML in their docs.
Strategies
- Start with a GitHub-like sanitizer config then tweak.
- Adoc. I've taken an oldish adoc user manual (the one I included in cljdoc-exerciser)
and analyzed the html produced by cljdoc.
This should give us an idea of what we should allow through.
This is pretty simple for most things, a little more complex for classes.
- Md. Much simpler, barely includes any class and no style.
- If a class attribute specifies an un-allowed css class, we'll
just strip that un-allowed css class.
- Log changes made by sanitizer to tags, attributes and attribute values.
This will be server side only for now, but will help us with any support and to tweak
our sanitizer config if necessary.
Technical choice:
- Chose java-html-sanitizer
- Also considered JSoup clean, because we are already using JSoup.
It did not have all the features of java-html-sanitizer, and right or wrong, I like
that the OWASP folks have a single focus library, it makes me think they spent lots
of time thinking about how to sanitize."
(:require [clojure.string :as string]
[clojure.tools.logging :as log])
(:import (org.owasp.html AttributePolicy
ElementPolicy
FilterUrlByProtocolAttributePolicy
Handler
HtmlSanitizer
HtmlSanitizer$Policy
HtmlStreamEventProcessor$Processors
HtmlStreamEventReceiver
HtmlStreamRenderer
HtmlPolicyBuilder
HtmlPolicyBuilder$AttributeBuilder
PolicyFactory))
(:require [clojure.string :as string]))
(set! *warn-on-reflection* true)
(defn- allow-tags
^HtmlPolicyBuilder [^HtmlPolicyBuilder builder & tags]
(.allowElements builder (into-array String tags)))
(defn- allow-attributes
^HtmlPolicyBuilder$AttributeBuilder [^HtmlPolicyBuilder builder & attrs]
(.allowAttributes builder (into-array String attrs)))
(defn- with-protocols
^HtmlPolicyBuilder$AttributeBuilder [^HtmlPolicyBuilder$AttributeBuilder builder & protocols]
(.matching builder (FilterUrlByProtocolAttributePolicy. protocols)))
(defn- on-tags
^HtmlPolicyBuilder [^HtmlPolicyBuilder$AttributeBuilder builder & tags]
(.onElements builder (into-array String tags)))
(defn- matching-vals
^HtmlPolicyBuilder$AttributeBuilder [^HtmlPolicyBuilder$AttributeBuilder builder & expected-values]
(-> builder
(.matching (proxy [AttributePolicy] []
(apply [tag-name attribute-name value]
(when (some (fn [test-value]
(if (string? test-value)
(= test-value value)
(re-matches test-value value)))
expected-values)
value))))))
(defn- class-matches? [t v]
(if (string? t)
(= t v)
(re-matches t v)))
(defn- sanitize-classes
"sanitize class-combos where a class-combo is:
[marker-class optional-class...]
where marker-class and optional-class can be a string or regular expression.
We match a class-combo on marker-class and then check that any other classes match optional-classes.
This seems to work well for our current use case.
Adjust as necessary if/when that stops being the case."
[policy & class-combos]
` big ` and ` small ` , we can add support for these if it makes sense to cljdoc and its users .
(let [global-classes ["underline" "overline" "line-through" "nobreak" "nowrap" "pre-wrap"]]
(-> policy
(allow-attributes "class")
(.matching (proxy [AttributePolicy] []
(apply [tag-name attribute-name value]
(let [cur-classes (string/split value #" +")
matching-combo (reduce (fn [_acc class-combo]
(let [marker-class (first class-combo)]
(when (some #(class-matches? marker-class %) cur-classes)
(reduced class-combo))))
nil
class-combos)
valid-classes (concat matching-combo global-classes)
[valid invalid] (reduce (fn [[valid invalid] cur-class]
(if (some #(class-matches? % cur-class) valid-classes)
[(conj valid cur-class) invalid]
[valid (conj invalid cur-class)]))
[[] []]
cur-classes)]
(if (seq invalid)
(when (seq valid)
(string/join " " valid))
value))))))))
(defn- allow-tag-with-attribute-value
"If tag does not include required-attribute with required-value, it will be dropped.
We deal with this at the tag level (rather than the attribute level) to allow dropping
a tag based on its attributes (rather than just dropping the attribute only)."
^HtmlPolicyBuilder [^HtmlPolicyBuilder builder tag required-attribute required-value]
(-> builder
(.allowElements (proxy [ElementPolicy] []
(apply [tag-name av-pairs]
(let [avs (->> av-pairs (partition 2) (map vec) (into {}))
actual-value (get avs required-attribute nil)]
(when (= required-value actual-value)
tag-name))))
(into-array String [tag]))))
(def ^:private ^PolicyFactory policy
(-> (HtmlPolicyBuilder.)
(allow-tags
"a" "abbr" "b" "bdo" "blockquote" "br" "caption" "cite" "code"
"dd" "del" "details" "dfn" "div" "dl" "dt" "em" "figcaption"
"figure" "h1" "h2" "h3" "h4" "h5" "h6" "h7" "h8" "hr"
"i" "img" "ins" "kbd" "li" "mark" "ol" "p" "pre" "q" "rp" "rt" "ruby"
"s" "samp" "small" "span" "strike" "strong" "sub" "summary" "sup"
"table" "tbody" "td" "tfoot" "th" "thead" "time" "tr" "tt" "ul" "var" "wbr"
"col" "colgroup" "input" "u")
(allow-attributes
"abbr" "accept" "accept-charset"
"accesskey" "action" "align" "alt"
"aria-describedby" "aria-hidden" "aria-label" "aria-labelledby"
"axis" "border" "cellpadding" "cellspacing" "char"
"charoff" "charset" "charset" "checked" "clear"
"color" "cols" "colspan"
"compact" "coords" "datetime" "describedby"
"dir" "disabled" "enctype" "for"
"frame" "headers" "height" "hidden"
"hreflang" "hspace" "ismap"
"itemprop" "label" "label" "labelledby"
"lang" "maxlength" "media"
"method" "multiple" "name" "nohref"
"noshade" "nowrap" "open" "progress" "prompt" "readonly" "rel"
"rev" "role" "rows" "rowspan" "rules"
"scope" "selected" "shape" "size"
"span" "start" "summary" "tabindex"
"target" "title" "type" "usemap" "valign"
"value" "vspace" "width")
(.globally)
assuming HTML5 ids are safe which is basically no spaces and more than 1 char .
(allow-attributes "id")
(matching-vals #"\S+")
(.globally)
(.allowUrlProtocols (into-array String ["http" "https" "mailto" "xmpp" "irc" "ircs" "viewsource"]))
(allow-attributes "href")
(with-protocols "http" "https" "mailto" "xmpp" "irc" "ircs" "viewsource")
(on-tags "a")
(allow-attributes "src" "longdesc")
(with-protocols "http" "https")
(on-tags "img")
(allow-attributes "cite")
(with-protocols "http" "https")
(on-tags "blockquote" "del" "ins" "q")
for md wikilink support
(allow-attributes "data-source")
(matching-vals "wikilink")
(on-tags "a")
(allow-attributes "data-value")
(on-tags "i")
(allow-attributes "itemscope" "itemtype")
(on-tags "div")
(allow-attributes "style")
(matching-vals #"width: \d+(\.\d+)?%;?")
(on-tags "col" "table")
(allow-tag-with-attribute-value "input" "type" "checkbox")
(allow-attributes "data-item-complete"
"checked")
(on-tags "input")
(allow-attributes "reversed")
(on-tags "ol")
(allow-attributes "data-lang")
(on-tags "code")
(sanitize-classes
["anchor"]
["bare"]
["footnote"]
["image"]
["link"])
(on-tags "a")
(sanitize-classes
["button"]
["caret"]
["conum"]
["menu"]
["menuref"]
["menuitem"]
["submenu"])
(on-tags "b")
(sanitize-classes ["title"])
(on-tags "caption")
(sanitize-classes
["code"])
(on-tags "code")
(sanitize-classes
["admonitionblock" #"(caution|important|note|tip|warning)"]
["attribution"]
["content"]
["details"]
["dlist" "gloassary"]
["exampleblock"]
["footnote"]
["hdlist"]
["imageblock" "left" "right" "thumb" "text-center" "text-right" "text-left"]
["listingblock"]
["literal"]
["literalblock"]
["olist" #"(arabic|decimal|lower(alpha|greek|roman)|upper(alpha|roman))"]
["openblock" "partintro"]
["paragraph" "lead"]
["qlist" "qanda"]
["quoteblock" "abstract"]
[#"sect[0-6]"]
["sectionbody"]
["sidebarblock"]
["stemblock"]
["title"]
["toc"]
["ulist" #"(bibliography|checklist|square)"]
["verseblock"])
(on-tags "div")
(sanitize-classes
["hdlist1"])
(on-tags "dt")
(sanitize-classes
["path"]
["term"])
(on-tags "em")
(sanitize-classes
["float"]
["sect0"])
(on-tags "h1")
(sanitize-classes
["float"])
(on-tags "h2" "h3" "h4" "h5" "h6")
(sanitize-classes
["conum"]
["caret"]
["icon-important"]
["icon-warning"]
["icon-caution"]
["icon-tip"]
["icon-note"])
(on-tags "i")
(sanitize-classes
["arabic"]
["decimal"]
["loweralpha"]
["upperalpha"]
["lowergreek"]
["lowerroman"]
["upperroman"]
["no-bullet"]
["unnumbered"]
["unstyled"])
(on-tags "ol")
(sanitize-classes
["tableblock"]
["quoteblock"])
(on-tags "p")
(sanitize-classes
["content"]
["highlight"])
(on-tags "pre")
(sanitize-classes
["alt"]
["icon"]
["image" "left" "right"]
["keyseq"]
["menuseq"])
(on-tags "span")
(sanitize-classes
["footnote"]
["footnoteref"])
(on-tags "sup")
(sanitize-classes
["tableblock"
#"frame-(all|sides|ends|none)"
#"grid-(all|cols|rows|none)"
#"stripes-(even|odd|all|hover)"
"fit-content" "stretch" "unstyled"])
(on-tags "table")
(sanitize-classes
["content"]
["hdlist1"]
["hdlist2"]
["icon"]
["tableblock" #"halign-(left|center|right)" #"valign-(top|middle|bottom)"])
(on-tags "td" "th")
(sanitize-classes
["bibliography"]
["checklist"]
["circle"]
["disc"]
["inline"]
["none"]
["no-bullet"]
[#"sectlevel[0-6]"]
["square"]
["unstyled"])
(on-tags "ul")
(.toFactory)))
(defn clean*
"The java-html-sanitizer HtmlChangeReporter only supports reporting on discarded tags and attributes, and
not attribute values.
We essentially mimic its strategy here but support reporting on attribute values.
The strategy is:
- what the policy removed will not be rendered
- so, compare tag, by tag what is passed to policy vs what is actually rendered
This little lower-level complexity removes multiple higher-level work-arounds.
Careful in here, Java lists are mutable, so make copies."
[html]
(if (not html)
{:cleaned ""
:changes []}
(let [changes (atom [])
change-tracker (atom {})
out (StringBuilder. (count html))
renderer (HtmlStreamRenderer/create out Handler/DO_NOTHING)
wrapped-renderer (proxy [HtmlStreamEventReceiver] []
(openDocument [] (.openDocument renderer))
(closeDocument [] (.closeDocument renderer))
(openTag [tag av-pairs]
(reset! change-tracker {:rendered-tag tag
:rendered-av-pairs (into [] av-pairs)})
(.openTag renderer tag av-pairs))
(closeTag [tag-name] (.closeTag renderer tag-name))
(text [text] (.text renderer text)))
wrapped-policy (.apply policy wrapped-renderer)
wrapped-policy (proxy [HtmlSanitizer$Policy] []
(openDocument [] (.openDocument wrapped-policy))
(closeDocument [] (.closeDocument wrapped-policy))
(openTag [tag av-pairs]
(let [orig-av-pairs (into [] av-pairs)]
(reset! change-tracker {})
(.openTag wrapped-policy tag av-pairs)
(let [{:keys [rendered-tag rendered-av-pairs]} @change-tracker]
(reset! change-tracker {})
(if (not= rendered-tag tag)
(swap! changes conj {:type :removed
:tag tag
:attributes (partition 2 orig-av-pairs)})
(when (not= orig-av-pairs rendered-av-pairs)
(swap! changes conj {:type :modified
:tag tag
:old-attributes (partition 2 orig-av-pairs)
:new-attributes (partition 2 rendered-av-pairs)}))))))
(closeTag [tag-name] (.closeTag wrapped-policy tag-name))
(text [text] (.text wrapped-policy text)))]
(HtmlSanitizer/sanitize
html
wrapped-policy
HtmlStreamEventProcessor$Processors/IDENTITY)
{:cleaned (.toString out)
:changes @changes})))
(defn- triage-changes
"Attach a log level to changes."
[changes]
(for [c changes]
(if (= :removed (:type c))
(assoc c :level :info)
(let [new-attributes (->> c
:new-attributes
(map vec)
(into {}))
interesting-changes (->> (:old-attributes c)
(remove (fn [[old-attr old-value]]
(let [new-value (get new-attributes old-attr nil)]
(or (= old-value new-value)
(and new-value (some #{old-attr} ["href" "src" "longdesc" "cite"])))))))]
(if (seq interesting-changes)
(assoc c :level :info)
(assoc c :level :debug))))))
(defn- log-changes [changes]
(doseq [{:keys [level] :as c} changes]
(log/log level (pr-str (dissoc c :level)))))
(defn clean
"Returns cleaned html string for given `html`.
Changes are logged:
- I don't see a need to format to text, just log the edn for now
- Some changes are uninteresting, like attribute addditions or simple escaping of urls,
these are currently logged anyway but at debug, rather than info level."
[html]
(let [{:keys [cleaned changes]} (clean* html)]
(-> changes
triage-changes
log-changes)
cleaned))
(comment
(clean* "<h1 bad='foo' id='ok' class='float boat'>")
(clean* "<hippo bad='foo' apple>")
(clean* "<img src='booya.png'>")
(clean* "<img src='mailto:'>")
(clean* "<a href='view-source:asciidoctor.org' target='_blank' rel='noopener'>Asciidoctor homepage</a>")
(clean* "<a href='mailto:'>hey</a>")
(clean "<h1 id='3'>hi</h1> <script>alert('hey');</script>")
(clean "<q cite=''>hey</cite>")
(clean* "<h1 id='***'>boo</h1>")
(clean "<input>")
(clean "<input type='text' checked chucked>")
(clean "<input type='checkbox' checked chucked>")
(clean* "<a href='view-source:asciidoctor.org' target='_blank' rel='noopener'>Asciidoctor homepage</a>")
(clean* "<a href='mailto:'>hey</a>")
(clean "<a class='amd-anchor foo' href='#' nope='dope'>hmm</a>")
(clean "<a class='md-anchor foo underline' href='#'>hmm</a>")
(clean "<a class='underline md-anchor foo' href='#'>hmm</a>")
(clean "<caption class='title'>Yup</caption>")
(clean "<caption class='underline'>Yup</caption>")
(clean "<caption>Yup</caption>")
(clean "<code class='code'>boo</code>")
(clean "<code class='language-foo.ffoo'>boo</code>")
(clean "<img src='().png'>")
(clean "<img src='().png' uhno>")
(distinct [8 1 22 1 3 8])
(clean "<img src='mailto:'>")
(clean "<table style='width: 13.5%;'></table>")
(clean "<table style='width: 10px;'></table>")
(clean "<div class=\"ok foo nice\">hey ho</div>")
(clean "<table class='tableblock frame-ends grid-all unstyled2'>")
(clean "<a class=\"md-anchor\" href=\"#\">iii</a>")
(clean "<a class=\"language-foopack.roo\" href=\"#\">iii</a>")
(clean* "<a href=\"-clj/sponsor/4/website\" target=\"_blank\">boo</a>")
(clean* "<a href=\"-clj/sponsor/0/website\" target=\"_blank\"><img src=\"-clj/sponsor/0/avatar.svg\"></a>")
(spit "leetest-cleaned.html" (clean (slurp "leetest.html"))))
|
dc050ff2396a7cee9b136bdbb1055b4bba979ae05b68bd0d808e864293a895df | issuu/ocaml-protoc-plugin | extensions.ml | open StdLabels
type t = (int * Field.t) list
let default = []
let pp_item fmt (index, field) = Format.fprintf fmt "(%d, %a)" index Field.pp field
let pp : Format.formatter -> t -> unit = fun fmt -> Format.pp_print_list pp_item fmt
let show : t -> string = Format.asprintf "%a" pp
let equal _ _ = true
let compare _ _ = 0
let get: ('b -> 'b, 'b) Deserialize.S.compound_list -> t -> 'b Result.t = fun spec t ->
let writer = Writer.of_list t in
(* Back and forth - its the same, no? *)
let reader = Writer.contents writer |> Reader.create in
Deserialize.deserialize [] spec (fun _ a -> a) reader
let set: ('a -> Writer.t, Writer.t) Serialize.S.compound_list -> t -> 'a -> t = fun spec t v ->
let writer = Serialize.serialize [] spec [] v in
let reader = Writer.contents writer |> Reader.create in
match Reader.to_list reader |> Result.get ~msg:"Internal serialization fail" with
| (((index, _) :: _) as fields) ->
(List.filter ~f:(fun (i, _) -> i != index) t) @ fields
| [] -> t
| null | https://raw.githubusercontent.com/issuu/ocaml-protoc-plugin/3d8b3eeb48e2a58dc80fbfdf9d749e69676625ab/src/ocaml_protoc_plugin/extensions.ml | ocaml | Back and forth - its the same, no? | open StdLabels
type t = (int * Field.t) list
let default = []
let pp_item fmt (index, field) = Format.fprintf fmt "(%d, %a)" index Field.pp field
let pp : Format.formatter -> t -> unit = fun fmt -> Format.pp_print_list pp_item fmt
let show : t -> string = Format.asprintf "%a" pp
let equal _ _ = true
let compare _ _ = 0
let get: ('b -> 'b, 'b) Deserialize.S.compound_list -> t -> 'b Result.t = fun spec t ->
let writer = Writer.of_list t in
let reader = Writer.contents writer |> Reader.create in
Deserialize.deserialize [] spec (fun _ a -> a) reader
let set: ('a -> Writer.t, Writer.t) Serialize.S.compound_list -> t -> 'a -> t = fun spec t v ->
let writer = Serialize.serialize [] spec [] v in
let reader = Writer.contents writer |> Reader.create in
match Reader.to_list reader |> Result.get ~msg:"Internal serialization fail" with
| (((index, _) :: _) as fields) ->
(List.filter ~f:(fun (i, _) -> i != index) t) @ fields
| [] -> t
|
2dae78702ebedff0bdf94ba5f40ec82c6bb4cba6c6669a1b5c00ead9ef55aaa9 | NathanReb/ppx_yojson | utils.mli | (** General puprose helper functions *)
val remove : idx:int -> 'a list -> 'a list
(** Return the given list without the element at index [idx].
If [idx] is not a valid index in the given list, it is returned as is.
*)
val permutations : 'a list -> 'a list list
(** Return all the permutations of the given list *)
| null | https://raw.githubusercontent.com/NathanReb/ppx_yojson/085844cbbbc199689faeeee0c9bc1f4d9bc5f4f9/lib/utils.mli | ocaml | * General puprose helper functions
* Return the given list without the element at index [idx].
If [idx] is not a valid index in the given list, it is returned as is.
* Return all the permutations of the given list |
val remove : idx:int -> 'a list -> 'a list
val permutations : 'a list -> 'a list list
|
a73067394976da58fab577c8226491f06d040a8828832ab14503f0bab3822976 | raviksharma/bartosz-basics-of-haskell | showcontent.hs | data Operator = Plus | Minus | Times | Div
deriving (Show, Eq)
opToStr :: Operator -> String
opToStr Plus = "+"
opToStr Minus = "-"
opToStr Times = "*"
opToStr Div = "/"
data Token = TokOp Operator
| TokIdent String
| TokNum Int
deriving (Show, Eq)
showContent :: Token -> String
showContent (TokOp op) = opToStr op
showContent (TokIdent str) = str
showContent (TokNum i) = show i
token :: Token
token = TokIdent "x"
token2 :: Token
token2 = TokOp Plus
main = do
putStrLn $ showContent token
print token
putStrLn $ showContent token2
print token2
putStrLn $ showContent (TokNum 5)
| null | https://raw.githubusercontent.com/raviksharma/bartosz-basics-of-haskell/86d40d831f61415ef0022bff7fe7060ae6a23701/05-tokenizer-data-types/showcontent.hs | haskell | data Operator = Plus | Minus | Times | Div
deriving (Show, Eq)
opToStr :: Operator -> String
opToStr Plus = "+"
opToStr Minus = "-"
opToStr Times = "*"
opToStr Div = "/"
data Token = TokOp Operator
| TokIdent String
| TokNum Int
deriving (Show, Eq)
showContent :: Token -> String
showContent (TokOp op) = opToStr op
showContent (TokIdent str) = str
showContent (TokNum i) = show i
token :: Token
token = TokIdent "x"
token2 :: Token
token2 = TokOp Plus
main = do
putStrLn $ showContent token
print token
putStrLn $ showContent token2
print token2
putStrLn $ showContent (TokNum 5)
| |
f60f9d8296fe7ab74828a9e901c9ead5b6a6d51fc0317775fde7f8b54d8dabac | monadfix/ormolu-live | PatSyn.hs |
( c ) The University of Glasgow 2006
( c ) The GRASP / AQUA Project , Glasgow University , 1998
\section[PatSyn]{@PatSyn@ : Pattern synonyms }
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1998
\section[PatSyn]{@PatSyn@: Pattern synonyms}
-}
# LANGUAGE CPP #
module PatSyn (
-- * Main data types
PatSyn, mkPatSyn,
-- ** Type deconstruction
patSynName, patSynArity, patSynIsInfix,
patSynArgs,
patSynMatcher, patSynBuilder,
patSynUnivTyVarBinders, patSynExTyVars, patSynExTyVarBinders, patSynSig,
patSynInstArgTys, patSynInstResTy, patSynFieldLabels,
patSynFieldType,
updatePatSynIds, pprPatSynType
) where
#include "HsVersions2.h"
import GhcPrelude
import Type
import TyCoPpr
import Name
import Outputable
import Unique
import Util
import BasicTypes
import Var
import FieldLabel
import qualified Data.Data as Data
import Data.Function
import Data.List (find)
{-
************************************************************************
* *
\subsection{Pattern synonyms}
* *
************************************************************************
-}
-- | Pattern Synonym
--
-- See Note [Pattern synonym representation]
-- See Note [Pattern synonym signature contexts]
data PatSyn
= MkPatSyn {
psName :: Name,
psUnique :: Unique, -- Cached from Name
psArgs :: [Type],
psArity :: Arity, -- == length psArgs
psInfix :: Bool, -- True <=> declared infix
psFieldLabels :: [FieldLabel], -- List of fields for a
-- record pattern synonym
INVARIANT : either empty if no
-- record pat syn or same length as
-- psArgs
Universally - quantified type variables
psUnivTyVars :: [TyVarBinder],
-- Required dictionaries (may mention psUnivTyVars)
psReqTheta :: ThetaType,
Existentially - quantified type vars
psExTyVars :: [TyVarBinder],
-- Provided dictionaries (may mention psUnivTyVars or psExTyVars)
psProvTheta :: ThetaType,
-- Result type
psResultTy :: Type, -- Mentions only psUnivTyVars
-- See Note [Pattern synonym result type]
-- See Note [Matchers and builders for pattern synonyms]
psMatcher :: (Id, Bool),
-- Matcher function.
If is True then prov_theta and arg_tys are empty
-- and type is
forall ( p : : RuntimeRep ) ( r : : TYPE p ) univ_tvs .
-- req_theta
-- => res_ty
-- -> (forall ex_tvs. Void# -> r)
-- -> (Void# -> r)
-- -> r
--
-- Otherwise type is
forall ( p : : RuntimeRep ) ( r : : TYPE r ) univ_tvs .
-- req_theta
-- => res_ty
-- -> (forall ex_tvs. prov_theta => arg_tys -> r)
-- -> (Void# -> r)
-- -> r
psBuilder :: Maybe (Id, Bool)
-- Nothing => uni-directional pattern synonym
-- Just (builder, is_unlifted) => bi-directional
-- Builder function, of type
-- forall univ_tvs, ex_tvs. (req_theta, prov_theta)
-- => arg_tys -> res_ty
-- See Note [Builder for pattern synonyms with unboxed type]
}
Note [ Pattern synonym signature contexts ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a pattern synonym signature we write
pattern P : : req = > prov = > t1 - > ... tn - > res_ty
Note that the " required " context comes first , then the " provided "
context . Moreover , the " required " context must not mention
existentially - bound type variables ; that is , ones not mentioned in
res_ty . See lots of discussion in # 10928 .
If there is no " provided " context , you can omit it ; but you
ca n't omit the " required " part ( unless you omit both ) .
Example 1 :
pattern P1 : : ( a , a ) = > b - > Maybe ( a , b )
pattern P1 x = Just ( 3,x )
We require ( a , a ) to match the 3 ; there is no provided
context .
Example 2 :
data T2 where
MkT2 : : ( a , a ) = > a - > a - > T2
pattern P2 : : ( ) = > ( a , a ) = > a - > T2
pattern P2 x = MkT2 3 x
When we match against P2 we get a dictionary provided .
We can use that to check the match against 3 .
Example 3 :
pattern P3 : : Eq a = > a - > b - > T3 b
This signature is illegal because the ( Eq a ) is a required
constraint , but it mentions the existentially - bound variable ' a ' .
You can see it 's existential because it does n't appear in the
result type ( T3 b ) .
Note [ Pattern synonym result type ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data T a b = MkT b a
pattern P : : a - > T [ a ] Bool
pattern P x = MkT True [ x ]
P 's psResultTy is ( T a Bool ) , and it really only matches values of
type ( T [ a ] Bool ) . For example , this is ill - typed
f : : T p q - > String
f ( P x ) = " urk "
This is different to the situation with GADTs :
data S a where
MkS : : Int - > S Bool
Now MkS ( and pattern synonyms coming from MkS ) can match a
value of type ( S a ) , not just ( S Bool ) ; we get type refinement .
That in turn means that if you have a pattern
P x : : T [ ty ]
it 's not entirely straightforward to work out the instantiation of
P 's universal tyvars . You have to /match/
the type of the pattern , ( T [ ty ] )
against
the psResultTy for the pattern synonym , T [ a ] Bool
to get the instantiation a : = ty .
This is very unlike DataCons , where univ tyvars match 1 - 1 the
arguments of the .
Side note : I ( SG ) get the impression that instantiated return types should
generate a * required * constraint for pattern synonyms , rather than a * provided *
constraint like it 's the case for GADTs . For example , I 'd expect these
declarations to have identical semantics :
pattern : : Maybe Int
pattern = Just 42
pattern Just'42 : : ( a ~ Int ) = > Maybe a
pattern Just'42 = Just 42
The latter generates the proper required constraint , the former does not .
Also rather different to GADTs is the fact that does n't have any
universally quantified type variables , whereas Just'42 or MkS above has .
Note [ Pattern synonym representation ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following pattern synonym declaration
pattern P x = MkT [ x ] ( Just 42 )
where
data T a where
MkT : : ( Show a , Ord b ) = > [ b ] - > a - > T a
so pattern P has type
b - > T ( Maybe t )
with the following typeclass constraints :
requires : ( Eq t , t )
provides : ( Show ( Maybe t ) , b )
In this case , the fields of MkPatSyn will be set as follows :
psArgs = [ b ]
psArity = 1
psInfix = False
psUnivTyVars = [ t ]
psExTyVars = [ b ]
psProvTheta = ( Show ( Maybe t ) , b )
psReqTheta = ( Eq t , t )
psResultTy = T ( Maybe t )
Note [ Matchers and builders for pattern synonyms ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For each pattern synonym P , we generate
* a " matcher " function , used to uses of P in patterns ,
which implements pattern matching
* A " builder " function ( for bidirectional pattern synonyms only ) ,
used to uses of P in expressions , which constructs P - values .
For the above example , the matcher function has type :
$ mP : : forall ( r : : ? ) t. ( Eq t , t )
= > T ( Maybe t )
- > ( forall b. ( Show ( Maybe t ) , b ) = > b - > r )
- > ( Void # - > r )
- > r
with the following implementation :
$ mP @r @t $ dEq $ dNum scrut cont fail
= case scrut of
MkT @b [ x ] ( Just 42 ) - > cont @b $ dShow $ dOrd x
_ - > fail Void #
Notice that the return type ' r ' has an open kind , so that it can
be instantiated by an unboxed type ; for example where we see
f ( P x ) = 3 #
The extra Void # argument for the failure continuation is needed so that
it is lazy even when the result type is unboxed .
For the same reason , if the pattern has no arguments , an extra Void #
argument is added to the success continuation as well .
For * bidirectional * pattern synonyms , we also generate a " builder "
function which implements the pattern synonym in an expression
context . For our running example , it will be :
$ bP : : forall t b. ( Eq t , t , Show ( Maybe t ) , b )
= > b - > T ( Maybe t )
$ bP x = MkT [ x ] ( Just 42 )
NB : the existential / universal and required / provided split does not
apply to the builder since you are only putting stuff in , not getting
stuff out .
Injectivity of bidirectional pattern synonyms is checked in
tcPatToExpr which walks the pattern and returns its corresponding
expression when available .
Note [ Builder for pattern synonyms with unboxed type ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For bidirectional pattern synonyms that have no arguments and have an
unboxed type , we add an extra Void # argument to the builder , else it
would be a top - level declaration with an unboxed type .
pattern P = 0 #
$ bP : : Void # - > Int #
$ bP _ = 0 #
This means that when typechecking an occurrence of P in an expression ,
we must remember that the builder has this void argument . This is
done by TcPatSyn.patSynBuilderOcc .
Note [ Pattern synonyms and the data type Type ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The type of a pattern synonym is of the form ( See Note
[ Pattern synonym signatures ] in ):
forall univ_tvs . req = > forall ex_tvs . prov = > ...
We can not in general represent this by a value of type Type :
- if ex_tvs is empty , then req and prov can not be distinguished from
each other
- if req is empty , then univ_tvs and ex_tvs can not be distinguished
from each other , and moreover , prov is seen as the " required " context
( as it is the only context )
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
\subsection{Instances }
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a pattern synonym signature we write
pattern P :: req => prov => t1 -> ... tn -> res_ty
Note that the "required" context comes first, then the "provided"
context. Moreover, the "required" context must not mention
existentially-bound type variables; that is, ones not mentioned in
res_ty. See lots of discussion in #10928.
If there is no "provided" context, you can omit it; but you
can't omit the "required" part (unless you omit both).
Example 1:
pattern P1 :: (Num a, Eq a) => b -> Maybe (a,b)
pattern P1 x = Just (3,x)
We require (Num a, Eq a) to match the 3; there is no provided
context.
Example 2:
data T2 where
MkT2 :: (Num a, Eq a) => a -> a -> T2
pattern P2 :: () => (Num a, Eq a) => a -> T2
pattern P2 x = MkT2 3 x
When we match against P2 we get a Num dictionary provided.
We can use that to check the match against 3.
Example 3:
pattern P3 :: Eq a => a -> b -> T3 b
This signature is illegal because the (Eq a) is a required
constraint, but it mentions the existentially-bound variable 'a'.
You can see it's existential because it doesn't appear in the
result type (T3 b).
Note [Pattern synonym result type]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data T a b = MkT b a
pattern P :: a -> T [a] Bool
pattern P x = MkT True [x]
P's psResultTy is (T a Bool), and it really only matches values of
type (T [a] Bool). For example, this is ill-typed
f :: T p q -> String
f (P x) = "urk"
This is different to the situation with GADTs:
data S a where
MkS :: Int -> S Bool
Now MkS (and pattern synonyms coming from MkS) can match a
value of type (S a), not just (S Bool); we get type refinement.
That in turn means that if you have a pattern
P x :: T [ty] Bool
it's not entirely straightforward to work out the instantiation of
P's universal tyvars. You have to /match/
the type of the pattern, (T [ty] Bool)
against
the psResultTy for the pattern synonym, T [a] Bool
to get the instantiation a := ty.
This is very unlike DataCons, where univ tyvars match 1-1 the
arguments of the TyCon.
Side note: I (SG) get the impression that instantiated return types should
generate a *required* constraint for pattern synonyms, rather than a *provided*
constraint like it's the case for GADTs. For example, I'd expect these
declarations to have identical semantics:
pattern Just42 :: Maybe Int
pattern Just42 = Just 42
pattern Just'42 :: (a ~ Int) => Maybe a
pattern Just'42 = Just 42
The latter generates the proper required constraint, the former does not.
Also rather different to GADTs is the fact that Just42 doesn't have any
universally quantified type variables, whereas Just'42 or MkS above has.
Note [Pattern synonym representation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following pattern synonym declaration
pattern P x = MkT [x] (Just 42)
where
data T a where
MkT :: (Show a, Ord b) => [b] -> a -> T a
so pattern P has type
b -> T (Maybe t)
with the following typeclass constraints:
requires: (Eq t, Num t)
provides: (Show (Maybe t), Ord b)
In this case, the fields of MkPatSyn will be set as follows:
psArgs = [b]
psArity = 1
psInfix = False
psUnivTyVars = [t]
psExTyVars = [b]
psProvTheta = (Show (Maybe t), Ord b)
psReqTheta = (Eq t, Num t)
psResultTy = T (Maybe t)
Note [Matchers and builders for pattern synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For each pattern synonym P, we generate
* a "matcher" function, used to desugar uses of P in patterns,
which implements pattern matching
* A "builder" function (for bidirectional pattern synonyms only),
used to desugar uses of P in expressions, which constructs P-values.
For the above example, the matcher function has type:
$mP :: forall (r :: ?) t. (Eq t, Num t)
=> T (Maybe t)
-> (forall b. (Show (Maybe t), Ord b) => b -> r)
-> (Void# -> r)
-> r
with the following implementation:
$mP @r @t $dEq $dNum scrut cont fail
= case scrut of
MkT @b $dShow $dOrd [x] (Just 42) -> cont @b $dShow $dOrd x
_ -> fail Void#
Notice that the return type 'r' has an open kind, so that it can
be instantiated by an unboxed type; for example where we see
f (P x) = 3#
The extra Void# argument for the failure continuation is needed so that
it is lazy even when the result type is unboxed.
For the same reason, if the pattern has no arguments, an extra Void#
argument is added to the success continuation as well.
For *bidirectional* pattern synonyms, we also generate a "builder"
function which implements the pattern synonym in an expression
context. For our running example, it will be:
$bP :: forall t b. (Eq t, Num t, Show (Maybe t), Ord b)
=> b -> T (Maybe t)
$bP x = MkT [x] (Just 42)
NB: the existential/universal and required/provided split does not
apply to the builder since you are only putting stuff in, not getting
stuff out.
Injectivity of bidirectional pattern synonyms is checked in
tcPatToExpr which walks the pattern and returns its corresponding
expression when available.
Note [Builder for pattern synonyms with unboxed type]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For bidirectional pattern synonyms that have no arguments and have an
unboxed type, we add an extra Void# argument to the builder, else it
would be a top-level declaration with an unboxed type.
pattern P = 0#
$bP :: Void# -> Int#
$bP _ = 0#
This means that when typechecking an occurrence of P in an expression,
we must remember that the builder has this void argument. This is
done by TcPatSyn.patSynBuilderOcc.
Note [Pattern synonyms and the data type Type]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The type of a pattern synonym is of the form (See Note
[Pattern synonym signatures] in TcSigs):
forall univ_tvs. req => forall ex_tvs. prov => ...
We cannot in general represent this by a value of type Type:
- if ex_tvs is empty, then req and prov cannot be distinguished from
each other
- if req is empty, then univ_tvs and ex_tvs cannot be distinguished
from each other, and moreover, prov is seen as the "required" context
(as it is the only context)
************************************************************************
* *
\subsection{Instances}
* *
************************************************************************
-}
instance Eq PatSyn where
(==) = (==) `on` getUnique
(/=) = (/=) `on` getUnique
instance Uniquable PatSyn where
getUnique = psUnique
instance NamedThing PatSyn where
getName = patSynName
instance Outputable PatSyn where
ppr = ppr . getName
instance OutputableBndr PatSyn where
pprInfixOcc = pprInfixName . getName
pprPrefixOcc = pprPrefixName . getName
instance Data.Data PatSyn where
-- don't traverse?
toConstr _ = abstractConstr "PatSyn"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "PatSyn"
{-
************************************************************************
* *
\subsection{Construction}
* *
************************************************************************
-}
-- | Build a new pattern synonym
mkPatSyn :: Name
-> Bool -- ^ Is the pattern synonym declared infix?
^ Universially - quantified type
variables and required dicts
^ - quantified type
variables and provided dicts
-> [Type] -- ^ Original arguments
-> Type -- ^ Original result type
-> (Id, Bool) -- ^ Name of matcher
-> Maybe (Id, Bool) -- ^ Name of builder
-> [FieldLabel] -- ^ Names of fields for
-- a record pattern synonym
-> PatSyn
NB : The univ and ex vars are both in TyBinder form and TyVar form for
convenience . All the TyBinders should be Named !
mkPatSyn name declared_infix
(univ_tvs, req_theta)
(ex_tvs, prov_theta)
orig_args
orig_res_ty
matcher builder field_labels
= MkPatSyn {psName = name, psUnique = getUnique name,
psUnivTyVars = univ_tvs,
psExTyVars = ex_tvs,
psProvTheta = prov_theta, psReqTheta = req_theta,
psInfix = declared_infix,
psArgs = orig_args,
psArity = length orig_args,
psResultTy = orig_res_ty,
psMatcher = matcher,
psBuilder = builder,
psFieldLabels = field_labels
}
-- | The 'Name' of the 'PatSyn', giving it a unique, rooted identification
patSynName :: PatSyn -> Name
patSynName = psName
-- | Should the 'PatSyn' be presented infix?
patSynIsInfix :: PatSyn -> Bool
patSynIsInfix = psInfix
-- | Arity of the pattern synonym
patSynArity :: PatSyn -> Arity
patSynArity = psArity
patSynArgs :: PatSyn -> [Type]
patSynArgs = psArgs
patSynFieldLabels :: PatSyn -> [FieldLabel]
patSynFieldLabels = psFieldLabels
-- | Extract the type for any given labelled field of the 'DataCon'
patSynFieldType :: PatSyn -> FieldLabelString -> Type
patSynFieldType ps label
= case find ((== label) . flLabel . fst) (psFieldLabels ps `zip` psArgs ps) of
Just (_, ty) -> ty
Nothing -> pprPanic "dataConFieldType" (ppr ps <+> ppr label)
patSynUnivTyVarBinders :: PatSyn -> [TyVarBinder]
patSynUnivTyVarBinders = psUnivTyVars
patSynExTyVars :: PatSyn -> [TyVar]
patSynExTyVars ps = binderVars (psExTyVars ps)
patSynExTyVarBinders :: PatSyn -> [TyVarBinder]
patSynExTyVarBinders = psExTyVars
patSynSig :: PatSyn -> ([TyVar], ThetaType, [TyVar], ThetaType, [Type], Type)
patSynSig (MkPatSyn { psUnivTyVars = univ_tvs, psExTyVars = ex_tvs
, psProvTheta = prov, psReqTheta = req
, psArgs = arg_tys, psResultTy = res_ty })
= (binderVars univ_tvs, req, binderVars ex_tvs, prov, arg_tys, res_ty)
patSynMatcher :: PatSyn -> (Id,Bool)
patSynMatcher = psMatcher
patSynBuilder :: PatSyn -> Maybe (Id, Bool)
patSynBuilder = psBuilder
updatePatSynIds :: (Id -> Id) -> PatSyn -> PatSyn
updatePatSynIds tidy_fn ps@(MkPatSyn { psMatcher = matcher, psBuilder = builder })
= ps { psMatcher = tidy_pr matcher, psBuilder = fmap tidy_pr builder }
where
tidy_pr (id, dummy) = (tidy_fn id, dummy)
patSynInstArgTys :: PatSyn -> [Type] -> [Type]
-- Return the types of the argument patterns
-- e.g. data D a = forall b. MkD a b (b->a)
-- pattern P f x y = MkD (x,True) y f
-- D :: forall a. forall b. a -> b -> (b->a) -> D a
P : : forall c. forall b. ( b->(c , ) ) - > c - > b - > P c
patSynInstArgTys P [ Int , bb ] = [ bb->(Int , ) , Int , bb ]
NB : the inst_tys should be both universal and existential
patSynInstArgTys (MkPatSyn { psName = name, psUnivTyVars = univ_tvs
, psExTyVars = ex_tvs, psArgs = arg_tys })
inst_tys
= ASSERT2( tyvars `equalLength` inst_tys
, text "patSynInstArgTys" <+> ppr name $$ ppr tyvars $$ ppr inst_tys )
map (substTyWith tyvars inst_tys) arg_tys
where
tyvars = binderVars (univ_tvs ++ ex_tvs)
patSynInstResTy :: PatSyn -> [Type] -> Type
-- Return the type of whole pattern
-- E.g. pattern P x y = Just (x,x,y)
-- P :: a -> b -> Just (a,a,b)
-- (patSynInstResTy P [Int,Bool] = Maybe (Int,Int,Bool)
NB : unlike patSynInstArgTys , the inst_tys should be just the * universal *
patSynInstResTy (MkPatSyn { psName = name, psUnivTyVars = univ_tvs
, psResultTy = res_ty })
inst_tys
= ASSERT2( univ_tvs `equalLength` inst_tys
, text "patSynInstResTy" <+> ppr name $$ ppr univ_tvs $$ ppr inst_tys )
substTyWith (binderVars univ_tvs) inst_tys res_ty
-- | Print the type of a pattern synonym. The foralls are printed explicitly
pprPatSynType :: PatSyn -> SDoc
pprPatSynType (MkPatSyn { psUnivTyVars = univ_tvs, psReqTheta = req_theta
, psExTyVars = ex_tvs, psProvTheta = prov_theta
, psArgs = orig_args, psResultTy = orig_res_ty })
= sep [ pprForAll univ_tvs
, pprThetaArrowTy req_theta
, ppWhen insert_empty_ctxt $ parens empty <+> darrow
, pprType sigma_ty ]
where
sigma_ty = mkForAllTys ex_tvs $
mkInvisFunTys prov_theta $
mkVisFunTys orig_args orig_res_ty
insert_empty_ctxt = null req_theta && not (null prov_theta && null ex_tvs)
| null | https://raw.githubusercontent.com/monadfix/ormolu-live/d8ae72ef168b98a8d179d642f70352c88b3ac226/ghc-lib-parser-8.10.1.20200412/compiler/basicTypes/PatSyn.hs | haskell | * Main data types
** Type deconstruction
************************************************************************
* *
\subsection{Pattern synonyms}
* *
************************************************************************
| Pattern Synonym
See Note [Pattern synonym representation]
See Note [Pattern synonym signature contexts]
Cached from Name
== length psArgs
True <=> declared infix
List of fields for a
record pattern synonym
record pat syn or same length as
psArgs
Required dictionaries (may mention psUnivTyVars)
Provided dictionaries (may mention psUnivTyVars or psExTyVars)
Result type
Mentions only psUnivTyVars
See Note [Pattern synonym result type]
See Note [Matchers and builders for pattern synonyms]
Matcher function.
and type is
req_theta
=> res_ty
-> (forall ex_tvs. Void# -> r)
-> (Void# -> r)
-> r
Otherwise type is
req_theta
=> res_ty
-> (forall ex_tvs. prov_theta => arg_tys -> r)
-> (Void# -> r)
-> r
Nothing => uni-directional pattern synonym
Just (builder, is_unlifted) => bi-directional
Builder function, of type
forall univ_tvs, ex_tvs. (req_theta, prov_theta)
=> arg_tys -> res_ty
See Note [Builder for pattern synonyms with unboxed type]
don't traverse?
************************************************************************
* *
\subsection{Construction}
* *
************************************************************************
| Build a new pattern synonym
^ Is the pattern synonym declared infix?
^ Original arguments
^ Original result type
^ Name of matcher
^ Name of builder
^ Names of fields for
a record pattern synonym
| The 'Name' of the 'PatSyn', giving it a unique, rooted identification
| Should the 'PatSyn' be presented infix?
| Arity of the pattern synonym
| Extract the type for any given labelled field of the 'DataCon'
Return the types of the argument patterns
e.g. data D a = forall b. MkD a b (b->a)
pattern P f x y = MkD (x,True) y f
D :: forall a. forall b. a -> b -> (b->a) -> D a
Return the type of whole pattern
E.g. pattern P x y = Just (x,x,y)
P :: a -> b -> Just (a,a,b)
(patSynInstResTy P [Int,Bool] = Maybe (Int,Int,Bool)
| Print the type of a pattern synonym. The foralls are printed explicitly |
( c ) The University of Glasgow 2006
( c ) The GRASP / AQUA Project , Glasgow University , 1998
\section[PatSyn]{@PatSyn@ : Pattern synonyms }
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1998
\section[PatSyn]{@PatSyn@: Pattern synonyms}
-}
# LANGUAGE CPP #
module PatSyn (
PatSyn, mkPatSyn,
patSynName, patSynArity, patSynIsInfix,
patSynArgs,
patSynMatcher, patSynBuilder,
patSynUnivTyVarBinders, patSynExTyVars, patSynExTyVarBinders, patSynSig,
patSynInstArgTys, patSynInstResTy, patSynFieldLabels,
patSynFieldType,
updatePatSynIds, pprPatSynType
) where
#include "HsVersions2.h"
import GhcPrelude
import Type
import TyCoPpr
import Name
import Outputable
import Unique
import Util
import BasicTypes
import Var
import FieldLabel
import qualified Data.Data as Data
import Data.Function
import Data.List (find)
data PatSyn
= MkPatSyn {
psName :: Name,
psArgs :: [Type],
INVARIANT : either empty if no
Universally - quantified type variables
psUnivTyVars :: [TyVarBinder],
psReqTheta :: ThetaType,
Existentially - quantified type vars
psExTyVars :: [TyVarBinder],
psProvTheta :: ThetaType,
psMatcher :: (Id, Bool),
If is True then prov_theta and arg_tys are empty
forall ( p : : RuntimeRep ) ( r : : TYPE p ) univ_tvs .
forall ( p : : RuntimeRep ) ( r : : TYPE r ) univ_tvs .
psBuilder :: Maybe (Id, Bool)
}
Note [ Pattern synonym signature contexts ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a pattern synonym signature we write
pattern P : : req = > prov = > t1 - > ... tn - > res_ty
Note that the " required " context comes first , then the " provided "
context . Moreover , the " required " context must not mention
existentially - bound type variables ; that is , ones not mentioned in
res_ty . See lots of discussion in # 10928 .
If there is no " provided " context , you can omit it ; but you
ca n't omit the " required " part ( unless you omit both ) .
Example 1 :
pattern P1 : : ( a , a ) = > b - > Maybe ( a , b )
pattern P1 x = Just ( 3,x )
We require ( a , a ) to match the 3 ; there is no provided
context .
Example 2 :
data T2 where
MkT2 : : ( a , a ) = > a - > a - > T2
pattern P2 : : ( ) = > ( a , a ) = > a - > T2
pattern P2 x = MkT2 3 x
When we match against P2 we get a dictionary provided .
We can use that to check the match against 3 .
Example 3 :
pattern P3 : : Eq a = > a - > b - > T3 b
This signature is illegal because the ( Eq a ) is a required
constraint , but it mentions the existentially - bound variable ' a ' .
You can see it 's existential because it does n't appear in the
result type ( T3 b ) .
Note [ Pattern synonym result type ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data T a b = MkT b a
pattern P : : a - > T [ a ] Bool
pattern P x = MkT True [ x ]
P 's psResultTy is ( T a Bool ) , and it really only matches values of
type ( T [ a ] Bool ) . For example , this is ill - typed
f : : T p q - > String
f ( P x ) = " urk "
This is different to the situation with GADTs :
data S a where
MkS : : Int - > S Bool
Now MkS ( and pattern synonyms coming from MkS ) can match a
value of type ( S a ) , not just ( S Bool ) ; we get type refinement .
That in turn means that if you have a pattern
P x : : T [ ty ]
it 's not entirely straightforward to work out the instantiation of
P 's universal tyvars . You have to /match/
the type of the pattern , ( T [ ty ] )
against
the psResultTy for the pattern synonym , T [ a ] Bool
to get the instantiation a : = ty .
This is very unlike DataCons , where univ tyvars match 1 - 1 the
arguments of the .
Side note : I ( SG ) get the impression that instantiated return types should
generate a * required * constraint for pattern synonyms , rather than a * provided *
constraint like it 's the case for GADTs . For example , I 'd expect these
declarations to have identical semantics :
pattern : : Maybe Int
pattern = Just 42
pattern Just'42 : : ( a ~ Int ) = > Maybe a
pattern Just'42 = Just 42
The latter generates the proper required constraint , the former does not .
Also rather different to GADTs is the fact that does n't have any
universally quantified type variables , whereas Just'42 or MkS above has .
Note [ Pattern synonym representation ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following pattern synonym declaration
pattern P x = MkT [ x ] ( Just 42 )
where
data T a where
MkT : : ( Show a , Ord b ) = > [ b ] - > a - > T a
so pattern P has type
b - > T ( Maybe t )
with the following typeclass constraints :
requires : ( Eq t , t )
provides : ( Show ( Maybe t ) , b )
In this case , the fields of MkPatSyn will be set as follows :
psArgs = [ b ]
psArity = 1
psInfix = False
psUnivTyVars = [ t ]
psExTyVars = [ b ]
psProvTheta = ( Show ( Maybe t ) , b )
psReqTheta = ( Eq t , t )
psResultTy = T ( Maybe t )
Note [ Matchers and builders for pattern synonyms ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For each pattern synonym P , we generate
* a " matcher " function , used to uses of P in patterns ,
which implements pattern matching
* A " builder " function ( for bidirectional pattern synonyms only ) ,
used to uses of P in expressions , which constructs P - values .
For the above example , the matcher function has type :
$ mP : : forall ( r : : ? ) t. ( Eq t , t )
= > T ( Maybe t )
- > ( forall b. ( Show ( Maybe t ) , b ) = > b - > r )
- > ( Void # - > r )
- > r
with the following implementation :
$ mP @r @t $ dEq $ dNum scrut cont fail
= case scrut of
MkT @b [ x ] ( Just 42 ) - > cont @b $ dShow $ dOrd x
_ - > fail Void #
Notice that the return type ' r ' has an open kind , so that it can
be instantiated by an unboxed type ; for example where we see
f ( P x ) = 3 #
The extra Void # argument for the failure continuation is needed so that
it is lazy even when the result type is unboxed .
For the same reason , if the pattern has no arguments , an extra Void #
argument is added to the success continuation as well .
For * bidirectional * pattern synonyms , we also generate a " builder "
function which implements the pattern synonym in an expression
context . For our running example , it will be :
$ bP : : forall t b. ( Eq t , t , Show ( Maybe t ) , b )
= > b - > T ( Maybe t )
$ bP x = MkT [ x ] ( Just 42 )
NB : the existential / universal and required / provided split does not
apply to the builder since you are only putting stuff in , not getting
stuff out .
Injectivity of bidirectional pattern synonyms is checked in
tcPatToExpr which walks the pattern and returns its corresponding
expression when available .
Note [ Builder for pattern synonyms with unboxed type ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For bidirectional pattern synonyms that have no arguments and have an
unboxed type , we add an extra Void # argument to the builder , else it
would be a top - level declaration with an unboxed type .
pattern P = 0 #
$ bP : : Void # - > Int #
$ bP _ = 0 #
This means that when typechecking an occurrence of P in an expression ,
we must remember that the builder has this void argument . This is
done by TcPatSyn.patSynBuilderOcc .
Note [ Pattern synonyms and the data type Type ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The type of a pattern synonym is of the form ( See Note
[ Pattern synonym signatures ] in ):
forall univ_tvs . req = > forall ex_tvs . prov = > ...
We can not in general represent this by a value of type Type :
- if ex_tvs is empty , then req and prov can not be distinguished from
each other
- if req is empty , then univ_tvs and ex_tvs can not be distinguished
from each other , and moreover , prov is seen as the " required " context
( as it is the only context )
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
\subsection{Instances }
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a pattern synonym signature we write
pattern P :: req => prov => t1 -> ... tn -> res_ty
Note that the "required" context comes first, then the "provided"
context. Moreover, the "required" context must not mention
existentially-bound type variables; that is, ones not mentioned in
res_ty. See lots of discussion in #10928.
If there is no "provided" context, you can omit it; but you
can't omit the "required" part (unless you omit both).
Example 1:
pattern P1 :: (Num a, Eq a) => b -> Maybe (a,b)
pattern P1 x = Just (3,x)
We require (Num a, Eq a) to match the 3; there is no provided
context.
Example 2:
data T2 where
MkT2 :: (Num a, Eq a) => a -> a -> T2
pattern P2 :: () => (Num a, Eq a) => a -> T2
pattern P2 x = MkT2 3 x
When we match against P2 we get a Num dictionary provided.
We can use that to check the match against 3.
Example 3:
pattern P3 :: Eq a => a -> b -> T3 b
This signature is illegal because the (Eq a) is a required
constraint, but it mentions the existentially-bound variable 'a'.
You can see it's existential because it doesn't appear in the
result type (T3 b).
Note [Pattern synonym result type]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data T a b = MkT b a
pattern P :: a -> T [a] Bool
pattern P x = MkT True [x]
P's psResultTy is (T a Bool), and it really only matches values of
type (T [a] Bool). For example, this is ill-typed
f :: T p q -> String
f (P x) = "urk"
This is different to the situation with GADTs:
data S a where
MkS :: Int -> S Bool
Now MkS (and pattern synonyms coming from MkS) can match a
value of type (S a), not just (S Bool); we get type refinement.
That in turn means that if you have a pattern
P x :: T [ty] Bool
it's not entirely straightforward to work out the instantiation of
P's universal tyvars. You have to /match/
the type of the pattern, (T [ty] Bool)
against
the psResultTy for the pattern synonym, T [a] Bool
to get the instantiation a := ty.
This is very unlike DataCons, where univ tyvars match 1-1 the
arguments of the TyCon.
Side note: I (SG) get the impression that instantiated return types should
generate a *required* constraint for pattern synonyms, rather than a *provided*
constraint like it's the case for GADTs. For example, I'd expect these
declarations to have identical semantics:
pattern Just42 :: Maybe Int
pattern Just42 = Just 42
pattern Just'42 :: (a ~ Int) => Maybe a
pattern Just'42 = Just 42
The latter generates the proper required constraint, the former does not.
Also rather different to GADTs is the fact that Just42 doesn't have any
universally quantified type variables, whereas Just'42 or MkS above has.
Note [Pattern synonym representation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following pattern synonym declaration
pattern P x = MkT [x] (Just 42)
where
data T a where
MkT :: (Show a, Ord b) => [b] -> a -> T a
so pattern P has type
b -> T (Maybe t)
with the following typeclass constraints:
requires: (Eq t, Num t)
provides: (Show (Maybe t), Ord b)
In this case, the fields of MkPatSyn will be set as follows:
psArgs = [b]
psArity = 1
psInfix = False
psUnivTyVars = [t]
psExTyVars = [b]
psProvTheta = (Show (Maybe t), Ord b)
psReqTheta = (Eq t, Num t)
psResultTy = T (Maybe t)
Note [Matchers and builders for pattern synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For each pattern synonym P, we generate
* a "matcher" function, used to desugar uses of P in patterns,
which implements pattern matching
* A "builder" function (for bidirectional pattern synonyms only),
used to desugar uses of P in expressions, which constructs P-values.
For the above example, the matcher function has type:
$mP :: forall (r :: ?) t. (Eq t, Num t)
=> T (Maybe t)
-> (forall b. (Show (Maybe t), Ord b) => b -> r)
-> (Void# -> r)
-> r
with the following implementation:
$mP @r @t $dEq $dNum scrut cont fail
= case scrut of
MkT @b $dShow $dOrd [x] (Just 42) -> cont @b $dShow $dOrd x
_ -> fail Void#
Notice that the return type 'r' has an open kind, so that it can
be instantiated by an unboxed type; for example where we see
f (P x) = 3#
The extra Void# argument for the failure continuation is needed so that
it is lazy even when the result type is unboxed.
For the same reason, if the pattern has no arguments, an extra Void#
argument is added to the success continuation as well.
For *bidirectional* pattern synonyms, we also generate a "builder"
function which implements the pattern synonym in an expression
context. For our running example, it will be:
$bP :: forall t b. (Eq t, Num t, Show (Maybe t), Ord b)
=> b -> T (Maybe t)
$bP x = MkT [x] (Just 42)
NB: the existential/universal and required/provided split does not
apply to the builder since you are only putting stuff in, not getting
stuff out.
Injectivity of bidirectional pattern synonyms is checked in
tcPatToExpr which walks the pattern and returns its corresponding
expression when available.
Note [Builder for pattern synonyms with unboxed type]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For bidirectional pattern synonyms that have no arguments and have an
unboxed type, we add an extra Void# argument to the builder, else it
would be a top-level declaration with an unboxed type.
pattern P = 0#
$bP :: Void# -> Int#
$bP _ = 0#
This means that when typechecking an occurrence of P in an expression,
we must remember that the builder has this void argument. This is
done by TcPatSyn.patSynBuilderOcc.
Note [Pattern synonyms and the data type Type]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The type of a pattern synonym is of the form (See Note
[Pattern synonym signatures] in TcSigs):
forall univ_tvs. req => forall ex_tvs. prov => ...
We cannot in general represent this by a value of type Type:
- if ex_tvs is empty, then req and prov cannot be distinguished from
each other
- if req is empty, then univ_tvs and ex_tvs cannot be distinguished
from each other, and moreover, prov is seen as the "required" context
(as it is the only context)
************************************************************************
* *
\subsection{Instances}
* *
************************************************************************
-}
instance Eq PatSyn where
(==) = (==) `on` getUnique
(/=) = (/=) `on` getUnique
instance Uniquable PatSyn where
getUnique = psUnique
instance NamedThing PatSyn where
getName = patSynName
instance Outputable PatSyn where
ppr = ppr . getName
instance OutputableBndr PatSyn where
pprInfixOcc = pprInfixName . getName
pprPrefixOcc = pprPrefixName . getName
instance Data.Data PatSyn where
toConstr _ = abstractConstr "PatSyn"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "PatSyn"
mkPatSyn :: Name
^ Universially - quantified type
variables and required dicts
^ - quantified type
variables and provided dicts
-> PatSyn
NB : The univ and ex vars are both in TyBinder form and TyVar form for
convenience . All the TyBinders should be Named !
mkPatSyn name declared_infix
(univ_tvs, req_theta)
(ex_tvs, prov_theta)
orig_args
orig_res_ty
matcher builder field_labels
= MkPatSyn {psName = name, psUnique = getUnique name,
psUnivTyVars = univ_tvs,
psExTyVars = ex_tvs,
psProvTheta = prov_theta, psReqTheta = req_theta,
psInfix = declared_infix,
psArgs = orig_args,
psArity = length orig_args,
psResultTy = orig_res_ty,
psMatcher = matcher,
psBuilder = builder,
psFieldLabels = field_labels
}
patSynName :: PatSyn -> Name
patSynName = psName
patSynIsInfix :: PatSyn -> Bool
patSynIsInfix = psInfix
patSynArity :: PatSyn -> Arity
patSynArity = psArity
patSynArgs :: PatSyn -> [Type]
patSynArgs = psArgs
patSynFieldLabels :: PatSyn -> [FieldLabel]
patSynFieldLabels = psFieldLabels
patSynFieldType :: PatSyn -> FieldLabelString -> Type
patSynFieldType ps label
= case find ((== label) . flLabel . fst) (psFieldLabels ps `zip` psArgs ps) of
Just (_, ty) -> ty
Nothing -> pprPanic "dataConFieldType" (ppr ps <+> ppr label)
patSynUnivTyVarBinders :: PatSyn -> [TyVarBinder]
patSynUnivTyVarBinders = psUnivTyVars
patSynExTyVars :: PatSyn -> [TyVar]
patSynExTyVars ps = binderVars (psExTyVars ps)
patSynExTyVarBinders :: PatSyn -> [TyVarBinder]
patSynExTyVarBinders = psExTyVars
patSynSig :: PatSyn -> ([TyVar], ThetaType, [TyVar], ThetaType, [Type], Type)
patSynSig (MkPatSyn { psUnivTyVars = univ_tvs, psExTyVars = ex_tvs
, psProvTheta = prov, psReqTheta = req
, psArgs = arg_tys, psResultTy = res_ty })
= (binderVars univ_tvs, req, binderVars ex_tvs, prov, arg_tys, res_ty)
patSynMatcher :: PatSyn -> (Id,Bool)
patSynMatcher = psMatcher
patSynBuilder :: PatSyn -> Maybe (Id, Bool)
patSynBuilder = psBuilder
updatePatSynIds :: (Id -> Id) -> PatSyn -> PatSyn
updatePatSynIds tidy_fn ps@(MkPatSyn { psMatcher = matcher, psBuilder = builder })
= ps { psMatcher = tidy_pr matcher, psBuilder = fmap tidy_pr builder }
where
tidy_pr (id, dummy) = (tidy_fn id, dummy)
patSynInstArgTys :: PatSyn -> [Type] -> [Type]
P : : forall c. forall b. ( b->(c , ) ) - > c - > b - > P c
patSynInstArgTys P [ Int , bb ] = [ bb->(Int , ) , Int , bb ]
NB : the inst_tys should be both universal and existential
patSynInstArgTys (MkPatSyn { psName = name, psUnivTyVars = univ_tvs
, psExTyVars = ex_tvs, psArgs = arg_tys })
inst_tys
= ASSERT2( tyvars `equalLength` inst_tys
, text "patSynInstArgTys" <+> ppr name $$ ppr tyvars $$ ppr inst_tys )
map (substTyWith tyvars inst_tys) arg_tys
where
tyvars = binderVars (univ_tvs ++ ex_tvs)
patSynInstResTy :: PatSyn -> [Type] -> Type
NB : unlike patSynInstArgTys , the inst_tys should be just the * universal *
patSynInstResTy (MkPatSyn { psName = name, psUnivTyVars = univ_tvs
, psResultTy = res_ty })
inst_tys
= ASSERT2( univ_tvs `equalLength` inst_tys
, text "patSynInstResTy" <+> ppr name $$ ppr univ_tvs $$ ppr inst_tys )
substTyWith (binderVars univ_tvs) inst_tys res_ty
pprPatSynType :: PatSyn -> SDoc
pprPatSynType (MkPatSyn { psUnivTyVars = univ_tvs, psReqTheta = req_theta
, psExTyVars = ex_tvs, psProvTheta = prov_theta
, psArgs = orig_args, psResultTy = orig_res_ty })
= sep [ pprForAll univ_tvs
, pprThetaArrowTy req_theta
, ppWhen insert_empty_ctxt $ parens empty <+> darrow
, pprType sigma_ty ]
where
sigma_ty = mkForAllTys ex_tvs $
mkInvisFunTys prov_theta $
mkVisFunTys orig_args orig_res_ty
insert_empty_ctxt = null req_theta && not (null prov_theta && null ex_tvs)
|
eef5b80b2b8db68bdd9afc012d711565eb5b8818b8b86b952324e1d24d6166b6 | puppetlabs/puppetdb | environments_test.clj | (ns puppetlabs.puppetdb.http.environments-test
(:require [puppetlabs.puppetdb.cheshire :as json]
[puppetlabs.puppetdb.scf.storage :as storage]
[puppetlabs.puppetdb.query-eng :as eng]
[clojure.test :refer :all]
[puppetlabs.puppetdb.testutils.db :refer [without-db-var]]
[puppetlabs.puppetdb.testutils.http :refer [deftest-http-app
query-response
query-result]]
[puppetlabs.puppetdb.testutils.nodes :as tu-nodes])
(:import
(java.net HttpURLConnection)))
(def endpoints [[:v4 "/v4/environments"]])
(deftest-http-app test-all-environments
[[_version endpoint] endpoints
method [:get :post]]
(testing "without environments"
(is (empty? (query-result method endpoint))))
(testing "with environments"
(doseq [env ["foo" "bar" "baz"]]
(storage/ensure-environment env))
(without-db-var
(fn []
(is (= #{{:name "foo"}
{:name "bar"}
{:name "baz"}}
(query-result method endpoint)))))
(without-db-var
(fn []
(is (= #{{:name "foo"}
{:name "bar"}
{:name "baz"}}
(set @(future (-> (query-response method endpoint)
:body
slurp
(json/parse-string true))))))))))
(deftest-http-app test-query-environment
[[_version endpoint] endpoints
method [:get :post]]
(testing "without environments"
(without-db-var
(fn []
(is (= 404 (:status (query-response method (str endpoint "/foo"))))))))
(testing "with environments"
(doseq [env ["foo" "bar" "baz"]]
(storage/ensure-environment env))
(without-db-var
(fn []
(is (= {:name "foo"}
(-> (query-response method (str endpoint "/foo"))
:body
(json/parse-string true))))))))
(deftest-http-app environment-queries
[[_version endpoint] endpoints
method [:get :post]]
(tu-nodes/store-example-nodes)
(doseq [env ["foo" "bar" "baz"]]
(storage/ensure-environment env))
(are [query expected] (= expected
(query-result method endpoint query))
["=" "name" "foo"]
#{{:name "foo"}}
["~" "name" "f.*"]
#{{:name "foo"}}
["not" ["=" "name" "foo"]]
#{{:name "DEV"}
{:name "bar"}
{:name "baz"}}
;;;;;;;;;;;;
;; Basic facts subquery examples
;;;;;;;;;;;;
;; In syntax: select_facts
["in" "name"
["extract" "environment"
["select_facts"
["and"
["=" "name" "operatingsystem"]
["=" "value" "Debian"]]]]]
#{{:name "DEV"}}
;; In syntax: from
["in" "name"
["from" "facts"
["extract" "environment"
["and"
["=" "name" "operatingsystem"]
["=" "value" "Debian"]]]]]
#{{:name "DEV"}}
;; Implicit subquery syntax
["subquery" "facts"
["and"
["=" "name" "operatingsystem"]
["=" "value" "Debian"]]]
#{{:name "DEV"}}
;;;;;;;;;;;;;
;; Not-wrapped subquery syntax
;;;;;;;;;;;;;
;; In syntax: select_facts
["not"
["in" "name"
["extract" "environment"
["select_facts"
["and"
["=" "name" "operatingsystem"]
["=" "value" "Debian"]]]]]]
#{{:name "foo"}
{:name "bar"}
{:name "baz"}}
;; In syntax: from
["not"
["in" "name"
["from" "facts"
["extract" "environment"
["and"
["=" "name" "operatingsystem"]
["=" "value" "Debian"]]]]]]
#{{:name "foo"}
{:name "bar"}
{:name "baz"}}
Implict subquery syntax
["not"
["subquery" "facts"
["and"
["=" "name" "operatingsystem"]
["=" "value" "Debian"]]]]
#{{:name "foo"}
{:name "bar"}
{:name "baz"}}
;;;;;;;;
;; Complex subquery example
;;;;;;;;
;; In syntax: select_<entity>
["in" "name"
["extract" "environment"
["select_facts"
["and"
["=" "name" "hostname"]
["in" "value"
["extract" "title"
["select_resources"
["=" "type" "Class"]]]]]]]]
#{{:name "DEV"}}
;; In syntax: from
["in" "name"
["from" "facts"
["extract" "environment"
["and"
["=" "name" "hostname"]
["in" "value"
["from" "resources"
["extract" "title"
["=" "type" "Class"]]]]]]]]
#{{:name "DEV"}}
;; Note: fact/resource comparison isn't a natural
;; join, so there is no implicit syntax here.
)
(testing "failed comparison"
(are [query]
(let [{:keys [_status body]} (query-response method endpoint query)]
(re-find
#"Query operators >,>=,<,<= are not allowed on field name" body))
["<=" "name" "foo"]
[">=" "name" "foo"]
["<" "name" "foo"]
[">" "name" "foo"])))
(def no-parent-endpoints [[:v4 "/v4/environments/foo/events"]
[:v4 "/v4/environments/foo/facts"]
[:v4 "/v4/environments/foo/reports"]
[:v4 "/v4/environments/foo/resources"]])
(deftest-http-app unknown-parent-handling
[[_version endpoint] no-parent-endpoints
method [:get :post]]
(testing "environment-exists? function"
(doseq [env ["bobby" "dave" "charlie"]]
(storage/ensure-environment env))
(is (= true (eng/object-exists? :environment "bobby")))
(is (= true (eng/object-exists? :environment "dave")))
(is (= true (eng/object-exists? :environment "charlie")))
(is (= false (eng/object-exists? :environment "ussr"))))
(let [{:keys [status body]} (query-response method endpoint)]
(is (= HttpURLConnection/HTTP_NOT_FOUND status))
(is (= {:error "No information is known about environment foo"}
(json/parse-string body true)))))
| null | https://raw.githubusercontent.com/puppetlabs/puppetdb/b3d6d10555561657150fa70b6d1e609fba9c0eda/test/puppetlabs/puppetdb/http/environments_test.clj | clojure |
Basic facts subquery examples
In syntax: select_facts
In syntax: from
Implicit subquery syntax
Not-wrapped subquery syntax
In syntax: select_facts
In syntax: from
Complex subquery example
In syntax: select_<entity>
In syntax: from
Note: fact/resource comparison isn't a natural
join, so there is no implicit syntax here. | (ns puppetlabs.puppetdb.http.environments-test
(:require [puppetlabs.puppetdb.cheshire :as json]
[puppetlabs.puppetdb.scf.storage :as storage]
[puppetlabs.puppetdb.query-eng :as eng]
[clojure.test :refer :all]
[puppetlabs.puppetdb.testutils.db :refer [without-db-var]]
[puppetlabs.puppetdb.testutils.http :refer [deftest-http-app
query-response
query-result]]
[puppetlabs.puppetdb.testutils.nodes :as tu-nodes])
(:import
(java.net HttpURLConnection)))
(def endpoints [[:v4 "/v4/environments"]])
(deftest-http-app test-all-environments
[[_version endpoint] endpoints
method [:get :post]]
(testing "without environments"
(is (empty? (query-result method endpoint))))
(testing "with environments"
(doseq [env ["foo" "bar" "baz"]]
(storage/ensure-environment env))
(without-db-var
(fn []
(is (= #{{:name "foo"}
{:name "bar"}
{:name "baz"}}
(query-result method endpoint)))))
(without-db-var
(fn []
(is (= #{{:name "foo"}
{:name "bar"}
{:name "baz"}}
(set @(future (-> (query-response method endpoint)
:body
slurp
(json/parse-string true))))))))))
(deftest-http-app test-query-environment
[[_version endpoint] endpoints
method [:get :post]]
(testing "without environments"
(without-db-var
(fn []
(is (= 404 (:status (query-response method (str endpoint "/foo"))))))))
(testing "with environments"
(doseq [env ["foo" "bar" "baz"]]
(storage/ensure-environment env))
(without-db-var
(fn []
(is (= {:name "foo"}
(-> (query-response method (str endpoint "/foo"))
:body
(json/parse-string true))))))))
(deftest-http-app environment-queries
[[_version endpoint] endpoints
method [:get :post]]
(tu-nodes/store-example-nodes)
(doseq [env ["foo" "bar" "baz"]]
(storage/ensure-environment env))
(are [query expected] (= expected
(query-result method endpoint query))
["=" "name" "foo"]
#{{:name "foo"}}
["~" "name" "f.*"]
#{{:name "foo"}}
["not" ["=" "name" "foo"]]
#{{:name "DEV"}
{:name "bar"}
{:name "baz"}}
["in" "name"
["extract" "environment"
["select_facts"
["and"
["=" "name" "operatingsystem"]
["=" "value" "Debian"]]]]]
#{{:name "DEV"}}
["in" "name"
["from" "facts"
["extract" "environment"
["and"
["=" "name" "operatingsystem"]
["=" "value" "Debian"]]]]]
#{{:name "DEV"}}
["subquery" "facts"
["and"
["=" "name" "operatingsystem"]
["=" "value" "Debian"]]]
#{{:name "DEV"}}
["not"
["in" "name"
["extract" "environment"
["select_facts"
["and"
["=" "name" "operatingsystem"]
["=" "value" "Debian"]]]]]]
#{{:name "foo"}
{:name "bar"}
{:name "baz"}}
["not"
["in" "name"
["from" "facts"
["extract" "environment"
["and"
["=" "name" "operatingsystem"]
["=" "value" "Debian"]]]]]]
#{{:name "foo"}
{:name "bar"}
{:name "baz"}}
Implict subquery syntax
["not"
["subquery" "facts"
["and"
["=" "name" "operatingsystem"]
["=" "value" "Debian"]]]]
#{{:name "foo"}
{:name "bar"}
{:name "baz"}}
["in" "name"
["extract" "environment"
["select_facts"
["and"
["=" "name" "hostname"]
["in" "value"
["extract" "title"
["select_resources"
["=" "type" "Class"]]]]]]]]
#{{:name "DEV"}}
["in" "name"
["from" "facts"
["extract" "environment"
["and"
["=" "name" "hostname"]
["in" "value"
["from" "resources"
["extract" "title"
["=" "type" "Class"]]]]]]]]
#{{:name "DEV"}}
)
(testing "failed comparison"
(are [query]
(let [{:keys [_status body]} (query-response method endpoint query)]
(re-find
#"Query operators >,>=,<,<= are not allowed on field name" body))
["<=" "name" "foo"]
[">=" "name" "foo"]
["<" "name" "foo"]
[">" "name" "foo"])))
(def no-parent-endpoints [[:v4 "/v4/environments/foo/events"]
[:v4 "/v4/environments/foo/facts"]
[:v4 "/v4/environments/foo/reports"]
[:v4 "/v4/environments/foo/resources"]])
(deftest-http-app unknown-parent-handling
[[_version endpoint] no-parent-endpoints
method [:get :post]]
(testing "environment-exists? function"
(doseq [env ["bobby" "dave" "charlie"]]
(storage/ensure-environment env))
(is (= true (eng/object-exists? :environment "bobby")))
(is (= true (eng/object-exists? :environment "dave")))
(is (= true (eng/object-exists? :environment "charlie")))
(is (= false (eng/object-exists? :environment "ussr"))))
(let [{:keys [status body]} (query-response method endpoint)]
(is (= HttpURLConnection/HTTP_NOT_FOUND status))
(is (= {:error "No information is known about environment foo"}
(json/parse-string body true)))))
|
db19e0e6af3e4ebb035030339f7ed47b861363db54455f9b7325c630ebb99478 | wh5a/thih | Env.hs | ------------------------------------------------------------------------------
Copyright : The Hatchet Team ( see file Contributors )
Module : Env
Description : A generic environment that supports mappings
from names to values .
Primary Authors :
Notes : See the file License for license information
Based on FiniteMaps
------------------------------------------------------------------------------
Copyright: The Hatchet Team (see file Contributors)
Module: Env
Description: A generic environment that supports mappings
from names to values.
Primary Authors: Bernie Pope
Notes: See the file License for license information
Based on FiniteMaps
-------------------------------------------------------------------------------}
module Env (Env,
emptyEnv,
unitEnv,
lookupEnv,
addToEnv,
joinEnv,
joinListEnvs,
listToEnv,
envToList,
getNamesFromEnv,
showEnv,
pprintEnv,
mapEnv
) where
import FiniteMaps (FiniteMap,
toListFM,
zeroFM,
unitFM,
lookupFM,
addToFM,
joinFM,
mapFM
)
import AnnotatedHsSyn (AHsName (..))
import Utils (isQualified,
getUnQualName)
import PPrint (PPrint (..),
Doc,
vcat,
(<+>),
($$),
text,
empty)
--------------------------------------------------------------------------------
type Env a = FiniteMap AHsName a
emptyEnv :: Env a
emptyEnv = zeroFM
unitEnv :: (AHsName, a) -> Env a
unitEnv item@(name, val)
= unitFM name val
lookupEnv :: AHsName -> Env a -> Maybe a
lookupEnv name env
= lookupFM env name
addToEnv :: (AHsName, a) -> Env a -> Env a
addToEnv item@(name, val) env
= addToFM name val env
-- this might be expensive!
joinEnv :: Env a -> Env a -> Env a
joinEnv env1 env2
= joinFM env1 env2
joinListEnvs :: [Env a] -> Env a
joinListEnvs = foldr joinEnv emptyEnv
listToEnv :: [(AHsName, a)] -> Env a
listToEnv = foldr addToEnv emptyEnv
envToList :: Env a -> [(AHsName, a)]
envToList env
= toListFM env
just get all the names out of the Env ( added by Bryn )
getNamesFromEnv :: Env a -> [AHsName]
getNamesFromEnv env = map fst (toListFM env)
showEnv :: Show a => Env a -> String
showEnv env
= unlines $ map show $ toListFM env
-- pretty print the environment
pprintEnv :: PPrint a => Env a -> Doc
pprintEnv env
= vcat [((pprint a) <+> (text "::") <+> (pprint b)) | (a, b) <- toListFM env]
-- map a function over the elements of the environment
mapEnv :: (AHsName -> e -> e') -> Env e -> Env e'
mapEnv f map = mapFM f map
--------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/wh5a/thih/dc5cb16ba4e998097135beb0c7b0b416cac7bfae/hatchet/Env.hs | haskell | ----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
------------------------------------------------------------------------------
this might be expensive!
pretty print the environment
map a function over the elements of the environment
------------------------------------------------------------------------------ |
Copyright : The Hatchet Team ( see file Contributors )
Module : Env
Description : A generic environment that supports mappings
from names to values .
Primary Authors :
Notes : See the file License for license information
Based on FiniteMaps
Copyright: The Hatchet Team (see file Contributors)
Module: Env
Description: A generic environment that supports mappings
from names to values.
Primary Authors: Bernie Pope
Notes: See the file License for license information
Based on FiniteMaps
module Env (Env,
emptyEnv,
unitEnv,
lookupEnv,
addToEnv,
joinEnv,
joinListEnvs,
listToEnv,
envToList,
getNamesFromEnv,
showEnv,
pprintEnv,
mapEnv
) where
import FiniteMaps (FiniteMap,
toListFM,
zeroFM,
unitFM,
lookupFM,
addToFM,
joinFM,
mapFM
)
import AnnotatedHsSyn (AHsName (..))
import Utils (isQualified,
getUnQualName)
import PPrint (PPrint (..),
Doc,
vcat,
(<+>),
($$),
text,
empty)
type Env a = FiniteMap AHsName a
emptyEnv :: Env a
emptyEnv = zeroFM
unitEnv :: (AHsName, a) -> Env a
unitEnv item@(name, val)
= unitFM name val
lookupEnv :: AHsName -> Env a -> Maybe a
lookupEnv name env
= lookupFM env name
addToEnv :: (AHsName, a) -> Env a -> Env a
addToEnv item@(name, val) env
= addToFM name val env
joinEnv :: Env a -> Env a -> Env a
joinEnv env1 env2
= joinFM env1 env2
joinListEnvs :: [Env a] -> Env a
joinListEnvs = foldr joinEnv emptyEnv
listToEnv :: [(AHsName, a)] -> Env a
listToEnv = foldr addToEnv emptyEnv
envToList :: Env a -> [(AHsName, a)]
envToList env
= toListFM env
just get all the names out of the Env ( added by Bryn )
getNamesFromEnv :: Env a -> [AHsName]
getNamesFromEnv env = map fst (toListFM env)
showEnv :: Show a => Env a -> String
showEnv env
= unlines $ map show $ toListFM env
pprintEnv :: PPrint a => Env a -> Doc
pprintEnv env
= vcat [((pprint a) <+> (text "::") <+> (pprint b)) | (a, b) <- toListFM env]
mapEnv :: (AHsName -> e -> e') -> Env e -> Env e'
mapEnv f map = mapFM f map
|
4ca7b184b7b6dd0abe73b32862e7509e2b02816a51cafa92b5a5bd96ce7a4d63 | well-typed-lightbulbs/ocaml-esp32 | pr4466.ml | (* TEST
* hassysthreads
include systhreads
** native
compare_programs = "false"
*)
open Printf
Regression test for PR#4466 : select timeout with simultaneous read
and write on socket in Windows .
and write on socket in Windows. *)
(* Scenario:
- thread [server] implements a simple 'echo' server on a socket
- thread [reader] selects then reads from a socket connected to
the echo server and copies to standard output
- main program executes [writer], which writes to the same socket
(the one connected to the echo server)
*)
let server sock =
let (s, _) = Unix.accept sock in
let buf = Bytes.make 1024 '>' in
for i = 1 to 3 do
let n = Unix.recv s buf 2 (Bytes.length buf - 2) [] in
if n = 0 then begin
Unix.close s; Thread.exit ()
end else begin
ignore (Unix.send s buf 0 (n + 2) [])
end
done
let reader s =
let buf = Bytes.make 16 ' ' in
match Unix.select [s] [] [] 10.0 with
| (_::_, _, _) ->
printf "Selected\n%!";
let n = Unix.recv s buf 0 (Bytes.length buf) [] in
printf "Data read: %s\n%!" (Bytes.sub_string buf 0 n)
| ([], _, _) ->
printf "TIMEOUT\n%!"
let writer s msg =
ignore (Unix.send_substring s msg 0 (String.length msg) [])
let _ =
let addr = Unix.ADDR_INET(Unix.inet_addr_loopback, 0) in
let serv =
Unix.socket (Unix.domain_of_sockaddr addr) Unix.SOCK_STREAM 0 in
Unix.setsockopt serv Unix.SO_REUSEADDR true;
Unix.bind serv addr;
let addr = Unix.getsockname serv in
Unix.listen serv 5;
let tserv = Thread.create server serv in
Thread.delay 0.2;
let client =
Unix.socket (Unix.domain_of_sockaddr addr) Unix.SOCK_STREAM 0 in
Unix.connect client addr;
(* Send before select & read *)
writer client "1111";
let a = Thread.create reader client in
Thread.delay 0.1;
Thread.join a;
(* Select then send *)
let a = Thread.create reader client in
Thread.delay 0.1;
writer client "2222";
Thread.join a;
(* Select then send again *)
let a = Thread.create reader client in
Thread.delay 0.1;
writer client "3333";
Thread.join a;
(* Cleanup before exiting *)
Thread.join tserv
| null | https://raw.githubusercontent.com/well-typed-lightbulbs/ocaml-esp32/c24fcbfbee0e3aa6bb71c9b467c60c6bac326cc7/testsuite/tests/lib-threads/pr4466.ml | ocaml | TEST
* hassysthreads
include systhreads
** native
compare_programs = "false"
Scenario:
- thread [server] implements a simple 'echo' server on a socket
- thread [reader] selects then reads from a socket connected to
the echo server and copies to standard output
- main program executes [writer], which writes to the same socket
(the one connected to the echo server)
Send before select & read
Select then send
Select then send again
Cleanup before exiting |
open Printf
Regression test for PR#4466 : select timeout with simultaneous read
and write on socket in Windows .
and write on socket in Windows. *)
let server sock =
let (s, _) = Unix.accept sock in
let buf = Bytes.make 1024 '>' in
for i = 1 to 3 do
let n = Unix.recv s buf 2 (Bytes.length buf - 2) [] in
if n = 0 then begin
Unix.close s; Thread.exit ()
end else begin
ignore (Unix.send s buf 0 (n + 2) [])
end
done
let reader s =
let buf = Bytes.make 16 ' ' in
match Unix.select [s] [] [] 10.0 with
| (_::_, _, _) ->
printf "Selected\n%!";
let n = Unix.recv s buf 0 (Bytes.length buf) [] in
printf "Data read: %s\n%!" (Bytes.sub_string buf 0 n)
| ([], _, _) ->
printf "TIMEOUT\n%!"
let writer s msg =
ignore (Unix.send_substring s msg 0 (String.length msg) [])
let _ =
let addr = Unix.ADDR_INET(Unix.inet_addr_loopback, 0) in
let serv =
Unix.socket (Unix.domain_of_sockaddr addr) Unix.SOCK_STREAM 0 in
Unix.setsockopt serv Unix.SO_REUSEADDR true;
Unix.bind serv addr;
let addr = Unix.getsockname serv in
Unix.listen serv 5;
let tserv = Thread.create server serv in
Thread.delay 0.2;
let client =
Unix.socket (Unix.domain_of_sockaddr addr) Unix.SOCK_STREAM 0 in
Unix.connect client addr;
writer client "1111";
let a = Thread.create reader client in
Thread.delay 0.1;
Thread.join a;
let a = Thread.create reader client in
Thread.delay 0.1;
writer client "2222";
Thread.join a;
let a = Thread.create reader client in
Thread.delay 0.1;
writer client "3333";
Thread.join a;
Thread.join tserv
|
b9457353b83fd7c2eafe22ae7cb1cb10f76cd494a705dc7dd222c9dd6f91dcfa | cfpb/qu | user.clj | (ns user)
(def namespaces (atom {}))
(alter-var-root (var clojure.core/load-lib)
(fn [f]
(fn [prefix lib & options]
(let [start (. java.lang.System (nanoTime))
return (apply f prefix lib options)
end (. java.lang.System (nanoTime))
ms (/ (double (- end start)) 1000000.0)
lib-name (if prefix
(keyword (str prefix "." lib))
(keyword lib))]
(swap! namespaces
update-in [lib-name] (fnil max ms) ms)
return))))
(defn ns-times
[]
(reverse (sort-by second @namespaces)))
(require '[alembic.still :refer [distill]]
'[clojure.string :as str]
'[clojure.pprint :refer [pprint]]
'[clojure.repl :refer :all]
'[clojure.tools.namespace.repl :refer [refresh refresh-all set-refresh-dirs]]
'[com.stuartsierra.component :as component]
'[qu.main :as main]
'[qu.app :refer [new-qu-system]]
'[qu.app.options :refer [inflate-options]]
'[qu.util :refer :all]
'[qu.loader :as loader :refer [load-dataset]])
(set-refresh-dirs "src/" "dev/")
(def system (atom nil))
(defn init
([] (init {}))
([options]
(reset! system (new-qu-system (combine (main/default-options) options)))))
(defn start
[]
(swap! system component/start)
(swap! system assoc :running true))
(defn stop
[]
(swap! system component/stop)
(swap! system assoc :running false))
(defn go
([] (go {}))
([options]
(init options)
(start)))
(defn reset
[]
(stop)
(refresh :after 'user/go))
(defn load-sample-data
[]
(if (:running @system)
(load-dataset "county_taxes")
(println "System not running")))
| null | https://raw.githubusercontent.com/cfpb/qu/f460d9ab2f05ac22f6d68a98a9641daf0f7c7ba4/dev/user.clj | clojure | (ns user)
(def namespaces (atom {}))
(alter-var-root (var clojure.core/load-lib)
(fn [f]
(fn [prefix lib & options]
(let [start (. java.lang.System (nanoTime))
return (apply f prefix lib options)
end (. java.lang.System (nanoTime))
ms (/ (double (- end start)) 1000000.0)
lib-name (if prefix
(keyword (str prefix "." lib))
(keyword lib))]
(swap! namespaces
update-in [lib-name] (fnil max ms) ms)
return))))
(defn ns-times
[]
(reverse (sort-by second @namespaces)))
(require '[alembic.still :refer [distill]]
'[clojure.string :as str]
'[clojure.pprint :refer [pprint]]
'[clojure.repl :refer :all]
'[clojure.tools.namespace.repl :refer [refresh refresh-all set-refresh-dirs]]
'[com.stuartsierra.component :as component]
'[qu.main :as main]
'[qu.app :refer [new-qu-system]]
'[qu.app.options :refer [inflate-options]]
'[qu.util :refer :all]
'[qu.loader :as loader :refer [load-dataset]])
(set-refresh-dirs "src/" "dev/")
(def system (atom nil))
(defn init
([] (init {}))
([options]
(reset! system (new-qu-system (combine (main/default-options) options)))))
(defn start
[]
(swap! system component/start)
(swap! system assoc :running true))
(defn stop
[]
(swap! system component/stop)
(swap! system assoc :running false))
(defn go
([] (go {}))
([options]
(init options)
(start)))
(defn reset
[]
(stop)
(refresh :after 'user/go))
(defn load-sample-data
[]
(if (:running @system)
(load-dataset "county_taxes")
(println "System not running")))
| |
4f265b15774f6da924b5d45df3249c5f31e4d5b596625796ccfd1374272d4730 | haskell-suite/haskell-names | PatternSynonyms.hs | {-# LANGUAGE PatternSynonyms, NamedFieldPuns #-}
module PatternSynonyms where
data Type = App String [Type]
pattern Arrow t1 t2 = App "->" [t1, t2]
pattern Int = App "Int" []
pattern Maybe t = App "Maybe" [t]
collectArgs :: Type -> [Type]
collectArgs (Arrow t1 t2) = t1 : collectArgs t2
collectArgs _ = []
isInt :: Type -> Bool
isInt Int = True
isInt _ = False
isIntEndo :: Type -> Bool
isIntEndo (Arrow Int Int) = True
isIntEndo _ = False
intEndo :: Type
intEndo = Arrow Int Int
pattern Head x <- x:xs
pattern HeadC x <- x:xs where
HeadC x = [x]
pattern Point :: Int -> Int -> (Int, Int)
pattern Point{x, y} = (x, y)
zero = Point 0 0
zero' = Point { x = 0, y = 0}
isZero (Point 0 0) = True
isZero' (Point { x = 0, y = 0 }) = True
getX (Point {x}) = x
setX = (0, 0) { x = 1 } == (1,0)
getX' = x (0,0) == 0
| null | https://raw.githubusercontent.com/haskell-suite/haskell-names/795d717541484dbe456342a510ac8e712e1f16e4/tests/annotations/PatternSynonyms.hs | haskell | # LANGUAGE PatternSynonyms, NamedFieldPuns # |
module PatternSynonyms where
data Type = App String [Type]
pattern Arrow t1 t2 = App "->" [t1, t2]
pattern Int = App "Int" []
pattern Maybe t = App "Maybe" [t]
collectArgs :: Type -> [Type]
collectArgs (Arrow t1 t2) = t1 : collectArgs t2
collectArgs _ = []
isInt :: Type -> Bool
isInt Int = True
isInt _ = False
isIntEndo :: Type -> Bool
isIntEndo (Arrow Int Int) = True
isIntEndo _ = False
intEndo :: Type
intEndo = Arrow Int Int
pattern Head x <- x:xs
pattern HeadC x <- x:xs where
HeadC x = [x]
pattern Point :: Int -> Int -> (Int, Int)
pattern Point{x, y} = (x, y)
zero = Point 0 0
zero' = Point { x = 0, y = 0}
isZero (Point 0 0) = True
isZero' (Point { x = 0, y = 0 }) = True
getX (Point {x}) = x
setX = (0, 0) { x = 1 } == (1,0)
getX' = x (0,0) == 0
|
b19975f1937875c240de1c97fcaa0c99f176e440a0dced9699de710efc143214 | clojure-lsp/clojure-lsp | restructure_keys_test.clj | (ns clojure-lsp.feature.restructure-keys-test
(:require
[clojure-lsp.feature.restructure-keys :as f.restructure-keys]
[clojure-lsp.test-helper :as h]
[clojure.test :refer [deftest is testing]]))
(h/reset-components-before-test)
(defn ^:private can-restructure-zloc? [zloc]
(f.restructure-keys/can-restructure-keys? zloc h/default-uri (h/db)))
(defn ^:private restructure-zloc [zloc]
(f.restructure-keys/restructure-keys zloc h/default-uri (h/db)))
(defn ^:private as-string [changes]
(h/changes->code changes (h/db)))
(defmacro ^:private assert-cannot-restructure [code]
`(let [zloc# (h/load-code-and-zloc ~code)]
(is (not (can-restructure-zloc? zloc#))
(as-string (restructure-zloc zloc#)))))
(defmacro ^:private assert-restructures [restructured-code original-code]
`(let [original# ~original-code
zloc# (h/load-code-and-zloc original#)
expected# ~restructured-code]
(is (can-restructure-zloc? zloc#) original#)
(is (= expected#
(as-string (restructure-zloc zloc#)))
original#)))
(defmacro assert-restructures-variations [restructured-code & original-codes]
`(do ~@(map (fn [original-code]
`(assert-restructures ~restructured-code ~original-code))
original-codes)))
(deftest should-not-restructure
(assert-cannot-restructure "{|:a 1}")
(assert-cannot-restructure "{:a |1}")
(assert-cannot-restructure "(|def foo)")
(assert-cannot-restructure "(def |foo)")
(assert-cannot-restructure "|")
(assert-cannot-restructure "|;; comment")
(assert-cannot-restructure "(let [loc' loc] (tangent |loc'))")
(assert-cannot-restructure "|{:a 1}"))
(deftest should-restructure-local
(testing "restructuring keys"
(assert-restructures-variations
(h/code "(defn foo [element] (:a element))")
(h/code "(defn foo [|{:keys [a]}] a)")
(h/code "(defn foo [|{:keys [:a]}] a)"))
(assert-restructures-variations
(h/code "(defn foo [element] (:prefix/a element))")
(h/code "(defn foo [|{:keys [prefix/a]}] a)")
(h/code "(defn foo [|{:keys [:prefix/a]}] a)")
(h/code "(defn foo [|{:prefix/keys [a]}] a)")
(h/code "(defn foo [|{:prefix/keys [:a]}] a)")
(h/code "(defn foo [|#:prefix{:keys [a]}] a)")
(h/code "(defn foo [|#:prefix{:keys [:a]}] a)"))
(assert-restructures-variations
(h/code "(defn foo [element] (::prefix/a element))")
(h/code "(defn foo [|{:keys [::prefix/a]}] a)")
(h/code "(defn foo [|{::prefix/keys [a]}] a)")
(h/code "(defn foo [|{::prefix/keys [:a]}] a)")
(h/code "(defn foo [|#::prefix{:keys [a]}] a)")
(h/code "(defn foo [|#::prefix{:keys [:a]}] a)"))
(assert-restructures-variations
(h/code "(defn foo [element] (::a element))")
(h/code "(defn foo [|{:keys [::a]}] a)")
(h/code "(defn foo [|{::keys [a]}] a)")
(h/code "(defn foo [|{::keys [:a]}] a)")
(h/code "(defn foo [|#::{:keys [a]}] a)")
(h/code "(defn foo [|#::{:keys [:a]}] a)"))
(testing "overriding implied ns"
(assert-restructures-variations
(h/code "(defn foo [element] (:override/a element))")
(h/code "(defn foo [|{:prefix/keys [override/a]}] a)")
(h/code "(defn foo [|{:prefix/keys [:override/a]}] a)")
(h/code "(defn foo [|#:prefix{:keys [override/a]}] a)")
(h/code "(defn foo [|#:prefix{:keys [:override/a]}] a)")
(h/code "(defn foo [|#::prefix{:keys [override/a]}] a)")
(h/code "(defn foo [|#::prefix{:keys [:override/a]}] a)")
(h/code "(defn foo [|#::{:keys [override/a]}] a)")
(h/code "(defn foo [|#::{:keys [:override/a]}] a)"))
(assert-restructures-variations
(h/code "(defn foo [element] (::override/a element))")
(h/code "(defn foo [|{:prefix/keys [::override/a]}] a)")
(h/code "(defn foo [|#:prefix{:keys [::override/a]}] a)")
(h/code "(defn foo [|#::prefix{:keys [::override/a]}] a)")
(h/code "(defn foo [|#::{:keys [::override/a]}] a)"))
(assert-restructures-variations
(h/code "(defn foo [element] (::a element))")
(h/code "(defn foo [|{:prefix/keys [::a]}] a)")
(h/code "(defn foo [|#:prefix{:keys [::a]}] a)")
(h/code "(defn foo [|#:prefix{:keys [::a]}] a)")
(h/code "(defn foo [|#::{:keys [::a]}] a)"))
(assert-restructures-variations
(h/code "(defn foo [element] (:a element))")
(h/code "(defn foo [|#:prefix{:_/keys [a]}] a)")
(h/code "(defn foo [|#:prefix{:_/keys [:a]}] a)")
(h/code "(defn foo [|#::prefix{:_/keys [a]}] a)")
(h/code "(defn foo [|#::prefix{:_/keys [:a]}] a)")
(h/code "(defn foo [|#::{:_/keys [a]}] a)")
(h/code "(defn foo [|#::{:_/keys [:a]}] a)"))))
(testing "restructuring symbols"
(assert-restructures-variations
(h/code "(defn foo [element] ('a element))")
(h/code "(defn foo [|{:syms [a]}] a)")
(h/code "(defn foo [|{:syms [:a]}] a)"))
(assert-restructures-variations
(h/code "(defn foo [element] ('prefix/a element))")
(h/code "(defn foo [|{:syms [prefix/a]}] a)")
(h/code "(defn foo [|{:syms [:prefix/a]}] a)")
(h/code "(defn foo [|{:prefix/syms [a]}] a)")
(h/code "(defn foo [|{:prefix/syms [:a]}] a)")
(h/code "(defn foo [|#:prefix{:syms [a]}] a)")
(h/code "(defn foo [|#:prefix{:syms [:a]}] a)"))
(testing "overriding implied ns"
(assert-restructures-variations
(h/code "(defn foo [element] ('override/a element))")
(h/code "(defn foo [|{:prefix/syms [override/a]}] a)")
(h/code "(defn foo [|{:prefix/syms [:override/a]}] a)")
(h/code "(defn foo [|#:prefix{:syms [override/a]}] a)")
(h/code "(defn foo [|#:prefix{:syms [:override/a]}] a)")
(h/code "(defn foo [|#::prefix{:syms [override/a]}] a)")
(h/code "(defn foo [|#::prefix{:syms [:override/a]}] a)")
(h/code "(defn foo [|#::{:syms [override/a]}] a)")
(h/code "(defn foo [|#::{:syms [:override/a]}] a)"))
(assert-restructures-variations
(h/code "(defn foo [element] ('a element))")
(h/code "(defn foo [|#:prefix{:_/syms [a]}] a)")
(h/code "(defn foo [|#:prefix{:_/syms [:a]}] a)")
(h/code "(defn foo [|#::prefix{:_/syms [a]}] a)")
(h/code "(defn foo [|#::prefix{:_/syms [:a]}] a)")
(h/code "(defn foo [|#::{:_/syms [a]}] a)")
(h/code "(defn foo [|#::{:_/syms [:a]}] a)"))))
(testing "restructures from usage"
(assert-restructures (h/code "(defn foo [element] (:a element))")
(h/code "(defn foo [{:keys [a]}] |a)")))
(testing "restructures elements of different type"
(assert-restructures (h/code "(defn foo [element] (+ ('a element) (:b element)))")
(h/code "(defn foo [|{:syms [a], :keys [b]}] (+ a b))")))
(testing "uses :as for element name"
(assert-restructures (h/code "(defn foo [loc] (:a loc))")
(h/code "(defn foo [|{:keys [a], :as loc}] a)"))
(assert-restructures (h/code "(defn foo [loc] (:prefix/a loc))")
(h/code "(defn foo [|#:prefix{:keys [a], :as loc}] a)"))
(assert-restructures (h/code "(defn foo [loc] (::a loc))")
(h/code "(defn foo [|#::{:keys [a], :as loc}] a)"))
(assert-restructures (h/code "(defn foo [loc] (+ (:a loc) (tangent loc)))")
(h/code "(defn foo [|{:keys [a], :as loc}] (+ a (tangent loc)))")))
(testing "doesn't shadow other locals with element name"
(assert-restructures (h/code "(defn foobar"
" [{element :top-a"
" element-1 :top-b}]"
" (:b element-1) (:a element))")
(h/code "(defn foobar"
" [{element :top-a"
" |{:keys [b]} :top-b}]"
" b (:a element))"))
(assert-restructures (h/code "(defn foobar"
" [{element-1 :top-a"
" element-2 :top-b}]"
" (:b element-2) (:a element-1))")
(h/code "(defn foobar"
" [{element-1 :top-a"
" |{:keys [b]} :top-b}]"
" b (:a element-1))"))
(assert-restructures (h/code "(defn foobar"
" [{element :top-a}]"
" (let [element-1 :top-b]"
" (:b element-1) (:a element)))")
(h/code "(defn foobar"
" [{element :top-a}]"
" (let [|{:keys [b]} :top-b]"
" b (:a element)))")))
(testing "uses :or for default values"
(assert-restructures (h/code "(defn foo [element] (get element :a 1))")
(h/code "(defn foo [|{:keys [a] :or {a 1}}] a)"))
(assert-restructures (h/code "(defn foo [element] (get element :prefix/a 1))")
(h/code "(defn foo [|#:prefix{:keys [a] :or {a 1}}] a)"))
(assert-restructures (h/code "(defn foo [element] (get element ::a 1))")
(h/code "(defn foo [|#::{:keys [a] :or {a 1}}] a)")))
(testing "of named keys that resolve to symbols"
(assert-restructures (h/code "(defn foo [element] (:a element))")
(h/code "(defn foo [|{a :a}] a)")))
(testing "of named keys that resolve to further destructuring"
(assert-restructures (h/code "(defn foo [{[a] :a}] a)")
(h/code "(defn foo [|{[a] :a}] a)"))
(assert-restructures (h/code "(defn foo [{{:keys [a]} :a}] a)")
(h/code "(defn foo [|{{:keys [a]} :a}] a)"))
(assert-restructures (h/code "(defn foo [{[a] :a :as element}] (+ a (:b element)))")
(h/code "(defn foo [|{[a] :a :keys [b]}] (+ a b))"))
(assert-restructures (h/code "(defn foo [#:prefix{[a] :a :as element}] (+ a (:prefix/b element)))")
(h/code "(defn foo [|#:prefix{[a] :a :keys [b]}] (+ a b))"))
(assert-restructures (h/code "(defn foo [{[b] :b :or {b 2} :as element}] (+ (get element :a 1) b))")
(h/code "(defn foo [|{:keys [a], [b] :b, :or {a 1 b 2}}] (+ a b))")))
(testing "of pathological maps"
;; This map establishes a local inside of it, so our heuristics suggest it
;; should be restructurable. Rather than make the heuristics smarter to
;; avoid offering the code action, we're satisified with not breaking the
;; map.
(assert-restructures (h/code "{:a (let [x 1] (inc x))}")
(h/code "|{:a (let [x 1] (inc x))}"))))
| null | https://raw.githubusercontent.com/clojure-lsp/clojure-lsp/a3ff38fca0a52e5b062ffc7e11b15851e9fec02e/lib/test/clojure_lsp/feature/restructure_keys_test.clj | clojure | This map establishes a local inside of it, so our heuristics suggest it
should be restructurable. Rather than make the heuristics smarter to
avoid offering the code action, we're satisified with not breaking the
map. | (ns clojure-lsp.feature.restructure-keys-test
(:require
[clojure-lsp.feature.restructure-keys :as f.restructure-keys]
[clojure-lsp.test-helper :as h]
[clojure.test :refer [deftest is testing]]))
(h/reset-components-before-test)
(defn ^:private can-restructure-zloc? [zloc]
(f.restructure-keys/can-restructure-keys? zloc h/default-uri (h/db)))
(defn ^:private restructure-zloc [zloc]
(f.restructure-keys/restructure-keys zloc h/default-uri (h/db)))
(defn ^:private as-string [changes]
(h/changes->code changes (h/db)))
(defmacro ^:private assert-cannot-restructure [code]
`(let [zloc# (h/load-code-and-zloc ~code)]
(is (not (can-restructure-zloc? zloc#))
(as-string (restructure-zloc zloc#)))))
(defmacro ^:private assert-restructures [restructured-code original-code]
`(let [original# ~original-code
zloc# (h/load-code-and-zloc original#)
expected# ~restructured-code]
(is (can-restructure-zloc? zloc#) original#)
(is (= expected#
(as-string (restructure-zloc zloc#)))
original#)))
(defmacro assert-restructures-variations [restructured-code & original-codes]
`(do ~@(map (fn [original-code]
`(assert-restructures ~restructured-code ~original-code))
original-codes)))
(deftest should-not-restructure
(assert-cannot-restructure "{|:a 1}")
(assert-cannot-restructure "{:a |1}")
(assert-cannot-restructure "(|def foo)")
(assert-cannot-restructure "(def |foo)")
(assert-cannot-restructure "|")
(assert-cannot-restructure "|;; comment")
(assert-cannot-restructure "(let [loc' loc] (tangent |loc'))")
(assert-cannot-restructure "|{:a 1}"))
(deftest should-restructure-local
(testing "restructuring keys"
(assert-restructures-variations
(h/code "(defn foo [element] (:a element))")
(h/code "(defn foo [|{:keys [a]}] a)")
(h/code "(defn foo [|{:keys [:a]}] a)"))
(assert-restructures-variations
(h/code "(defn foo [element] (:prefix/a element))")
(h/code "(defn foo [|{:keys [prefix/a]}] a)")
(h/code "(defn foo [|{:keys [:prefix/a]}] a)")
(h/code "(defn foo [|{:prefix/keys [a]}] a)")
(h/code "(defn foo [|{:prefix/keys [:a]}] a)")
(h/code "(defn foo [|#:prefix{:keys [a]}] a)")
(h/code "(defn foo [|#:prefix{:keys [:a]}] a)"))
(assert-restructures-variations
(h/code "(defn foo [element] (::prefix/a element))")
(h/code "(defn foo [|{:keys [::prefix/a]}] a)")
(h/code "(defn foo [|{::prefix/keys [a]}] a)")
(h/code "(defn foo [|{::prefix/keys [:a]}] a)")
(h/code "(defn foo [|#::prefix{:keys [a]}] a)")
(h/code "(defn foo [|#::prefix{:keys [:a]}] a)"))
(assert-restructures-variations
(h/code "(defn foo [element] (::a element))")
(h/code "(defn foo [|{:keys [::a]}] a)")
(h/code "(defn foo [|{::keys [a]}] a)")
(h/code "(defn foo [|{::keys [:a]}] a)")
(h/code "(defn foo [|#::{:keys [a]}] a)")
(h/code "(defn foo [|#::{:keys [:a]}] a)"))
(testing "overriding implied ns"
(assert-restructures-variations
(h/code "(defn foo [element] (:override/a element))")
(h/code "(defn foo [|{:prefix/keys [override/a]}] a)")
(h/code "(defn foo [|{:prefix/keys [:override/a]}] a)")
(h/code "(defn foo [|#:prefix{:keys [override/a]}] a)")
(h/code "(defn foo [|#:prefix{:keys [:override/a]}] a)")
(h/code "(defn foo [|#::prefix{:keys [override/a]}] a)")
(h/code "(defn foo [|#::prefix{:keys [:override/a]}] a)")
(h/code "(defn foo [|#::{:keys [override/a]}] a)")
(h/code "(defn foo [|#::{:keys [:override/a]}] a)"))
(assert-restructures-variations
(h/code "(defn foo [element] (::override/a element))")
(h/code "(defn foo [|{:prefix/keys [::override/a]}] a)")
(h/code "(defn foo [|#:prefix{:keys [::override/a]}] a)")
(h/code "(defn foo [|#::prefix{:keys [::override/a]}] a)")
(h/code "(defn foo [|#::{:keys [::override/a]}] a)"))
(assert-restructures-variations
(h/code "(defn foo [element] (::a element))")
(h/code "(defn foo [|{:prefix/keys [::a]}] a)")
(h/code "(defn foo [|#:prefix{:keys [::a]}] a)")
(h/code "(defn foo [|#:prefix{:keys [::a]}] a)")
(h/code "(defn foo [|#::{:keys [::a]}] a)"))
(assert-restructures-variations
(h/code "(defn foo [element] (:a element))")
(h/code "(defn foo [|#:prefix{:_/keys [a]}] a)")
(h/code "(defn foo [|#:prefix{:_/keys [:a]}] a)")
(h/code "(defn foo [|#::prefix{:_/keys [a]}] a)")
(h/code "(defn foo [|#::prefix{:_/keys [:a]}] a)")
(h/code "(defn foo [|#::{:_/keys [a]}] a)")
(h/code "(defn foo [|#::{:_/keys [:a]}] a)"))))
(testing "restructuring symbols"
(assert-restructures-variations
(h/code "(defn foo [element] ('a element))")
(h/code "(defn foo [|{:syms [a]}] a)")
(h/code "(defn foo [|{:syms [:a]}] a)"))
(assert-restructures-variations
(h/code "(defn foo [element] ('prefix/a element))")
(h/code "(defn foo [|{:syms [prefix/a]}] a)")
(h/code "(defn foo [|{:syms [:prefix/a]}] a)")
(h/code "(defn foo [|{:prefix/syms [a]}] a)")
(h/code "(defn foo [|{:prefix/syms [:a]}] a)")
(h/code "(defn foo [|#:prefix{:syms [a]}] a)")
(h/code "(defn foo [|#:prefix{:syms [:a]}] a)"))
(testing "overriding implied ns"
(assert-restructures-variations
(h/code "(defn foo [element] ('override/a element))")
(h/code "(defn foo [|{:prefix/syms [override/a]}] a)")
(h/code "(defn foo [|{:prefix/syms [:override/a]}] a)")
(h/code "(defn foo [|#:prefix{:syms [override/a]}] a)")
(h/code "(defn foo [|#:prefix{:syms [:override/a]}] a)")
(h/code "(defn foo [|#::prefix{:syms [override/a]}] a)")
(h/code "(defn foo [|#::prefix{:syms [:override/a]}] a)")
(h/code "(defn foo [|#::{:syms [override/a]}] a)")
(h/code "(defn foo [|#::{:syms [:override/a]}] a)"))
(assert-restructures-variations
(h/code "(defn foo [element] ('a element))")
(h/code "(defn foo [|#:prefix{:_/syms [a]}] a)")
(h/code "(defn foo [|#:prefix{:_/syms [:a]}] a)")
(h/code "(defn foo [|#::prefix{:_/syms [a]}] a)")
(h/code "(defn foo [|#::prefix{:_/syms [:a]}] a)")
(h/code "(defn foo [|#::{:_/syms [a]}] a)")
(h/code "(defn foo [|#::{:_/syms [:a]}] a)"))))
(testing "restructures from usage"
(assert-restructures (h/code "(defn foo [element] (:a element))")
(h/code "(defn foo [{:keys [a]}] |a)")))
(testing "restructures elements of different type"
(assert-restructures (h/code "(defn foo [element] (+ ('a element) (:b element)))")
(h/code "(defn foo [|{:syms [a], :keys [b]}] (+ a b))")))
(testing "uses :as for element name"
(assert-restructures (h/code "(defn foo [loc] (:a loc))")
(h/code "(defn foo [|{:keys [a], :as loc}] a)"))
(assert-restructures (h/code "(defn foo [loc] (:prefix/a loc))")
(h/code "(defn foo [|#:prefix{:keys [a], :as loc}] a)"))
(assert-restructures (h/code "(defn foo [loc] (::a loc))")
(h/code "(defn foo [|#::{:keys [a], :as loc}] a)"))
(assert-restructures (h/code "(defn foo [loc] (+ (:a loc) (tangent loc)))")
(h/code "(defn foo [|{:keys [a], :as loc}] (+ a (tangent loc)))")))
(testing "doesn't shadow other locals with element name"
(assert-restructures (h/code "(defn foobar"
" [{element :top-a"
" element-1 :top-b}]"
" (:b element-1) (:a element))")
(h/code "(defn foobar"
" [{element :top-a"
" |{:keys [b]} :top-b}]"
" b (:a element))"))
(assert-restructures (h/code "(defn foobar"
" [{element-1 :top-a"
" element-2 :top-b}]"
" (:b element-2) (:a element-1))")
(h/code "(defn foobar"
" [{element-1 :top-a"
" |{:keys [b]} :top-b}]"
" b (:a element-1))"))
(assert-restructures (h/code "(defn foobar"
" [{element :top-a}]"
" (let [element-1 :top-b]"
" (:b element-1) (:a element)))")
(h/code "(defn foobar"
" [{element :top-a}]"
" (let [|{:keys [b]} :top-b]"
" b (:a element)))")))
(testing "uses :or for default values"
(assert-restructures (h/code "(defn foo [element] (get element :a 1))")
(h/code "(defn foo [|{:keys [a] :or {a 1}}] a)"))
(assert-restructures (h/code "(defn foo [element] (get element :prefix/a 1))")
(h/code "(defn foo [|#:prefix{:keys [a] :or {a 1}}] a)"))
(assert-restructures (h/code "(defn foo [element] (get element ::a 1))")
(h/code "(defn foo [|#::{:keys [a] :or {a 1}}] a)")))
(testing "of named keys that resolve to symbols"
(assert-restructures (h/code "(defn foo [element] (:a element))")
(h/code "(defn foo [|{a :a}] a)")))
(testing "of named keys that resolve to further destructuring"
(assert-restructures (h/code "(defn foo [{[a] :a}] a)")
(h/code "(defn foo [|{[a] :a}] a)"))
(assert-restructures (h/code "(defn foo [{{:keys [a]} :a}] a)")
(h/code "(defn foo [|{{:keys [a]} :a}] a)"))
(assert-restructures (h/code "(defn foo [{[a] :a :as element}] (+ a (:b element)))")
(h/code "(defn foo [|{[a] :a :keys [b]}] (+ a b))"))
(assert-restructures (h/code "(defn foo [#:prefix{[a] :a :as element}] (+ a (:prefix/b element)))")
(h/code "(defn foo [|#:prefix{[a] :a :keys [b]}] (+ a b))"))
(assert-restructures (h/code "(defn foo [{[b] :b :or {b 2} :as element}] (+ (get element :a 1) b))")
(h/code "(defn foo [|{:keys [a], [b] :b, :or {a 1 b 2}}] (+ a b))")))
(testing "of pathological maps"
(assert-restructures (h/code "{:a (let [x 1] (inc x))}")
(h/code "|{:a (let [x 1] (inc x))}"))))
|
c50733d851ba8f913fa6fe3215f8be555293df18758897b86921d79b8d8c0505 | Noeda/dfterm3 | SubscriptionIO.hs | {-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-}
module Dfterm3.GameSubscription.Internal.SubscriptionIO
( SubscriptionIO(..)
, runSubscriptionIO
, useAcidState )
where
import Dfterm3.GameSubscription.Internal.Types
import Dfterm3.Dfterm3State.Internal.Types
import Data.IORef
import Data.Acid
import Data.Typeable ( Typeable )
import Control.Lens
import Control.Concurrent.MVar
import Control.Monad.State
import Control.Applicative
-- | Actions that require reading or changing values on the disk live in the
` ` monad .
newtype SubscriptionIO a =
SubscriptionIO (StateT ( SubscriptionStateVolatile
, AcidState PersistentStorageState ) IO a)
deriving ( Monad, MonadIO, MonadFix, Applicative, Functor, Typeable )
| Runs ` ` actions .
--
-- These actions can be issued concurrently; however internally there is a lock
-- that prevents actions from running at the same time.
runSubscriptionIO :: Storage -> SubscriptionIO a -> IO a
runSubscriptionIO (Storage (pss, ref)) (SubscriptionIO action) = do
insides' <- readIORef ref
let insides = _gameSubscriptionsVolatile insides'
withMVar (_lock insides) $ \_ -> do
( result, new_state ) <- runStateT action ( insides, pss )
atomicModifyIORef' ref $ \old ->
( set gameSubscriptionsVolatile (fst new_state) old, () )
return result
useAcidState :: SubscriptionIO (AcidState PersistentStorageState)
useAcidState = SubscriptionIO $ use _2
| null | https://raw.githubusercontent.com/Noeda/dfterm3/6b33c9b4712da486bb84356f6c9f48abb8074faf/src/Dfterm3/GameSubscription/Internal/SubscriptionIO.hs | haskell | # LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #
| Actions that require reading or changing values on the disk live in the
These actions can be issued concurrently; however internally there is a lock
that prevents actions from running at the same time. |
module Dfterm3.GameSubscription.Internal.SubscriptionIO
( SubscriptionIO(..)
, runSubscriptionIO
, useAcidState )
where
import Dfterm3.GameSubscription.Internal.Types
import Dfterm3.Dfterm3State.Internal.Types
import Data.IORef
import Data.Acid
import Data.Typeable ( Typeable )
import Control.Lens
import Control.Concurrent.MVar
import Control.Monad.State
import Control.Applicative
` ` monad .
newtype SubscriptionIO a =
SubscriptionIO (StateT ( SubscriptionStateVolatile
, AcidState PersistentStorageState ) IO a)
deriving ( Monad, MonadIO, MonadFix, Applicative, Functor, Typeable )
| Runs ` ` actions .
runSubscriptionIO :: Storage -> SubscriptionIO a -> IO a
runSubscriptionIO (Storage (pss, ref)) (SubscriptionIO action) = do
insides' <- readIORef ref
let insides = _gameSubscriptionsVolatile insides'
withMVar (_lock insides) $ \_ -> do
( result, new_state ) <- runStateT action ( insides, pss )
atomicModifyIORef' ref $ \old ->
( set gameSubscriptionsVolatile (fst new_state) old, () )
return result
useAcidState :: SubscriptionIO (AcidState PersistentStorageState)
useAcidState = SubscriptionIO $ use _2
|
b6fa82325e90f363df41c111f191b0434523b07bf18be5987ff21bf460f3ff9b | ronxin/stolzen | zip.scm | #lang scheme
(require rackunit)
(define (zip . lists)
(define (zip-inner params)
(if (null? (car params))
null
(cons (apply list (map car params))
(zip-inner (map cdr params)))
)
)
(zip-inner lists)
)
(check-equal?
(zip '(1 2 3) '(4 5 6) '(7 8 9))
'((1 4 7) (2 5 8) (3 6 9)))
(provide zip) | null | https://raw.githubusercontent.com/ronxin/stolzen/bb13d0a7deea53b65253bb4b61aaf2abe4467f0d/sicp/chapter3/3.3/zip.scm | scheme | #lang scheme
(require rackunit)
(define (zip . lists)
(define (zip-inner params)
(if (null? (car params))
null
(cons (apply list (map car params))
(zip-inner (map cdr params)))
)
)
(zip-inner lists)
)
(check-equal?
(zip '(1 2 3) '(4 5 6) '(7 8 9))
'((1 4 7) (2 5 8) (3 6 9)))
(provide zip) | |
193600991beea239f205415b36e23ae5265ff075ce6e292372a437a55c160534 | kanaka/bartender | cli.clj | (ns wend.cli
(:require [clojure.tools.cli :refer [parse-opts summarize]]
[clojure.java.io :as io]
[clojure.string :refer [ends-with?]]
[clojure.pprint :refer [pprint]]
[instacheck.core :as icore]
[instacheck.grammar :as igrammar]
[instacheck.reduce :as ireduce]
[html5-css3-ebnf.parse]
[html5-css3-ebnf.html-mangle :as html-mangle]
[mend.parse]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
This extends to add mapping of weights from
;; a parse grammar to a generator grammar.
(defn pr-err
[& args]
(binding [*out* *err*]
(apply println args)
(flush)))
;; Default values to use for generator specific weights in order to
;; create a usable generator weight map from a parsed one. Can be
;; either a default value, a weight to lookup, or a function that is
called with the wtrek .
(def gen-weight-mapping
{
;; Adjust for different elements in :cat
[:head-test :cat 3 :opt nil] #(or (get % [:head :cat 2 :star nil]) 1)
[:head-test :cat 3 :opt 0] [:head :cat 2 :star 0]
[:title-test :cat 1 :star nil] [:title :cat 1 :star nil]
[:title-test :cat 1 :star 0] [:title :cat 1 :star 0]
[:title-test :cat 3 :star nil] [:title :cat 3 :star nil]
[:title-test :cat 3 :star 0] [:title :cat 3 :star 0]
[:body-test :cat 1 :star nil] [:body :cat 1 :star nil]
[:body-test :cat 1 :star 0] [:body :cat 1 :star 0]
[:body-test :cat 4 :star nil] [:body :cat 3 :star nil]
[:body-test :cat 4 :star 0] [:body :cat 3 :star 0]
[:body-test :cat 4 :star 0 :alt 0] [:body :cat 3 :star 0 :alt 0]
[:body-test :cat 4 :star 0 :alt 1] [:body :cat 3 :star 0 :alt 1]
[:css-assignments-test :alt 0] [:css-assignments :alt 0]
[:css-assignments-test :alt 1] [:css-assignments :alt 1]
[:css-assignments-test :alt 1 :cat 1 :star nil]
,,, [:css-assignments :alt 1 :cat 2 :star nil]
[:css-assignments-test :alt 1 :cat 1 :star 0]
,,, [:css-assignments :alt 1 :cat 2 :star 0]
;; No great match, but use the closest elements
[:char-data-test :alt 0] [:content :alt 0]
[:char-data-test :alt 1] [:content :alt 0]
[:char-data-test :alt 2] [:content :alt 1]
[:char-data-test :alt 3] [:content :alt 0]
;; Just use even weights for url types
[:url-test :alt 0] 100
[:url-test :alt 1] 100
[:url-test :alt 2] 100
;; Increase style attr since style and linked stylesheets are not
;; used in gen mode. Sum the :element weights to get a decently
;; large approx magnitude that is inline with existing weights.
[:global-attribute :alt 11]
,,, (fn [tk] (apply + (vals (filter #(= :element (first (key %))) tk))))
})
(defn apply-weight-mapping
[wtrek mapping]
(reduce
(fn [tk [p v]]
(let [w (cond
(number? v) v
(fn? v) (v tk)
:else (get tk v -1))]
(if (> w 0)
(assoc tk p w)
tk)))
wtrek
mapping))
(defn mangle-wtrek
[html-grammar orig-wtrek multiplier]
(let [;; Apply the gen-weight-mapping transforms
wtrek1 (apply-weight-mapping orig-wtrek gen-weight-mapping)
;; Multiply weights by multiplier factor
wtrek2 (into {} (for [[p w] wtrek1]
[p (* w multiplier)]))
;; Make sure that global attributes have weight so that style
;; will appear since style and linked stylesheets are not used
;; in gen mode.
wtrek3 (reduce
(fn [tk [p w]]
(if (and (= 3 (count p))
(= [:element :alt] (take 2 p)))
(let [attr (-> (igrammar/get-in-grammar html-grammar p)
:parsers
(nth 0)
:string
(subs 1)
(str "-attribute")
keyword)]
(assoc tk
[:element :alt (nth p 2) :cat 1 :star 0] 77
[attr :alt 0] 78))
tk))
wtrek2
wtrek2)]
wtrek3))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Command line usage of wend
(defn usage [data]
(str "Usage: parse [OPTS] <FILE>..."
(summarize data)))
(def cli-options
[["-?" "--help" "Show usage"
:default false]
[nil "--debug" "Add debug comments to generated code"]
[nil "--verbose" "Verbose output during execution"]
[nil "--multiplier MULTIPLIER" "Multiply parsed weights by MULTIPLIER"
:default 100]
[nil "--weights-output WEIGHTS-OUTPUT" "Write all resulting frequency weights to WEIGHTS-OUTPUT"]
[nil "--parse-output PARSE-OUTPUT" "Write resulting parse data to PARSE-OUTPUT"]
[nil "--html-ebnf-output HTML-EBNF-OUTPUT" "Write pruned HTML EBNF grammar to HTML-EBNF-OUTPUT"]
[nil "--css-ebnf-output CSS-EBNF-OUTPUT" "Write pruned CSS EBNF grammar to CSS-EBNF-OUTPUT"]])
(defn opt-errors [opts]
(when (:errors opts)
(doall (map pr-err (:errors opts)))
(System/exit 2))
(when (or (-> opts :options :help)
(-> opts :arguments count (= 0)))
(println (:summary opts))
(System/exit 2))
opts)
(defn -main
[& args]
(let [opts (opt-errors (parse-opts args cli-options
:summary-fn usage))
{:keys [multiplier parse-output weights-output
html-ebnf-output css-ebnf-output]} (:options opts)
[& files] (:arguments opts)
_ (pr-err "Loading HTML parser")
html-parser (mend.parse/load-parser-from-grammar :html :parse)
_ (pr-err "Loading CSS parser")
css-parser (mend.parse/load-parser-from-grammar :css :parse)
parse-data (html5-css3-ebnf.parse/parse-files
html-parser css-parser files)
gen-wtrek (mangle-wtrek (:grammar html-parser)
(:full-wtrek parse-data)
multiplier)]
(pr-err (str "Combined and filtered weights: "
(count gen-wtrek)))
(when parse-output
(pr-err (str "Saving parse data to: '" parse-output "'"))
(spit parse-output parse-data))
(when html-ebnf-output
(pr-err (str "Generating pruned HTML EBNF"))
(let [ebnf (html5-css3-ebnf.parse/parser-wtrek->ebnf
html-parser gen-wtrek)]
(pr-err (str "Saving pruned HTML EBNF to: '" html-ebnf-output "'"))
(spit html-ebnf-output ebnf)))
(when css-ebnf-output
(pr-err (str "Generating pruned CSS EBNF"))
(let [ebnf (html5-css3-ebnf.parse/parser-wtrek->ebnf
css-parser gen-wtrek)]
(pr-err (str "Saving pruned CSS EBNF to: '" css-ebnf-output "'"))
(spit css-ebnf-output ebnf)))
(when weights-output
(pr-err (str "Saving merged weights to: '" weights-output "'"))
(icore/save-weights weights-output gen-wtrek))))
| null | https://raw.githubusercontent.com/kanaka/bartender/4357fde74adb228a3cd3fcc12cae4926da899b4e/src/wend/cli.clj | clojure |
a parse grammar to a generator grammar.
Default values to use for generator specific weights in order to
create a usable generator weight map from a parsed one. Can be
either a default value, a weight to lookup, or a function that is
Adjust for different elements in :cat
No great match, but use the closest elements
Just use even weights for url types
Increase style attr since style and linked stylesheets are not
used in gen mode. Sum the :element weights to get a decently
large approx magnitude that is inline with existing weights.
Apply the gen-weight-mapping transforms
Multiply weights by multiplier factor
Make sure that global attributes have weight so that style
will appear since style and linked stylesheets are not used
in gen mode.
Command line usage of wend | (ns wend.cli
(:require [clojure.tools.cli :refer [parse-opts summarize]]
[clojure.java.io :as io]
[clojure.string :refer [ends-with?]]
[clojure.pprint :refer [pprint]]
[instacheck.core :as icore]
[instacheck.grammar :as igrammar]
[instacheck.reduce :as ireduce]
[html5-css3-ebnf.parse]
[html5-css3-ebnf.html-mangle :as html-mangle]
[mend.parse]))
This extends to add mapping of weights from
(defn pr-err
[& args]
(binding [*out* *err*]
(apply println args)
(flush)))
called with the wtrek .
(def gen-weight-mapping
{
[:head-test :cat 3 :opt nil] #(or (get % [:head :cat 2 :star nil]) 1)
[:head-test :cat 3 :opt 0] [:head :cat 2 :star 0]
[:title-test :cat 1 :star nil] [:title :cat 1 :star nil]
[:title-test :cat 1 :star 0] [:title :cat 1 :star 0]
[:title-test :cat 3 :star nil] [:title :cat 3 :star nil]
[:title-test :cat 3 :star 0] [:title :cat 3 :star 0]
[:body-test :cat 1 :star nil] [:body :cat 1 :star nil]
[:body-test :cat 1 :star 0] [:body :cat 1 :star 0]
[:body-test :cat 4 :star nil] [:body :cat 3 :star nil]
[:body-test :cat 4 :star 0] [:body :cat 3 :star 0]
[:body-test :cat 4 :star 0 :alt 0] [:body :cat 3 :star 0 :alt 0]
[:body-test :cat 4 :star 0 :alt 1] [:body :cat 3 :star 0 :alt 1]
[:css-assignments-test :alt 0] [:css-assignments :alt 0]
[:css-assignments-test :alt 1] [:css-assignments :alt 1]
[:css-assignments-test :alt 1 :cat 1 :star nil]
,,, [:css-assignments :alt 1 :cat 2 :star nil]
[:css-assignments-test :alt 1 :cat 1 :star 0]
,,, [:css-assignments :alt 1 :cat 2 :star 0]
[:char-data-test :alt 0] [:content :alt 0]
[:char-data-test :alt 1] [:content :alt 0]
[:char-data-test :alt 2] [:content :alt 1]
[:char-data-test :alt 3] [:content :alt 0]
[:url-test :alt 0] 100
[:url-test :alt 1] 100
[:url-test :alt 2] 100
[:global-attribute :alt 11]
,,, (fn [tk] (apply + (vals (filter #(= :element (first (key %))) tk))))
})
(defn apply-weight-mapping
[wtrek mapping]
(reduce
(fn [tk [p v]]
(let [w (cond
(number? v) v
(fn? v) (v tk)
:else (get tk v -1))]
(if (> w 0)
(assoc tk p w)
tk)))
wtrek
mapping))
(defn mangle-wtrek
[html-grammar orig-wtrek multiplier]
wtrek1 (apply-weight-mapping orig-wtrek gen-weight-mapping)
wtrek2 (into {} (for [[p w] wtrek1]
[p (* w multiplier)]))
wtrek3 (reduce
(fn [tk [p w]]
(if (and (= 3 (count p))
(= [:element :alt] (take 2 p)))
(let [attr (-> (igrammar/get-in-grammar html-grammar p)
:parsers
(nth 0)
:string
(subs 1)
(str "-attribute")
keyword)]
(assoc tk
[:element :alt (nth p 2) :cat 1 :star 0] 77
[attr :alt 0] 78))
tk))
wtrek2
wtrek2)]
wtrek3))
(defn usage [data]
(str "Usage: parse [OPTS] <FILE>..."
(summarize data)))
(def cli-options
[["-?" "--help" "Show usage"
:default false]
[nil "--debug" "Add debug comments to generated code"]
[nil "--verbose" "Verbose output during execution"]
[nil "--multiplier MULTIPLIER" "Multiply parsed weights by MULTIPLIER"
:default 100]
[nil "--weights-output WEIGHTS-OUTPUT" "Write all resulting frequency weights to WEIGHTS-OUTPUT"]
[nil "--parse-output PARSE-OUTPUT" "Write resulting parse data to PARSE-OUTPUT"]
[nil "--html-ebnf-output HTML-EBNF-OUTPUT" "Write pruned HTML EBNF grammar to HTML-EBNF-OUTPUT"]
[nil "--css-ebnf-output CSS-EBNF-OUTPUT" "Write pruned CSS EBNF grammar to CSS-EBNF-OUTPUT"]])
(defn opt-errors [opts]
(when (:errors opts)
(doall (map pr-err (:errors opts)))
(System/exit 2))
(when (or (-> opts :options :help)
(-> opts :arguments count (= 0)))
(println (:summary opts))
(System/exit 2))
opts)
(defn -main
[& args]
(let [opts (opt-errors (parse-opts args cli-options
:summary-fn usage))
{:keys [multiplier parse-output weights-output
html-ebnf-output css-ebnf-output]} (:options opts)
[& files] (:arguments opts)
_ (pr-err "Loading HTML parser")
html-parser (mend.parse/load-parser-from-grammar :html :parse)
_ (pr-err "Loading CSS parser")
css-parser (mend.parse/load-parser-from-grammar :css :parse)
parse-data (html5-css3-ebnf.parse/parse-files
html-parser css-parser files)
gen-wtrek (mangle-wtrek (:grammar html-parser)
(:full-wtrek parse-data)
multiplier)]
(pr-err (str "Combined and filtered weights: "
(count gen-wtrek)))
(when parse-output
(pr-err (str "Saving parse data to: '" parse-output "'"))
(spit parse-output parse-data))
(when html-ebnf-output
(pr-err (str "Generating pruned HTML EBNF"))
(let [ebnf (html5-css3-ebnf.parse/parser-wtrek->ebnf
html-parser gen-wtrek)]
(pr-err (str "Saving pruned HTML EBNF to: '" html-ebnf-output "'"))
(spit html-ebnf-output ebnf)))
(when css-ebnf-output
(pr-err (str "Generating pruned CSS EBNF"))
(let [ebnf (html5-css3-ebnf.parse/parser-wtrek->ebnf
css-parser gen-wtrek)]
(pr-err (str "Saving pruned CSS EBNF to: '" css-ebnf-output "'"))
(spit css-ebnf-output ebnf)))
(when weights-output
(pr-err (str "Saving merged weights to: '" weights-output "'"))
(icore/save-weights weights-output gen-wtrek))))
|
bc51255bf3f7ced08bb8c44a4f2b00e302cfcfe644e1270198f7843bc5ef1f22 | creswick/ihaskell-notebook | Main.hs | module Main where
import Test.Framework ( defaultMain )
import qualified JsonIO as JsonIO
main :: IO ()
main = defaultMain $ concat [ JsonIO.tests ] | null | https://raw.githubusercontent.com/creswick/ihaskell-notebook/91dfd756d408e5cddf9b53286bca702d731b09b7/ghcj/tests/src/Main.hs | haskell | module Main where
import Test.Framework ( defaultMain )
import qualified JsonIO as JsonIO
main :: IO ()
main = defaultMain $ concat [ JsonIO.tests ] | |
8226a26c7a500295dccda442a3c5586c99ec8389ef6b4088f6e7c83d6b30631d | matsubara0507/git-plantation | Main.hs | # LANGUAGE OverloadedLabels #
# OPTIONS_GHC -fno - warn - orphans #
module Main where
import Options
import qualified Paths_git_plantation as Meta
import RIO
import Configuration.Dotenv (defaultConfig, loadFile)
import Data.Extensible
import Git.Plantation.Cmd as Cmd
import Git.Plantation.Config (readConfig)
import Git.Plantation.Env (mkWebhookConf)
import Options.Applicative
import System.Environment (getEnv)
import qualified Mix
import qualified Mix.Plugin.Drone as MixDrone
import qualified Mix.Plugin.GitHub as MixGitHub
import qualified Mix.Plugin.Logger as MixLogger
import qualified Mix.Plugin.Shell as MixShell
main :: IO ()
main = execParser parser >>= \opts -> do
_ <- tryIO $ loadFile defaultConfig
config <- readConfig (opts ^. #config)
token <- liftIO $ fromString <$> getEnv "GH_TOKEN"
dHost <- liftIO $ fromString <$> getEnv "DRONE_HOST"
dPort <- liftIO $ readMaybe <$> getEnv "DRONE_PORT"
dToken <- liftIO $ fromString <$> getEnv "DRONE_TOKEN"
secret <- liftIO $ fromString <$> getEnv "GH_SECRET"
appUrl <- liftIO $ fromString <$> getEnv "APP_SERVER"
let client = #host @= dHost <: #port @= dPort <: #token @= dToken <: nil
logConf = #handle @= stdout <: #verbose @= (opts ^. #verbose) <: nil
plugin = hsequence
$ #config <@=> pure config
<: #github <@=> MixGitHub.buildPlugin token
<: #slack <@=> pure Nothing
<: #work <@=> MixShell.buildPlugin (opts ^. #work)
<: #drone <@=> MixDrone.buildPlugin client False
<: #webhook <@=> pure (mkWebhookConf (appUrl <> "/hook") secret)
<: #store <@=> pure ""
<: #logger <@=> MixLogger.buildPlugin logConf
<: #oauth <@=> pure Nothing
<: nil
Mix.run plugin $ Cmd.run (opts ^. #subcmd)
where
parser = info (options <**> version Meta.version <**> helper)
$ fullDesc
<> header "git-plantation-tool - operate repository for git-plantation"
| null | https://raw.githubusercontent.com/matsubara0507/git-plantation/7bd7ea01fec83dc02118eefcfeb145a1df4f564e/exec/tool/Main.hs | haskell | # LANGUAGE OverloadedLabels #
# OPTIONS_GHC -fno - warn - orphans #
module Main where
import Options
import qualified Paths_git_plantation as Meta
import RIO
import Configuration.Dotenv (defaultConfig, loadFile)
import Data.Extensible
import Git.Plantation.Cmd as Cmd
import Git.Plantation.Config (readConfig)
import Git.Plantation.Env (mkWebhookConf)
import Options.Applicative
import System.Environment (getEnv)
import qualified Mix
import qualified Mix.Plugin.Drone as MixDrone
import qualified Mix.Plugin.GitHub as MixGitHub
import qualified Mix.Plugin.Logger as MixLogger
import qualified Mix.Plugin.Shell as MixShell
main :: IO ()
main = execParser parser >>= \opts -> do
_ <- tryIO $ loadFile defaultConfig
config <- readConfig (opts ^. #config)
token <- liftIO $ fromString <$> getEnv "GH_TOKEN"
dHost <- liftIO $ fromString <$> getEnv "DRONE_HOST"
dPort <- liftIO $ readMaybe <$> getEnv "DRONE_PORT"
dToken <- liftIO $ fromString <$> getEnv "DRONE_TOKEN"
secret <- liftIO $ fromString <$> getEnv "GH_SECRET"
appUrl <- liftIO $ fromString <$> getEnv "APP_SERVER"
let client = #host @= dHost <: #port @= dPort <: #token @= dToken <: nil
logConf = #handle @= stdout <: #verbose @= (opts ^. #verbose) <: nil
plugin = hsequence
$ #config <@=> pure config
<: #github <@=> MixGitHub.buildPlugin token
<: #slack <@=> pure Nothing
<: #work <@=> MixShell.buildPlugin (opts ^. #work)
<: #drone <@=> MixDrone.buildPlugin client False
<: #webhook <@=> pure (mkWebhookConf (appUrl <> "/hook") secret)
<: #store <@=> pure ""
<: #logger <@=> MixLogger.buildPlugin logConf
<: #oauth <@=> pure Nothing
<: nil
Mix.run plugin $ Cmd.run (opts ^. #subcmd)
where
parser = info (options <**> version Meta.version <**> helper)
$ fullDesc
<> header "git-plantation-tool - operate repository for git-plantation"
| |
73232e49423f46c97a56b054fb04485871243250943eb52e4220191dfc712d57 | picty/parsifal | test_pci.ml | open Parsifal
open Pci
let _ =
try
let pci_filename =
if Array.length Sys.argv > 1
then Sys.argv.(1)
else "test.pci"
in
let input = string_input_of_filename pci_filename in
let pci_file = parse_rom_file input in
print_endline (print_value (value_of_rom_file pci_file));
exit 0
with
| ParsingException (e, h) -> prerr_endline (string_of_exception e h); exit 1
| e -> prerr_endline (Printexc.to_string e); exit 1
| null | https://raw.githubusercontent.com/picty/parsifal/767a1d558ea6da23ada46d8d96a057514b0aa2a8/pci/test_pci.ml | ocaml | open Parsifal
open Pci
let _ =
try
let pci_filename =
if Array.length Sys.argv > 1
then Sys.argv.(1)
else "test.pci"
in
let input = string_input_of_filename pci_filename in
let pci_file = parse_rom_file input in
print_endline (print_value (value_of_rom_file pci_file));
exit 0
with
| ParsingException (e, h) -> prerr_endline (string_of_exception e h); exit 1
| e -> prerr_endline (Printexc.to_string e); exit 1
| |
d4f381cb868c59f98af749bb1042511fa632890b846a6d812972edf096510de3 | ocsigen/ocaml-eliom | oprint.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
Projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2002 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open Format
open Outcometree
exception Ellipsis
let cautious f ppf arg =
try f ppf arg with
Ellipsis -> fprintf ppf "..."
let rec print_ident ppf =
function
Oide_ident s -> pp_print_string ppf s
| Oide_dot (id, s) ->
print_ident ppf id; pp_print_char ppf '.'; pp_print_string ppf s
| Oide_apply (id1, id2) ->
fprintf ppf "%a(%a)" print_ident id1 print_ident id2
let parenthesized_ident name =
(List.mem name ["or"; "mod"; "land"; "lor"; "lxor"; "lsl"; "lsr"; "asr"])
||
(match name.[0] with
'a'..'z' | 'A'..'Z' | '\223'..'\246' | '\248'..'\255' | '_' ->
false
| _ -> true)
let value_ident ppf name =
if parenthesized_ident name then
fprintf ppf "( %s )" name
else
pp_print_string ppf name
(* Values *)
let valid_float_lexeme s =
let l = String.length s in
let rec loop i =
if i >= l then s ^ "." else
match s.[i] with
| '0' .. '9' | '-' -> loop (i+1)
| _ -> s
in loop 0
let float_repres f =
match classify_float f with
FP_nan -> "nan"
| FP_infinite ->
if f < 0.0 then "neg_infinity" else "infinity"
| _ ->
let float_val =
let s1 = Printf.sprintf "%.12g" f in
if f = float_of_string s1 then s1 else
let s2 = Printf.sprintf "%.15g" f in
if f = float_of_string s2 then s2 else
Printf.sprintf "%.18g" f
in valid_float_lexeme float_val
let parenthesize_if_neg ppf fmt v isneg =
if isneg then pp_print_char ppf '(';
fprintf ppf fmt v;
if isneg then pp_print_char ppf ')'
let print_out_value ppf tree =
let rec print_tree_1 ppf =
function
| Oval_constr (name, [param]) ->
fprintf ppf "@[<1>%a@ %a@]" print_ident name print_constr_param param
| Oval_constr (name, (_ :: _ as params)) ->
fprintf ppf "@[<1>%a@ (%a)@]" print_ident name
(print_tree_list print_tree_1 ",") params
| Oval_variant (name, Some param) ->
fprintf ppf "@[<2>`%s@ %a@]" name print_constr_param param
| tree -> print_simple_tree ppf tree
and print_constr_param ppf = function
| Oval_int i -> parenthesize_if_neg ppf "%i" i (i < 0)
| Oval_int32 i -> parenthesize_if_neg ppf "%lil" i (i < 0l)
| Oval_int64 i -> parenthesize_if_neg ppf "%LiL" i (i < 0L)
| Oval_nativeint i -> parenthesize_if_neg ppf "%nin" i (i < 0n)
| Oval_float f -> parenthesize_if_neg ppf "%s" (float_repres f) (f < 0.0)
| tree -> print_simple_tree ppf tree
and print_simple_tree ppf =
function
Oval_int i -> fprintf ppf "%i" i
| Oval_int32 i -> fprintf ppf "%lil" i
| Oval_int64 i -> fprintf ppf "%LiL" i
| Oval_nativeint i -> fprintf ppf "%nin" i
| Oval_float f -> pp_print_string ppf (float_repres f)
| Oval_char c -> fprintf ppf "%C" c
| Oval_string s ->
begin try fprintf ppf "%S" s with
Invalid_argument _ (* "String.create" *)-> fprintf ppf "<huge string>"
end
| Oval_list tl ->
fprintf ppf "@[<1>[%a]@]" (print_tree_list print_tree_1 ";") tl
| Oval_array tl ->
fprintf ppf "@[<2>[|%a|]@]" (print_tree_list print_tree_1 ";") tl
| Oval_constr (name, []) -> print_ident ppf name
| Oval_variant (name, None) -> fprintf ppf "`%s" name
| Oval_stuff s -> pp_print_string ppf s
| Oval_record fel ->
fprintf ppf "@[<1>{%a}@]" (cautious (print_fields true)) fel
| Oval_ellipsis -> raise Ellipsis
| Oval_printer f -> f ppf
| Oval_tuple tree_list ->
fprintf ppf "@[<1>(%a)@]" (print_tree_list print_tree_1 ",") tree_list
| tree -> fprintf ppf "@[<1>(%a)@]" (cautious print_tree_1) tree
and print_fields first ppf =
function
[] -> ()
| (name, tree) :: fields ->
if not first then fprintf ppf ";@ ";
fprintf ppf "@[<1>%a@ =@ %a@]" print_ident name (cautious print_tree_1)
tree;
print_fields false ppf fields
and print_tree_list print_item sep ppf tree_list =
let rec print_list first ppf =
function
[] -> ()
| tree :: tree_list ->
if not first then fprintf ppf "%s@ " sep;
print_item ppf tree;
print_list false ppf tree_list
in
cautious (print_list true) ppf tree_list
in
cautious print_tree_1 ppf tree
let out_value = ref print_out_value
(* Types *)
let rec print_list_init pr sep ppf =
function
[] -> ()
| a :: l -> sep ppf; pr ppf a; print_list_init pr sep ppf l
let rec print_list pr sep ppf =
function
[] -> ()
| [a] -> pr ppf a
| a :: l -> pr ppf a; sep ppf; print_list pr sep ppf l
let pr_present =
print_list (fun ppf s -> fprintf ppf "`%s" s) (fun ppf -> fprintf ppf "@ ")
let pr_vars =
print_list (fun ppf s -> fprintf ppf "'%s" s) (fun ppf -> fprintf ppf "@ ")
let rec print_out_type ppf =
function
| Otyp_alias (ty, s) ->
fprintf ppf "@[%a@ as '%s@]" print_out_type ty s
| Otyp_poly (sl, ty) ->
fprintf ppf "@[<hov 2>%a.@ %a@]"
pr_vars sl
print_out_type ty
| ty ->
print_out_type_1 ppf ty
and print_out_type_1 ppf =
function
Otyp_arrow (lab, ty1, ty2) ->
pp_open_box ppf 0;
if lab <> "" then (pp_print_string ppf lab; pp_print_char ppf ':');
print_out_type_2 ppf ty1;
pp_print_string ppf " ->";
pp_print_space ppf ();
print_out_type_1 ppf ty2;
pp_close_box ppf ()
| ty -> print_out_type_2 ppf ty
and print_out_type_2 ppf =
function
Otyp_tuple tyl ->
fprintf ppf "@[<0>%a@]" (print_typlist print_simple_out_type " *") tyl
| ty -> print_simple_out_type ppf ty
and print_simple_out_type ppf =
function
Otyp_class (ng, id, tyl) ->
fprintf ppf "@[%a%s#%a@]" print_typargs tyl (if ng then "_" else "")
print_ident id
| Otyp_constr (id, tyl) ->
pp_open_box ppf 0;
print_typargs ppf tyl;
print_ident ppf id;
pp_close_box ppf ()
| Otyp_object (fields, rest) ->
fprintf ppf "@[<2>< %a >@]" (print_fields rest) fields
| Otyp_stuff s -> pp_print_string ppf s
| Otyp_var (ng, s) -> fprintf ppf "'%s%s" (if ng then "_" else "") s
| Otyp_variant (non_gen, row_fields, closed, tags) ->
let print_present ppf =
function
None | Some [] -> ()
| Some l -> fprintf ppf "@;<1 -2>> @[<hov>%a@]" pr_present l
in
let print_fields ppf =
function
Ovar_fields fields ->
print_list print_row_field (fun ppf -> fprintf ppf "@;<1 -2>| ")
ppf fields
| Ovar_name (id, tyl) ->
fprintf ppf "@[%a%a@]" print_typargs tyl print_ident id
in
fprintf ppf "%s[%s@[<hv>@[<hv>%a@]%a ]@]" (if non_gen then "_" else "")
(if closed then if tags = None then " " else "< "
else if tags = None then "> " else "? ")
print_fields row_fields
print_present tags
| Otyp_alias _ | Otyp_poly _ | Otyp_arrow _ | Otyp_tuple _ as ty ->
pp_open_box ppf 1;
pp_print_char ppf '(';
print_out_type ppf ty;
pp_print_char ppf ')';
pp_close_box ppf ()
| Otyp_abstract | Otyp_open
| Otyp_sum _ | Otyp_manifest (_, _) -> ()
| Otyp_record lbls -> print_record_decl ppf lbls
| Otyp_module (p, n, tyl) ->
fprintf ppf "@[<1>(module %s" p;
let first = ref true in
List.iter2
(fun s t ->
let sep = if !first then (first := false; "with") else "and" in
fprintf ppf " %s type %s = %a" sep s print_out_type t
)
n tyl;
fprintf ppf ")@]"
| Otyp_attribute (t, attr) ->
fprintf ppf "@[<1>(%a [@@%s])@]" print_out_type t attr.oattr_name
and print_record_decl ppf lbls =
fprintf ppf "{%a@;<1 -2>}"
(print_list_init print_out_label (fun ppf -> fprintf ppf "@ ")) lbls
and print_fields rest ppf =
function
[] ->
begin match rest with
Some non_gen -> fprintf ppf "%s.." (if non_gen then "_" else "")
| None -> ()
end
| [s, t] ->
fprintf ppf "%s : %a" s print_out_type t;
begin match rest with
Some _ -> fprintf ppf ";@ "
| None -> ()
end;
print_fields rest ppf []
| (s, t) :: l ->
fprintf ppf "%s : %a;@ %a" s print_out_type t (print_fields rest) l
and print_row_field ppf (l, opt_amp, tyl) =
let pr_of ppf =
if opt_amp then fprintf ppf " of@ &@ "
else if tyl <> [] then fprintf ppf " of@ "
else fprintf ppf ""
in
fprintf ppf "@[<hv 2>`%s%t%a@]" l pr_of (print_typlist print_out_type " &")
tyl
and print_typlist print_elem sep ppf =
function
[] -> ()
| [ty] -> print_elem ppf ty
| ty :: tyl ->
print_elem ppf ty;
pp_print_string ppf sep;
pp_print_space ppf ();
print_typlist print_elem sep ppf tyl
and print_typargs ppf =
function
[] -> ()
| [ty1] -> print_simple_out_type ppf ty1; pp_print_space ppf ()
| tyl ->
pp_open_box ppf 1;
pp_print_char ppf '(';
print_typlist print_out_type "," ppf tyl;
pp_print_char ppf ')';
pp_close_box ppf ();
pp_print_space ppf ()
and print_out_label ppf (name, mut, arg) =
fprintf ppf "@[<2>%s%s :@ %a@];" (if mut then "mutable " else "") name
print_out_type arg
let out_type = ref print_out_type
(* Class types *)
let type_parameter ppf (ty, (co, cn)) =
fprintf ppf "%s%s"
(if not cn then "+" else if not co then "-" else "")
(if ty = "_" then ty else "'"^ty)
let print_out_class_params ppf =
function
[] -> ()
| tyl ->
fprintf ppf "@[<1>[%a]@]@ "
(print_list type_parameter (fun ppf -> fprintf ppf ", "))
tyl
let rec print_out_class_type ppf =
function
Octy_constr (id, tyl) ->
let pr_tyl ppf =
function
[] -> ()
| tyl ->
fprintf ppf "@[<1>[%a]@]@ " (print_typlist !out_type ",") tyl
in
fprintf ppf "@[%a%a@]" pr_tyl tyl print_ident id
| Octy_arrow (lab, ty, cty) ->
fprintf ppf "@[%s%a ->@ %a@]" (if lab <> "" then lab ^ ":" else "")
print_out_type_2 ty print_out_class_type cty
| Octy_signature (self_ty, csil) ->
let pr_param ppf =
function
Some ty -> fprintf ppf "@ @[(%a)@]" !out_type ty
| None -> ()
in
fprintf ppf "@[<hv 2>@[<2>object%a@]@ %a@;<1 -2>end@]" pr_param self_ty
(print_list print_out_class_sig_item (fun ppf -> fprintf ppf "@ "))
csil
and print_out_class_sig_item ppf =
function
Ocsg_constraint (ty1, ty2) ->
fprintf ppf "@[<2>constraint %a =@ %a@]" !out_type ty1
!out_type ty2
| Ocsg_method (name, priv, virt, ty) ->
fprintf ppf "@[<2>method %s%s%s :@ %a@]"
(if priv then "private " else "") (if virt then "virtual " else "")
name !out_type ty
| Ocsg_value (name, mut, vr, ty) ->
fprintf ppf "@[<2>val %s%s%s :@ %a@]"
(if mut then "mutable " else "")
(if vr then "virtual " else "")
name !out_type ty
let out_class_type = ref print_out_class_type
Signature
let out_module_type = ref (fun _ -> failwith "Oprint.out_module_type")
let out_sig_item = ref (fun _ -> failwith "Oprint.out_sig_item")
let out_signature = ref (fun _ -> failwith "Oprint.out_signature")
let out_type_extension = ref (fun _ -> failwith "Oprint.out_type_extension")
let rec print_out_functor funct ppf =
function
Omty_functor (_, None, mty_res) ->
if funct then fprintf ppf "() %a" (print_out_functor true) mty_res
else fprintf ppf "functor@ () %a" (print_out_functor true) mty_res
| Omty_functor (name, Some mty_arg, mty_res) -> begin
match name, funct with
| "_", true ->
fprintf ppf "->@ %a ->@ %a"
print_out_module_type mty_arg (print_out_functor false) mty_res
| "_", false ->
fprintf ppf "%a ->@ %a"
print_out_module_type mty_arg (print_out_functor false) mty_res
| name, true ->
fprintf ppf "(%s : %a) %a" name
print_out_module_type mty_arg (print_out_functor true) mty_res
| name, false ->
fprintf ppf "functor@ (%s : %a) %a" name
print_out_module_type mty_arg (print_out_functor true) mty_res
end
| m ->
if funct then fprintf ppf "->@ %a" print_out_module_type m
else print_out_module_type ppf m
and print_out_module_type ppf =
function
Omty_abstract -> ()
| Omty_functor _ as t ->
fprintf ppf "@[<2>%a@]" (print_out_functor false) t
| Omty_ident id -> fprintf ppf "%a" print_ident id
| Omty_signature sg ->
fprintf ppf "@[<hv 2>sig@ %a@;<1 -2>end@]" !out_signature sg
| Omty_alias id -> fprintf ppf "(module %a)" print_ident id
and print_out_signature ppf =
function
[] -> ()
| [item] -> !out_sig_item ppf item
| Osig_typext(ext, Oext_first) :: items ->
(* Gather together the extension constructors *)
let rec gather_extensions acc items =
match items with
Osig_typext(ext, Oext_next) :: items ->
gather_extensions
((ext.oext_name, ext.oext_args, ext.oext_ret_type) :: acc)
items
| _ -> (List.rev acc, items)
in
let exts, items =
gather_extensions
[(ext.oext_name, ext.oext_args, ext.oext_ret_type)]
items
in
let te =
{ otyext_name = ext.oext_type_name;
otyext_params = ext.oext_type_params;
otyext_constructors = exts;
otyext_private = ext.oext_private }
in
fprintf ppf "%a@ %a" !out_type_extension te print_out_signature items
| item :: items ->
fprintf ppf "%a@ %a" !out_sig_item item print_out_signature items
ELIOM
and side_to_string = let open Eliom_base in function
| Loc Client -> "%client"
| Loc Server -> "%server"
| Poly -> ""
and print_out_sig_item ppf sigi =
let side = side_to_string (Eliom_base.get_side ()) in
match sigi with
(* /ELIOM *)
Osig_class (vir_flag, name, params, clt, rs) ->
fprintf ppf "@[<2>%s%s@ %a%s@ :@ %a@]"
(if rs = Orec_next then "and" else "class"^side (*ELIOM*) )
(if vir_flag then " virtual" else "") print_out_class_params params
name !out_class_type clt
| Osig_class_type (vir_flag, name, params, clt, rs) ->
fprintf ppf "@[<2>%s%s@ %a%s@ =@ %a@]"
(if rs = Orec_next then "and" else "class type"^side (*ELIOM*) )
(if vir_flag then " virtual" else "") print_out_class_params params
name !out_class_type clt
| Osig_typext (ext, Oext_exception) ->
fprintf ppf "@[<2>exception%s %a@]"
ELIOM
print_out_constr (ext.oext_name, ext.oext_args, ext.oext_ret_type)
| Osig_typext (ext, es) ->
print_out_extension_constructor ppf ext
| Osig_modtype (name, Omty_abstract) ->
ELIOM
| Osig_modtype (name, mty) ->
ELIOM
| Osig_module (name, Omty_alias id, _) ->
ELIOM
| Osig_module (name, mty, rs) ->
fprintf ppf "@[<2>%s %s :@ %a@]"
(match rs with Orec_not -> "module"^side (*ELIOM*)
| Orec_first -> "module"^side (*ELIOM*)^ " rec"
| Orec_next -> "and")
name !out_module_type mty
| Osig_type(td, rs) ->
print_out_type_decl
(match rs with
| Orec_not -> "type"^side (*ELIOM*) ^" nonrec"
| Orec_first -> "type"^side (*ELIOM*)
| Orec_next -> "and")
ppf td
| Osig_value vd ->
let kwd = if vd.oval_prims = [] then "val" else "external" in
let pr_prims ppf =
function
[] -> ()
| s :: sl ->
fprintf ppf "@ = \"%s\"" s;
List.iter (fun s -> fprintf ppf "@ \"%s\"" s) sl
in
fprintf ppf "@[<2>%s%s %a :@ %a%a%a@]" kwd side value_ident vd.oval_name
!out_type vd.oval_type pr_prims vd.oval_prims
(fun ppf -> List.iter (fun a -> fprintf ppf "@ [@@@@%s]" a.oattr_name))
vd.oval_attributes
| Osig_ellipsis ->
fprintf ppf "..."
| Osig_side (side, sigi) ->
Eliom_base.in_loc side @@ fun () -> print_out_sig_item ppf sigi
and print_out_type_decl kwd ppf td =
let print_constraints ppf =
List.iter
(fun (ty1, ty2) ->
fprintf ppf "@ @[<2>constraint %a =@ %a@]" !out_type ty1
!out_type ty2)
td.otype_cstrs
in
let type_defined ppf =
match td.otype_params with
[] -> pp_print_string ppf td.otype_name
| [param] -> fprintf ppf "@[%a@ %s@]" type_parameter param td.otype_name
| _ ->
fprintf ppf "@[(@[%a)@]@ %s@]"
(print_list type_parameter (fun ppf -> fprintf ppf ",@ "))
td.otype_params
td.otype_name
in
let print_manifest ppf =
function
Otyp_manifest (ty, _) -> fprintf ppf " =@ %a" !out_type ty
| _ -> ()
in
let print_name_params ppf =
fprintf ppf "%s %t%a" kwd type_defined print_manifest td.otype_type
in
let ty =
match td.otype_type with
Otyp_manifest (_, ty) -> ty
| _ -> td.otype_type
in
let print_private ppf = function
Asttypes.Private -> fprintf ppf " private"
| Asttypes.Public -> ()
in
let print_immediate ppf =
if td.otype_immediate then fprintf ppf " [%@%@immediate]" else ()
in
let print_out_tkind ppf = function
| Otyp_abstract -> ()
| Otyp_record lbls ->
fprintf ppf " =%a %a"
print_private td.otype_private
print_record_decl lbls
| Otyp_sum constrs ->
fprintf ppf " =%a@;<1 2>%a"
print_private td.otype_private
(print_list print_out_constr (fun ppf -> fprintf ppf "@ | ")) constrs
| Otyp_open ->
fprintf ppf " = .."
| ty ->
fprintf ppf " =%a@;<1 2>%a"
print_private td.otype_private
!out_type ty
in
fprintf ppf "@[<2>@[<hv 2>%t%a@]%t%t@]"
print_name_params
print_out_tkind ty
print_constraints
print_immediate
and print_out_constr ppf (name, tyl,ret_type_opt) =
match ret_type_opt with
| None ->
begin match tyl with
| [] ->
pp_print_string ppf name
| _ ->
fprintf ppf "@[<2>%s of@ %a@]" name
(print_typlist print_simple_out_type " *") tyl
end
| Some ret_type ->
begin match tyl with
| [] ->
fprintf ppf "@[<2>%s :@ %a@]" name print_simple_out_type ret_type
| _ ->
fprintf ppf "@[<2>%s :@ %a -> %a@]" name
(print_typlist print_simple_out_type " *")
tyl print_simple_out_type ret_type
end
and print_out_extension_constructor ppf ext =
let print_extended_type ppf =
let print_type_parameter ppf ty =
fprintf ppf "%s"
(if ty = "_" then ty else "'"^ty)
in
match ext.oext_type_params with
[] -> fprintf ppf "%s" ext.oext_type_name
| [ty_param] ->
fprintf ppf "@[%a@ %s@]"
print_type_parameter
ty_param
ext.oext_type_name
| _ ->
fprintf ppf "@[(@[%a)@]@ %s@]"
(print_list print_type_parameter (fun ppf -> fprintf ppf ",@ "))
ext.oext_type_params
ext.oext_type_name
in
fprintf ppf "@[<hv 2>type %t +=%s@;<1 2>%a@]"
print_extended_type
(if ext.oext_private = Asttypes.Private then " private" else "")
print_out_constr (ext.oext_name, ext.oext_args, ext.oext_ret_type)
and print_out_type_extension ppf te =
let print_extended_type ppf =
let print_type_parameter ppf ty =
fprintf ppf "%s"
(if ty = "_" then ty else "'"^ty)
in
match te.otyext_params with
[] -> fprintf ppf "%s" te.otyext_name
| [param] ->
fprintf ppf "@[%a@ %s@]"
print_type_parameter param
te.otyext_name
| _ ->
fprintf ppf "@[(@[%a)@]@ %s@]"
(print_list print_type_parameter (fun ppf -> fprintf ppf ",@ "))
te.otyext_params
te.otyext_name
in
fprintf ppf "@[<hv 2>type %t +=%s@;<1 2>%a@]"
print_extended_type
(if te.otyext_private = Asttypes.Private then " private" else "")
(print_list print_out_constr (fun ppf -> fprintf ppf "@ | "))
te.otyext_constructors
let _ = out_module_type := print_out_module_type
let _ = out_signature := print_out_signature
let _ = out_sig_item := print_out_sig_item
let _ = out_type_extension := print_out_type_extension
(* Phrases *)
let print_out_exception ppf exn outv =
match exn with
Sys.Break -> fprintf ppf "Interrupted.@."
| Out_of_memory -> fprintf ppf "Out of memory during evaluation.@."
| Stack_overflow ->
fprintf ppf "Stack overflow during evaluation (looping recursion?).@."
| _ -> fprintf ppf "@[Exception:@ %a.@]@." !out_value outv
let rec print_items ppf =
function
[] -> ()
| (Osig_typext(ext, Oext_first), None) :: items ->
(* Gather together extension constructors *)
let rec gather_extensions acc items =
match items with
(Osig_typext(ext, Oext_next), None) :: items ->
gather_extensions
((ext.oext_name, ext.oext_args, ext.oext_ret_type) :: acc)
items
| _ -> (List.rev acc, items)
in
let exts, items =
gather_extensions
[(ext.oext_name, ext.oext_args, ext.oext_ret_type)]
items
in
let te =
{ otyext_name = ext.oext_type_name;
otyext_params = ext.oext_type_params;
otyext_constructors = exts;
otyext_private = ext.oext_private }
in
fprintf ppf "@[%a@]" !out_type_extension te;
if items <> [] then fprintf ppf "@ %a" print_items items
| (tree, valopt) :: items ->
begin match valopt with
Some v ->
fprintf ppf "@[<2>%a =@ %a@]" !out_sig_item tree
!out_value v
| None -> fprintf ppf "@[%a@]" !out_sig_item tree
end;
if items <> [] then fprintf ppf "@ %a" print_items items
let print_out_phrase ppf =
function
Ophr_eval (outv, ty) ->
fprintf ppf "@[- : %a@ =@ %a@]@." !out_type ty !out_value outv
| Ophr_signature [] -> ()
| Ophr_signature items -> fprintf ppf "@[<v>%a@]@." print_items items
| Ophr_exception (exn, outv) -> print_out_exception ppf exn outv
let out_phrase = ref print_out_phrase
| null | https://raw.githubusercontent.com/ocsigen/ocaml-eliom/497c6707f477cb3086dc6d8124384e74a8c379ae/typing/oprint.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Values
"String.create"
Types
Class types
Gather together the extension constructors
/ELIOM
ELIOM
ELIOM
ELIOM
ELIOM
ELIOM
ELIOM
Phrases
Gather together extension constructors | Projet Cristal , INRIA Rocquencourt
Copyright 2002 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Format
open Outcometree
exception Ellipsis
let cautious f ppf arg =
try f ppf arg with
Ellipsis -> fprintf ppf "..."
let rec print_ident ppf =
function
Oide_ident s -> pp_print_string ppf s
| Oide_dot (id, s) ->
print_ident ppf id; pp_print_char ppf '.'; pp_print_string ppf s
| Oide_apply (id1, id2) ->
fprintf ppf "%a(%a)" print_ident id1 print_ident id2
let parenthesized_ident name =
(List.mem name ["or"; "mod"; "land"; "lor"; "lxor"; "lsl"; "lsr"; "asr"])
||
(match name.[0] with
'a'..'z' | 'A'..'Z' | '\223'..'\246' | '\248'..'\255' | '_' ->
false
| _ -> true)
let value_ident ppf name =
if parenthesized_ident name then
fprintf ppf "( %s )" name
else
pp_print_string ppf name
let valid_float_lexeme s =
let l = String.length s in
let rec loop i =
if i >= l then s ^ "." else
match s.[i] with
| '0' .. '9' | '-' -> loop (i+1)
| _ -> s
in loop 0
let float_repres f =
match classify_float f with
FP_nan -> "nan"
| FP_infinite ->
if f < 0.0 then "neg_infinity" else "infinity"
| _ ->
let float_val =
let s1 = Printf.sprintf "%.12g" f in
if f = float_of_string s1 then s1 else
let s2 = Printf.sprintf "%.15g" f in
if f = float_of_string s2 then s2 else
Printf.sprintf "%.18g" f
in valid_float_lexeme float_val
let parenthesize_if_neg ppf fmt v isneg =
if isneg then pp_print_char ppf '(';
fprintf ppf fmt v;
if isneg then pp_print_char ppf ')'
let print_out_value ppf tree =
let rec print_tree_1 ppf =
function
| Oval_constr (name, [param]) ->
fprintf ppf "@[<1>%a@ %a@]" print_ident name print_constr_param param
| Oval_constr (name, (_ :: _ as params)) ->
fprintf ppf "@[<1>%a@ (%a)@]" print_ident name
(print_tree_list print_tree_1 ",") params
| Oval_variant (name, Some param) ->
fprintf ppf "@[<2>`%s@ %a@]" name print_constr_param param
| tree -> print_simple_tree ppf tree
and print_constr_param ppf = function
| Oval_int i -> parenthesize_if_neg ppf "%i" i (i < 0)
| Oval_int32 i -> parenthesize_if_neg ppf "%lil" i (i < 0l)
| Oval_int64 i -> parenthesize_if_neg ppf "%LiL" i (i < 0L)
| Oval_nativeint i -> parenthesize_if_neg ppf "%nin" i (i < 0n)
| Oval_float f -> parenthesize_if_neg ppf "%s" (float_repres f) (f < 0.0)
| tree -> print_simple_tree ppf tree
and print_simple_tree ppf =
function
Oval_int i -> fprintf ppf "%i" i
| Oval_int32 i -> fprintf ppf "%lil" i
| Oval_int64 i -> fprintf ppf "%LiL" i
| Oval_nativeint i -> fprintf ppf "%nin" i
| Oval_float f -> pp_print_string ppf (float_repres f)
| Oval_char c -> fprintf ppf "%C" c
| Oval_string s ->
begin try fprintf ppf "%S" s with
end
| Oval_list tl ->
fprintf ppf "@[<1>[%a]@]" (print_tree_list print_tree_1 ";") tl
| Oval_array tl ->
fprintf ppf "@[<2>[|%a|]@]" (print_tree_list print_tree_1 ";") tl
| Oval_constr (name, []) -> print_ident ppf name
| Oval_variant (name, None) -> fprintf ppf "`%s" name
| Oval_stuff s -> pp_print_string ppf s
| Oval_record fel ->
fprintf ppf "@[<1>{%a}@]" (cautious (print_fields true)) fel
| Oval_ellipsis -> raise Ellipsis
| Oval_printer f -> f ppf
| Oval_tuple tree_list ->
fprintf ppf "@[<1>(%a)@]" (print_tree_list print_tree_1 ",") tree_list
| tree -> fprintf ppf "@[<1>(%a)@]" (cautious print_tree_1) tree
and print_fields first ppf =
function
[] -> ()
| (name, tree) :: fields ->
if not first then fprintf ppf ";@ ";
fprintf ppf "@[<1>%a@ =@ %a@]" print_ident name (cautious print_tree_1)
tree;
print_fields false ppf fields
and print_tree_list print_item sep ppf tree_list =
let rec print_list first ppf =
function
[] -> ()
| tree :: tree_list ->
if not first then fprintf ppf "%s@ " sep;
print_item ppf tree;
print_list false ppf tree_list
in
cautious (print_list true) ppf tree_list
in
cautious print_tree_1 ppf tree
let out_value = ref print_out_value
let rec print_list_init pr sep ppf =
function
[] -> ()
| a :: l -> sep ppf; pr ppf a; print_list_init pr sep ppf l
let rec print_list pr sep ppf =
function
[] -> ()
| [a] -> pr ppf a
| a :: l -> pr ppf a; sep ppf; print_list pr sep ppf l
let pr_present =
print_list (fun ppf s -> fprintf ppf "`%s" s) (fun ppf -> fprintf ppf "@ ")
let pr_vars =
print_list (fun ppf s -> fprintf ppf "'%s" s) (fun ppf -> fprintf ppf "@ ")
let rec print_out_type ppf =
function
| Otyp_alias (ty, s) ->
fprintf ppf "@[%a@ as '%s@]" print_out_type ty s
| Otyp_poly (sl, ty) ->
fprintf ppf "@[<hov 2>%a.@ %a@]"
pr_vars sl
print_out_type ty
| ty ->
print_out_type_1 ppf ty
and print_out_type_1 ppf =
function
Otyp_arrow (lab, ty1, ty2) ->
pp_open_box ppf 0;
if lab <> "" then (pp_print_string ppf lab; pp_print_char ppf ':');
print_out_type_2 ppf ty1;
pp_print_string ppf " ->";
pp_print_space ppf ();
print_out_type_1 ppf ty2;
pp_close_box ppf ()
| ty -> print_out_type_2 ppf ty
and print_out_type_2 ppf =
function
Otyp_tuple tyl ->
fprintf ppf "@[<0>%a@]" (print_typlist print_simple_out_type " *") tyl
| ty -> print_simple_out_type ppf ty
and print_simple_out_type ppf =
function
Otyp_class (ng, id, tyl) ->
fprintf ppf "@[%a%s#%a@]" print_typargs tyl (if ng then "_" else "")
print_ident id
| Otyp_constr (id, tyl) ->
pp_open_box ppf 0;
print_typargs ppf tyl;
print_ident ppf id;
pp_close_box ppf ()
| Otyp_object (fields, rest) ->
fprintf ppf "@[<2>< %a >@]" (print_fields rest) fields
| Otyp_stuff s -> pp_print_string ppf s
| Otyp_var (ng, s) -> fprintf ppf "'%s%s" (if ng then "_" else "") s
| Otyp_variant (non_gen, row_fields, closed, tags) ->
let print_present ppf =
function
None | Some [] -> ()
| Some l -> fprintf ppf "@;<1 -2>> @[<hov>%a@]" pr_present l
in
let print_fields ppf =
function
Ovar_fields fields ->
print_list print_row_field (fun ppf -> fprintf ppf "@;<1 -2>| ")
ppf fields
| Ovar_name (id, tyl) ->
fprintf ppf "@[%a%a@]" print_typargs tyl print_ident id
in
fprintf ppf "%s[%s@[<hv>@[<hv>%a@]%a ]@]" (if non_gen then "_" else "")
(if closed then if tags = None then " " else "< "
else if tags = None then "> " else "? ")
print_fields row_fields
print_present tags
| Otyp_alias _ | Otyp_poly _ | Otyp_arrow _ | Otyp_tuple _ as ty ->
pp_open_box ppf 1;
pp_print_char ppf '(';
print_out_type ppf ty;
pp_print_char ppf ')';
pp_close_box ppf ()
| Otyp_abstract | Otyp_open
| Otyp_sum _ | Otyp_manifest (_, _) -> ()
| Otyp_record lbls -> print_record_decl ppf lbls
| Otyp_module (p, n, tyl) ->
fprintf ppf "@[<1>(module %s" p;
let first = ref true in
List.iter2
(fun s t ->
let sep = if !first then (first := false; "with") else "and" in
fprintf ppf " %s type %s = %a" sep s print_out_type t
)
n tyl;
fprintf ppf ")@]"
| Otyp_attribute (t, attr) ->
fprintf ppf "@[<1>(%a [@@%s])@]" print_out_type t attr.oattr_name
and print_record_decl ppf lbls =
fprintf ppf "{%a@;<1 -2>}"
(print_list_init print_out_label (fun ppf -> fprintf ppf "@ ")) lbls
and print_fields rest ppf =
function
[] ->
begin match rest with
Some non_gen -> fprintf ppf "%s.." (if non_gen then "_" else "")
| None -> ()
end
| [s, t] ->
fprintf ppf "%s : %a" s print_out_type t;
begin match rest with
Some _ -> fprintf ppf ";@ "
| None -> ()
end;
print_fields rest ppf []
| (s, t) :: l ->
fprintf ppf "%s : %a;@ %a" s print_out_type t (print_fields rest) l
and print_row_field ppf (l, opt_amp, tyl) =
let pr_of ppf =
if opt_amp then fprintf ppf " of@ &@ "
else if tyl <> [] then fprintf ppf " of@ "
else fprintf ppf ""
in
fprintf ppf "@[<hv 2>`%s%t%a@]" l pr_of (print_typlist print_out_type " &")
tyl
and print_typlist print_elem sep ppf =
function
[] -> ()
| [ty] -> print_elem ppf ty
| ty :: tyl ->
print_elem ppf ty;
pp_print_string ppf sep;
pp_print_space ppf ();
print_typlist print_elem sep ppf tyl
and print_typargs ppf =
function
[] -> ()
| [ty1] -> print_simple_out_type ppf ty1; pp_print_space ppf ()
| tyl ->
pp_open_box ppf 1;
pp_print_char ppf '(';
print_typlist print_out_type "," ppf tyl;
pp_print_char ppf ')';
pp_close_box ppf ();
pp_print_space ppf ()
and print_out_label ppf (name, mut, arg) =
fprintf ppf "@[<2>%s%s :@ %a@];" (if mut then "mutable " else "") name
print_out_type arg
let out_type = ref print_out_type
let type_parameter ppf (ty, (co, cn)) =
fprintf ppf "%s%s"
(if not cn then "+" else if not co then "-" else "")
(if ty = "_" then ty else "'"^ty)
let print_out_class_params ppf =
function
[] -> ()
| tyl ->
fprintf ppf "@[<1>[%a]@]@ "
(print_list type_parameter (fun ppf -> fprintf ppf ", "))
tyl
let rec print_out_class_type ppf =
function
Octy_constr (id, tyl) ->
let pr_tyl ppf =
function
[] -> ()
| tyl ->
fprintf ppf "@[<1>[%a]@]@ " (print_typlist !out_type ",") tyl
in
fprintf ppf "@[%a%a@]" pr_tyl tyl print_ident id
| Octy_arrow (lab, ty, cty) ->
fprintf ppf "@[%s%a ->@ %a@]" (if lab <> "" then lab ^ ":" else "")
print_out_type_2 ty print_out_class_type cty
| Octy_signature (self_ty, csil) ->
let pr_param ppf =
function
Some ty -> fprintf ppf "@ @[(%a)@]" !out_type ty
| None -> ()
in
fprintf ppf "@[<hv 2>@[<2>object%a@]@ %a@;<1 -2>end@]" pr_param self_ty
(print_list print_out_class_sig_item (fun ppf -> fprintf ppf "@ "))
csil
and print_out_class_sig_item ppf =
function
Ocsg_constraint (ty1, ty2) ->
fprintf ppf "@[<2>constraint %a =@ %a@]" !out_type ty1
!out_type ty2
| Ocsg_method (name, priv, virt, ty) ->
fprintf ppf "@[<2>method %s%s%s :@ %a@]"
(if priv then "private " else "") (if virt then "virtual " else "")
name !out_type ty
| Ocsg_value (name, mut, vr, ty) ->
fprintf ppf "@[<2>val %s%s%s :@ %a@]"
(if mut then "mutable " else "")
(if vr then "virtual " else "")
name !out_type ty
let out_class_type = ref print_out_class_type
Signature
let out_module_type = ref (fun _ -> failwith "Oprint.out_module_type")
let out_sig_item = ref (fun _ -> failwith "Oprint.out_sig_item")
let out_signature = ref (fun _ -> failwith "Oprint.out_signature")
let out_type_extension = ref (fun _ -> failwith "Oprint.out_type_extension")
let rec print_out_functor funct ppf =
function
Omty_functor (_, None, mty_res) ->
if funct then fprintf ppf "() %a" (print_out_functor true) mty_res
else fprintf ppf "functor@ () %a" (print_out_functor true) mty_res
| Omty_functor (name, Some mty_arg, mty_res) -> begin
match name, funct with
| "_", true ->
fprintf ppf "->@ %a ->@ %a"
print_out_module_type mty_arg (print_out_functor false) mty_res
| "_", false ->
fprintf ppf "%a ->@ %a"
print_out_module_type mty_arg (print_out_functor false) mty_res
| name, true ->
fprintf ppf "(%s : %a) %a" name
print_out_module_type mty_arg (print_out_functor true) mty_res
| name, false ->
fprintf ppf "functor@ (%s : %a) %a" name
print_out_module_type mty_arg (print_out_functor true) mty_res
end
| m ->
if funct then fprintf ppf "->@ %a" print_out_module_type m
else print_out_module_type ppf m
and print_out_module_type ppf =
function
Omty_abstract -> ()
| Omty_functor _ as t ->
fprintf ppf "@[<2>%a@]" (print_out_functor false) t
| Omty_ident id -> fprintf ppf "%a" print_ident id
| Omty_signature sg ->
fprintf ppf "@[<hv 2>sig@ %a@;<1 -2>end@]" !out_signature sg
| Omty_alias id -> fprintf ppf "(module %a)" print_ident id
and print_out_signature ppf =
function
[] -> ()
| [item] -> !out_sig_item ppf item
| Osig_typext(ext, Oext_first) :: items ->
let rec gather_extensions acc items =
match items with
Osig_typext(ext, Oext_next) :: items ->
gather_extensions
((ext.oext_name, ext.oext_args, ext.oext_ret_type) :: acc)
items
| _ -> (List.rev acc, items)
in
let exts, items =
gather_extensions
[(ext.oext_name, ext.oext_args, ext.oext_ret_type)]
items
in
let te =
{ otyext_name = ext.oext_type_name;
otyext_params = ext.oext_type_params;
otyext_constructors = exts;
otyext_private = ext.oext_private }
in
fprintf ppf "%a@ %a" !out_type_extension te print_out_signature items
| item :: items ->
fprintf ppf "%a@ %a" !out_sig_item item print_out_signature items
ELIOM
and side_to_string = let open Eliom_base in function
| Loc Client -> "%client"
| Loc Server -> "%server"
| Poly -> ""
and print_out_sig_item ppf sigi =
let side = side_to_string (Eliom_base.get_side ()) in
match sigi with
Osig_class (vir_flag, name, params, clt, rs) ->
fprintf ppf "@[<2>%s%s@ %a%s@ :@ %a@]"
(if vir_flag then " virtual" else "") print_out_class_params params
name !out_class_type clt
| Osig_class_type (vir_flag, name, params, clt, rs) ->
fprintf ppf "@[<2>%s%s@ %a%s@ =@ %a@]"
(if vir_flag then " virtual" else "") print_out_class_params params
name !out_class_type clt
| Osig_typext (ext, Oext_exception) ->
fprintf ppf "@[<2>exception%s %a@]"
ELIOM
print_out_constr (ext.oext_name, ext.oext_args, ext.oext_ret_type)
| Osig_typext (ext, es) ->
print_out_extension_constructor ppf ext
| Osig_modtype (name, Omty_abstract) ->
ELIOM
| Osig_modtype (name, mty) ->
ELIOM
| Osig_module (name, Omty_alias id, _) ->
ELIOM
| Osig_module (name, mty, rs) ->
fprintf ppf "@[<2>%s %s :@ %a@]"
| Orec_next -> "and")
name !out_module_type mty
| Osig_type(td, rs) ->
print_out_type_decl
(match rs with
| Orec_next -> "and")
ppf td
| Osig_value vd ->
let kwd = if vd.oval_prims = [] then "val" else "external" in
let pr_prims ppf =
function
[] -> ()
| s :: sl ->
fprintf ppf "@ = \"%s\"" s;
List.iter (fun s -> fprintf ppf "@ \"%s\"" s) sl
in
fprintf ppf "@[<2>%s%s %a :@ %a%a%a@]" kwd side value_ident vd.oval_name
!out_type vd.oval_type pr_prims vd.oval_prims
(fun ppf -> List.iter (fun a -> fprintf ppf "@ [@@@@%s]" a.oattr_name))
vd.oval_attributes
| Osig_ellipsis ->
fprintf ppf "..."
| Osig_side (side, sigi) ->
Eliom_base.in_loc side @@ fun () -> print_out_sig_item ppf sigi
and print_out_type_decl kwd ppf td =
let print_constraints ppf =
List.iter
(fun (ty1, ty2) ->
fprintf ppf "@ @[<2>constraint %a =@ %a@]" !out_type ty1
!out_type ty2)
td.otype_cstrs
in
let type_defined ppf =
match td.otype_params with
[] -> pp_print_string ppf td.otype_name
| [param] -> fprintf ppf "@[%a@ %s@]" type_parameter param td.otype_name
| _ ->
fprintf ppf "@[(@[%a)@]@ %s@]"
(print_list type_parameter (fun ppf -> fprintf ppf ",@ "))
td.otype_params
td.otype_name
in
let print_manifest ppf =
function
Otyp_manifest (ty, _) -> fprintf ppf " =@ %a" !out_type ty
| _ -> ()
in
let print_name_params ppf =
fprintf ppf "%s %t%a" kwd type_defined print_manifest td.otype_type
in
let ty =
match td.otype_type with
Otyp_manifest (_, ty) -> ty
| _ -> td.otype_type
in
let print_private ppf = function
Asttypes.Private -> fprintf ppf " private"
| Asttypes.Public -> ()
in
let print_immediate ppf =
if td.otype_immediate then fprintf ppf " [%@%@immediate]" else ()
in
let print_out_tkind ppf = function
| Otyp_abstract -> ()
| Otyp_record lbls ->
fprintf ppf " =%a %a"
print_private td.otype_private
print_record_decl lbls
| Otyp_sum constrs ->
fprintf ppf " =%a@;<1 2>%a"
print_private td.otype_private
(print_list print_out_constr (fun ppf -> fprintf ppf "@ | ")) constrs
| Otyp_open ->
fprintf ppf " = .."
| ty ->
fprintf ppf " =%a@;<1 2>%a"
print_private td.otype_private
!out_type ty
in
fprintf ppf "@[<2>@[<hv 2>%t%a@]%t%t@]"
print_name_params
print_out_tkind ty
print_constraints
print_immediate
and print_out_constr ppf (name, tyl,ret_type_opt) =
match ret_type_opt with
| None ->
begin match tyl with
| [] ->
pp_print_string ppf name
| _ ->
fprintf ppf "@[<2>%s of@ %a@]" name
(print_typlist print_simple_out_type " *") tyl
end
| Some ret_type ->
begin match tyl with
| [] ->
fprintf ppf "@[<2>%s :@ %a@]" name print_simple_out_type ret_type
| _ ->
fprintf ppf "@[<2>%s :@ %a -> %a@]" name
(print_typlist print_simple_out_type " *")
tyl print_simple_out_type ret_type
end
and print_out_extension_constructor ppf ext =
let print_extended_type ppf =
let print_type_parameter ppf ty =
fprintf ppf "%s"
(if ty = "_" then ty else "'"^ty)
in
match ext.oext_type_params with
[] -> fprintf ppf "%s" ext.oext_type_name
| [ty_param] ->
fprintf ppf "@[%a@ %s@]"
print_type_parameter
ty_param
ext.oext_type_name
| _ ->
fprintf ppf "@[(@[%a)@]@ %s@]"
(print_list print_type_parameter (fun ppf -> fprintf ppf ",@ "))
ext.oext_type_params
ext.oext_type_name
in
fprintf ppf "@[<hv 2>type %t +=%s@;<1 2>%a@]"
print_extended_type
(if ext.oext_private = Asttypes.Private then " private" else "")
print_out_constr (ext.oext_name, ext.oext_args, ext.oext_ret_type)
and print_out_type_extension ppf te =
let print_extended_type ppf =
let print_type_parameter ppf ty =
fprintf ppf "%s"
(if ty = "_" then ty else "'"^ty)
in
match te.otyext_params with
[] -> fprintf ppf "%s" te.otyext_name
| [param] ->
fprintf ppf "@[%a@ %s@]"
print_type_parameter param
te.otyext_name
| _ ->
fprintf ppf "@[(@[%a)@]@ %s@]"
(print_list print_type_parameter (fun ppf -> fprintf ppf ",@ "))
te.otyext_params
te.otyext_name
in
fprintf ppf "@[<hv 2>type %t +=%s@;<1 2>%a@]"
print_extended_type
(if te.otyext_private = Asttypes.Private then " private" else "")
(print_list print_out_constr (fun ppf -> fprintf ppf "@ | "))
te.otyext_constructors
let _ = out_module_type := print_out_module_type
let _ = out_signature := print_out_signature
let _ = out_sig_item := print_out_sig_item
let _ = out_type_extension := print_out_type_extension
let print_out_exception ppf exn outv =
match exn with
Sys.Break -> fprintf ppf "Interrupted.@."
| Out_of_memory -> fprintf ppf "Out of memory during evaluation.@."
| Stack_overflow ->
fprintf ppf "Stack overflow during evaluation (looping recursion?).@."
| _ -> fprintf ppf "@[Exception:@ %a.@]@." !out_value outv
let rec print_items ppf =
function
[] -> ()
| (Osig_typext(ext, Oext_first), None) :: items ->
let rec gather_extensions acc items =
match items with
(Osig_typext(ext, Oext_next), None) :: items ->
gather_extensions
((ext.oext_name, ext.oext_args, ext.oext_ret_type) :: acc)
items
| _ -> (List.rev acc, items)
in
let exts, items =
gather_extensions
[(ext.oext_name, ext.oext_args, ext.oext_ret_type)]
items
in
let te =
{ otyext_name = ext.oext_type_name;
otyext_params = ext.oext_type_params;
otyext_constructors = exts;
otyext_private = ext.oext_private }
in
fprintf ppf "@[%a@]" !out_type_extension te;
if items <> [] then fprintf ppf "@ %a" print_items items
| (tree, valopt) :: items ->
begin match valopt with
Some v ->
fprintf ppf "@[<2>%a =@ %a@]" !out_sig_item tree
!out_value v
| None -> fprintf ppf "@[%a@]" !out_sig_item tree
end;
if items <> [] then fprintf ppf "@ %a" print_items items
let print_out_phrase ppf =
function
Ophr_eval (outv, ty) ->
fprintf ppf "@[- : %a@ =@ %a@]@." !out_type ty !out_value outv
| Ophr_signature [] -> ()
| Ophr_signature items -> fprintf ppf "@[<v>%a@]@." print_items items
| Ophr_exception (exn, outv) -> print_out_exception ppf exn outv
let out_phrase = ref print_out_phrase
|
be2e8eb76bb95f1d199f99d3e35d0ca9a8cc35ddbbc3f7efff7a6d2def5c6858 | yutopp/rill | builtin.ml |
* Copyright 2020 - .
*
* Distributed under the Boost Software License , Version 1.0 .
* ( See accompanying file LICENSE_1_0.txt or copy at
* )
* Copyright yutopp 2020 - .
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* )
*)
module Span = Common.Span
type t = {
bool_ : span:Span.t -> Typing.Type.t;
i8_ : span:Span.t -> Typing.Type.t;
i32_ : span:Span.t -> Typing.Type.t;
i64_ : span:Span.t -> Typing.Type.t;
u64_ : span:Span.t -> Typing.Type.t;
usize_ : span:Span.t -> Typing.Type.t;
isize_ : span:Span.t -> Typing.Type.t;
string_ : span:Span.t -> Typing.Type.t;
unit_ : span:Span.t -> Typing.Type.t;
array_ : span:Span.t -> Typing.Type.t -> int -> Typing.Type.t;
pointer_ :
span:Span.t -> Typing.Type.mutability_t -> Typing.Type.t -> Typing.Type.t;
(* meta *)
type_ : span:Span.t -> Typing.Type.t -> Typing.Type.t;
}
let create () : t =
let open Typing.Type in
let binding_mut = MutMut in
let bool_ ~span =
{ ty = Num { bits = 1; signed = false }; binding_mut; span }
in
let i8_ ~span = { ty = Num { bits = 8; signed = true }; binding_mut; span } in
let i32_ ~span =
{ ty = Num { bits = 32; signed = true }; binding_mut; span }
in
let i64_ ~span =
{ ty = Num { bits = 64; signed = true }; binding_mut; span }
in
let u64_ ~span =
{ ty = Num { bits = 64; signed = false }; binding_mut; span }
in
let usize_ ~span = { ty = Size { signed = false }; binding_mut; span } in
let isize_ ~span = { ty = Size { signed = true }; binding_mut; span } in
let string_ ~span = { ty = String; binding_mut; span } in
let unit_ ~span = { ty = Unit; binding_mut; span } in
let array_ ~span elem n = { ty = Array { elem; n }; binding_mut; span } in
let pointer_ ~span mut elem =
{ ty = Pointer { mut; elem }; binding_mut; span }
in
let type_ ~span ty = { ty = Type ty; binding_mut; span } in
{
bool_;
i8_;
i32_;
i64_;
u64_;
usize_;
isize_;
string_;
unit_;
array_;
pointer_;
type_;
}
| null | https://raw.githubusercontent.com/yutopp/rill/375b67c03ab2087d0a2a833bd9e80f3e51e2694f/rillc/lib/sema/builtin.ml | ocaml | meta |
* Copyright 2020 - .
*
* Distributed under the Boost Software License , Version 1.0 .
* ( See accompanying file LICENSE_1_0.txt or copy at
* )
* Copyright yutopp 2020 - .
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* )
*)
module Span = Common.Span
type t = {
bool_ : span:Span.t -> Typing.Type.t;
i8_ : span:Span.t -> Typing.Type.t;
i32_ : span:Span.t -> Typing.Type.t;
i64_ : span:Span.t -> Typing.Type.t;
u64_ : span:Span.t -> Typing.Type.t;
usize_ : span:Span.t -> Typing.Type.t;
isize_ : span:Span.t -> Typing.Type.t;
string_ : span:Span.t -> Typing.Type.t;
unit_ : span:Span.t -> Typing.Type.t;
array_ : span:Span.t -> Typing.Type.t -> int -> Typing.Type.t;
pointer_ :
span:Span.t -> Typing.Type.mutability_t -> Typing.Type.t -> Typing.Type.t;
type_ : span:Span.t -> Typing.Type.t -> Typing.Type.t;
}
let create () : t =
let open Typing.Type in
let binding_mut = MutMut in
let bool_ ~span =
{ ty = Num { bits = 1; signed = false }; binding_mut; span }
in
let i8_ ~span = { ty = Num { bits = 8; signed = true }; binding_mut; span } in
let i32_ ~span =
{ ty = Num { bits = 32; signed = true }; binding_mut; span }
in
let i64_ ~span =
{ ty = Num { bits = 64; signed = true }; binding_mut; span }
in
let u64_ ~span =
{ ty = Num { bits = 64; signed = false }; binding_mut; span }
in
let usize_ ~span = { ty = Size { signed = false }; binding_mut; span } in
let isize_ ~span = { ty = Size { signed = true }; binding_mut; span } in
let string_ ~span = { ty = String; binding_mut; span } in
let unit_ ~span = { ty = Unit; binding_mut; span } in
let array_ ~span elem n = { ty = Array { elem; n }; binding_mut; span } in
let pointer_ ~span mut elem =
{ ty = Pointer { mut; elem }; binding_mut; span }
in
let type_ ~span ty = { ty = Type ty; binding_mut; span } in
{
bool_;
i8_;
i32_;
i64_;
u64_;
usize_;
isize_;
string_;
unit_;
array_;
pointer_;
type_;
}
|
58dec3436bf03aa76e4dc3c997466b59e2c65e2965bf01db7c5e8cf1cda80586 | marick/Midje | wrapping.clj | (ns ^{:doc "midje.background uses these to wrap extra code around
:contents, :facts, or :expects"}
midje.parsing.util.wrapping
(:require [clojure.zip :as zip]
[midje.parsing.util.core :refer :all]
[midje.util.thread-safe-var-nesting :refer [namespace-values-inside-out
set-namespace-value
with-pushed-namespace-values]]
[midje.util.unify :as unify]
[such.sequences :as seq]))
(defn midje-wrapped
"This is used to prevent later wrapping passes from processing
the code-that-produces-the-value."
[value] value)
(defn already-wrapped? [form]
(first-named? form "midje-wrapped"))
(defn multiwrap [form [wrapper & more-wrappers]]
(if wrapper
(recur (unify/inject-form wrapper form) more-wrappers)
`(midje-wrapped ~form)))
;; stashing wrapping targets
(defn wrappers []
(namespace-values-inside-out :midje/wrappers))
(defn with-wrapping-target [what target]
(vary-meta what assoc :midje/wrapping-target target))
(defn for-wrapping-target? [target]
(fn [actual]
(= target (:midje/wrapping-target (meta actual)))))
(defmacro with-additional-wrappers [final-wrappers form]
`(with-pushed-namespace-values :midje/wrappers ~final-wrappers
~form))
(defn put-wrappers-into-effect [wrappers]
(let [[immediates deferred] (seq/bifurcate (for-wrapping-target? :contents) wrappers)]
(set-namespace-value :midje/wrappers (list wrappers))
(multiwrap "unimportant-value" immediates)))
(defn forms-to-wrap-around [wrapping-target]
(filter (for-wrapping-target? wrapping-target) (wrappers)))
| null | https://raw.githubusercontent.com/marick/Midje/2b9bcb117442d3bd2d16446b47540888d683c717/src/midje/parsing/util/wrapping.clj | clojure | stashing wrapping targets | (ns ^{:doc "midje.background uses these to wrap extra code around
:contents, :facts, or :expects"}
midje.parsing.util.wrapping
(:require [clojure.zip :as zip]
[midje.parsing.util.core :refer :all]
[midje.util.thread-safe-var-nesting :refer [namespace-values-inside-out
set-namespace-value
with-pushed-namespace-values]]
[midje.util.unify :as unify]
[such.sequences :as seq]))
(defn midje-wrapped
"This is used to prevent later wrapping passes from processing
the code-that-produces-the-value."
[value] value)
(defn already-wrapped? [form]
(first-named? form "midje-wrapped"))
(defn multiwrap [form [wrapper & more-wrappers]]
(if wrapper
(recur (unify/inject-form wrapper form) more-wrappers)
`(midje-wrapped ~form)))
(defn wrappers []
(namespace-values-inside-out :midje/wrappers))
(defn with-wrapping-target [what target]
(vary-meta what assoc :midje/wrapping-target target))
(defn for-wrapping-target? [target]
(fn [actual]
(= target (:midje/wrapping-target (meta actual)))))
(defmacro with-additional-wrappers [final-wrappers form]
`(with-pushed-namespace-values :midje/wrappers ~final-wrappers
~form))
(defn put-wrappers-into-effect [wrappers]
(let [[immediates deferred] (seq/bifurcate (for-wrapping-target? :contents) wrappers)]
(set-namespace-value :midje/wrappers (list wrappers))
(multiwrap "unimportant-value" immediates)))
(defn forms-to-wrap-around [wrapping-target]
(filter (for-wrapping-target? wrapping-target) (wrappers)))
|
a6464aec87bfaec66d501404943e0b1f6d24149bd96e44fd9a3602609963d2c9 | niquola/pg3 | instance.clj | (ns pg3.instance
(:require [clj-yaml.core :as yaml]
[k8s.core :as k8s]
[clojure.string :as str]
[pg3.naming :as naming]
[pg3.model :as model]
[cheshire.core :as json]))
(defn update-status [inst status]
(k8s/patch
(assoc inst
:kind naming/instance-resource-kind
:apiVersion naming/api
:status (merge (or (:status inst) {})
{:lastUpdate (java.util.Date.)}
status))))
(defn init-instance [inst]
(let [data-v (k8s/patch (model/instance-data-volume-spec inst))
wals-v (k8s/patch (model/instance-wals-volume-spec inst))]
(update-status inst {:volumes [data-v wals-v]
:phase "waiting-volumes"})))
(defn volumes-ready? [inst]
(let [vols (get-in inst [:status :volumes])
ready? (reduce
(fn [acc v]
(let [pvc (k8s/find
(assoc v
:kind "PersistentVolumeClaim"
:apiVersion "v1"))]
(println "PVC STATUS:" (get-in pvc [:status :phase]))
(and acc (= "Bound" (get-in pvc [:status :phase])))))
true vols)]
(when ready?
(update-status inst {:phase "waiting-init"}))))
(defn init-instance [inst]
(when (= "master"
(get-in inst [:spec :role]))
TODO check status
(let [pod (model/initdb-pod inst)
res (k8s/create pod)]
(-> (yaml/generate-string)
(println))
(update-status inst {:phase "waiting-master-initdb"
:initdbPod (get-in pod [:metadata :name])}))))
(defn master-inited? [inst]
(let [pod-name (or (get-in inst [:status :initdbPod])
(get-in (model/initdb-pod inst) [:metadata :name]))
pod (k8s/find {:kind "Pod"
:apiVersion "v1"
:metadata {:name pod-name
:namespace (get-in inst [:metadata :namespace])}})
phase (get-in pod [:status :phase])]
(cond
(= "Succeeded" phase)
(update-status inst {:phase "master-ready-to-start"})
:else (println "TODO:" phase))))
(defn start-master [inst]
(println "Start master" inst)
(let [depl-spec (model/master-deployment inst)
depl (k8s/create depl-spec)]
(-> (update-status inst {:phase "master-starting"})
yaml/generate-string
println)))
(defn master-starting [inst]
TODO check deployment status
(println "master started?" inst)
(let [service-spec (model/master-service inst)
service (k8s/patch service-spec)]
(-> service
yaml/generate-string
println)
(-> (update-status inst {:phase "active"})
yaml/generate-string
println)
)
)
(defn instance-status [inst]
(println "DEFAULT: "
(get-in inst [:metadata :name])
" "
(get-in inst [:status :phase])))
(defn watch-instance [{st :status :as inst}]
(cond
(nil? st) (init-instance inst)
(= "waiting-volumes" (:phase st))
(volumes-ready? inst)
(= "waiting-init" (:phase st))
(init-instance inst)
(= "waiting-master-initdb" (:phase st))
(master-inited? inst)
(= "master-ready-to-start" (:phase st))
(start-master inst)
(= "master-starting" (:phase st))
(master-starting inst)
:else (instance-status inst)))
(defn watch-instances []
(doseq [inst (:items (k8s/query {:kind naming/instance-resource-kind :apiVersion naming/api}))]
(watch-instance inst)))
(comment
(watch-instances)
)
| null | https://raw.githubusercontent.com/niquola/pg3/5ae683813bd724fa2dad3162dcfb2b600f63bc7d/src/pg3/instance.clj | clojure | (ns pg3.instance
(:require [clj-yaml.core :as yaml]
[k8s.core :as k8s]
[clojure.string :as str]
[pg3.naming :as naming]
[pg3.model :as model]
[cheshire.core :as json]))
(defn update-status [inst status]
(k8s/patch
(assoc inst
:kind naming/instance-resource-kind
:apiVersion naming/api
:status (merge (or (:status inst) {})
{:lastUpdate (java.util.Date.)}
status))))
(defn init-instance [inst]
(let [data-v (k8s/patch (model/instance-data-volume-spec inst))
wals-v (k8s/patch (model/instance-wals-volume-spec inst))]
(update-status inst {:volumes [data-v wals-v]
:phase "waiting-volumes"})))
(defn volumes-ready? [inst]
(let [vols (get-in inst [:status :volumes])
ready? (reduce
(fn [acc v]
(let [pvc (k8s/find
(assoc v
:kind "PersistentVolumeClaim"
:apiVersion "v1"))]
(println "PVC STATUS:" (get-in pvc [:status :phase]))
(and acc (= "Bound" (get-in pvc [:status :phase])))))
true vols)]
(when ready?
(update-status inst {:phase "waiting-init"}))))
(defn init-instance [inst]
(when (= "master"
(get-in inst [:spec :role]))
TODO check status
(let [pod (model/initdb-pod inst)
res (k8s/create pod)]
(-> (yaml/generate-string)
(println))
(update-status inst {:phase "waiting-master-initdb"
:initdbPod (get-in pod [:metadata :name])}))))
(defn master-inited? [inst]
(let [pod-name (or (get-in inst [:status :initdbPod])
(get-in (model/initdb-pod inst) [:metadata :name]))
pod (k8s/find {:kind "Pod"
:apiVersion "v1"
:metadata {:name pod-name
:namespace (get-in inst [:metadata :namespace])}})
phase (get-in pod [:status :phase])]
(cond
(= "Succeeded" phase)
(update-status inst {:phase "master-ready-to-start"})
:else (println "TODO:" phase))))
(defn start-master [inst]
(println "Start master" inst)
(let [depl-spec (model/master-deployment inst)
depl (k8s/create depl-spec)]
(-> (update-status inst {:phase "master-starting"})
yaml/generate-string
println)))
(defn master-starting [inst]
TODO check deployment status
(println "master started?" inst)
(let [service-spec (model/master-service inst)
service (k8s/patch service-spec)]
(-> service
yaml/generate-string
println)
(-> (update-status inst {:phase "active"})
yaml/generate-string
println)
)
)
(defn instance-status [inst]
(println "DEFAULT: "
(get-in inst [:metadata :name])
" "
(get-in inst [:status :phase])))
(defn watch-instance [{st :status :as inst}]
(cond
(nil? st) (init-instance inst)
(= "waiting-volumes" (:phase st))
(volumes-ready? inst)
(= "waiting-init" (:phase st))
(init-instance inst)
(= "waiting-master-initdb" (:phase st))
(master-inited? inst)
(= "master-ready-to-start" (:phase st))
(start-master inst)
(= "master-starting" (:phase st))
(master-starting inst)
:else (instance-status inst)))
(defn watch-instances []
(doseq [inst (:items (k8s/query {:kind naming/instance-resource-kind :apiVersion naming/api}))]
(watch-instance inst)))
(comment
(watch-instances)
)
| |
16b8dcb1707f006b38459ad99c198ca7e69a7f33b325ab60ada2116ce530c9a0 | myuon/minilight | Resolver.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE PatternSynonyms #
# LANGUAGE ViewPatterns #
module MiniLight.Loader.Internal.Resolver where
import Control.Applicative
import Control.Monad
import Data.Aeson hiding (Result)
import qualified Data.HashMap.Strict as HM
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.Scientific (fromFloatDigits)
import qualified Data.Vector as V
import GHC.Generics (Generic)
import MiniLight.Loader.Internal.Types
import Text.Trifecta
data Expr
= None
| Ref T.Text -- ^ reference syntax: ${ref:...}
| Var T.Text -- ^ variable syntax: ${var:...}
| Op T.Text Expr Expr -- ^ expr operator: +, -, *, /
| Constant Value -- ^ constants (string or number or null)
| Symbol T.Text -- ^ token symbol
| App Expr [Expr] -- ^ function application ($func(a,b,c))
deriving (Eq, Show, Generic)
instance ToJSON Expr
instance FromJSON Expr
parser :: Parser Expr
parser = try reference <|> try variable <|> try (char '$' *> braces expr)
where
expr = chainl expr1 op1 None
expr1 = chainl expr2 op2 None
expr2 =
parens expr
<|> try apply
<|> try parameter
<|> try reference
<|> try variable
<|> try number
<|> try strlit
-- low precedence infixl operator group
op1 = Op "+" <$ textSymbol "+" <|> Op "-" <$ textSymbol "-"
-- high precedence infixl operator group
op2 = Op "*" <$ textSymbol "*" <|> Op "/" <$ textSymbol "/"
reference = char '$' *> do
braces $ text "ref:" *> (fmap (Ref . T.pack) (many (letter <|> oneOf ".")))
variable = char '$' *> do
braces $ text "var:" *> (fmap (Var . T.pack) (many (letter <|> oneOf ".")))
number = fmap (Constant . Number . either fromIntegral fromFloatDigits)
integerOrDouble
strlit = fmap (Constant . String) $ stringLiteral
parameter = char '$' *> do
fmap (Symbol . T.pack) $ (:) <$> letter <*> many (letter <|> digit)
apply = do
func <- parameter
exps <-
parens
$ option []
$ fmap (filter (/= None))
$ try
$ (:)
<$> expr
<*> expr
`sepBy` (char ',')
return $ App func exps
data Context = Context {
path :: V.Vector (Either Int T.Text),
variables :: Object,
values :: HM.HashMap T.Text Value
}
emptyContext :: Context
emptyContext = Context V.empty HM.empty HM.empty
getAt :: Value -> [Either Int T.Text] -> Either T.Text Value
getAt = go
where
go value [] = Right value
go (Object obj) (Right key:ps) | key `HM.member` obj = go (obj HM.! key) ps
go (Array arr) (Left i :ps) | 0 <= i && i < V.length arr = go (arr V.! i) ps
go v (p:_) =
Left
$ "TypeError: path `"
<> T.pack (show p)
<> "` is missing in `"
<> T.pack (show v)
<> "`"
normalize
:: V.Vector (Either Int T.Text) -> [Either Int T.Text] -> [Either Int T.Text]
normalize path1 ts = V.toList path1' ++ dropWhile (\v -> v == Right "") ts
where
depth = length $ takeWhile (\v -> v == Right "") ts
path1' = V.take (V.length path1 - depth - 1) path1
eval :: Context -> Value -> Expr -> Either T.Text Value
eval ctx target = go
where
go None = Right ""
go (Ref path') =
either (Left . (("Error in `${ref:" <> path' <> "}`\n") <>)) Right
$ getAt target (normalize (path ctx) (convertPath path'))
go (Var path') =
either (Left . (("Error in `${var:" <> path' <> "}`\n") <>)) Right
$ getAt (Object (variables ctx)) (normalize V.empty (convertPath path'))
go (Op "+" e1 e2) = runOp (+) e1 e2
go (Op "-" e1 e2) = runOp (-) e1 e2
go (Op "*" e1 e2) = runOp (*) e1 e2
go (Op "/" e1 e2) = runOp (/) e1 e2
go (Symbol t) =
maybe (Left $ "Symbol not defined: `" <> t <> "`") Right
$ HM.lookup t
$ values ctx
go expr = Left $ "Illegal expression: " <> T.pack (show expr)
runOp op e1 e2 =
fmap Number
$ join
$ (\x y -> op <$> asNumber x <*> asNumber y)
<$> go e1
<*> go e2
asNumber (Number x) = Right x
asNumber x = Left $ "Not a number: " <> T.pack (show x)
convertPath :: T.Text -> [Either Int T.Text]
convertPath =
map (\t -> either (\_ -> Right t) (Left . fromIntegral) $ parseText index t)
. T.splitOn "."
. (\t -> if T.length t > 0 && T.head t == '.' then T.tail t else t)
where index = char '[' *> natural <* char ']'
convert :: Context -> Value -> T.Text -> Either T.Text Value
convert ctx target t =
either (\_ -> Right $ String t) (eval ctx target) $ parseText parser t
parseText :: Parser a -> T.Text -> Either T.Text a
parseText parser =
foldResult (Left . T.pack . show) Right
. parseByteString parser mempty
. TE.encodeUtf8
resolveWith :: Context -> Value -> Either T.Text Value
resolveWith ctx target = go ctx target
where
go ctx (Object obj)
| "_vars" `HM.member` obj
= let vars = obj HM.! "_vars"
in go
( ctx
{ variables = HM.union ((\(Object o) -> o) $ vars) (variables ctx)
}
)
(Object (HM.delete "_vars" obj))
| otherwise
= fmap Object $ sequence $ HM.mapWithKey
(\key -> go (ctx { path = V.snoc (path ctx) (Right key) }))
obj
go ctx (Array arr) = fmap Array $ sequence $ V.imap
(\i -> go (ctx { path = V.snoc (path ctx) (Left i) }))
arr
go ctx (String t) = convert ctx target t
go _ (Number n) = Right $ Number n
go _ (Bool b) = Right $ Bool b
go _ Null = Right Null
-- | Interpret a JSON value, and unsafely apply fromRight
resolve :: Value -> Value
resolve = (\(Right a) -> a) . resolveWith emptyContext
| Create ' AppConfig ' value from JSON value
parseAppConfig :: Value -> Either T.Text AppConfig
parseAppConfig = conf (Context V.empty HM.empty HM.empty)
where
conf :: Context -> Value -> Either T.Text AppConfig
conf ctx (Object obj) | "app" `HM.member` obj =
let
ctx' = maybe
ctx
( \vars -> ctx
{ variables = HM.union ((\(Object o) -> o) vars) (variables ctx)
}
)
(HM.lookup "_vars" obj)
in
fmap (\v -> AppConfig v V.empty) $ app ctx' (obj HM.! "app")
conf _ (Object obj) =
Left $ "path `app` is missing in " <> T.pack (show (Object obj))
conf _ ast = Left $ "Invalid format: " <> T.pack (show ast)
app :: Context -> Value -> Either T.Text (V.Vector ComponentConfig)
app ctx (Array vec) = V.mapM (component ctx) vec
app _ ast = Left $ "Invalid format: " <> T.pack (show ast)
component :: Context -> Value -> Either T.Text ComponentConfig
component ctx (Object obj) | all (`HM.member` obj) ["type", "properties"] = do
let
ctx' = maybe
ctx
( \vars -> ctx
{ variables = HM.union ((\(Object o) -> o) vars) (variables ctx)
}
)
(HM.lookup "_vars" obj)
nameValue <- resolveWith ctx' (obj HM.! "type")
case nameValue of
String name -> do
props <- resolveWith ctx' (obj HM.! "properties")
hooks <-
sequence
$ (fmap (\(Object o) -> mapM toHook o) $ HM.lookup "hooks" obj)
Right $ ComponentConfig name
(fmap (\(String s) -> s) $ HM.lookup "id" obj)
props
hooks
_ -> Left $ "Invalid format: " <> T.pack (show nameValue)
component _ ast = Left $ "Invalid format: " <> T.pack (show ast)
| null | https://raw.githubusercontent.com/myuon/minilight/3c6a4f6b9ed15c97c7de02a281c31152442fb4d7/src/MiniLight/Loader/Internal/Resolver.hs | haskell | ^ reference syntax: ${ref:...}
^ variable syntax: ${var:...}
^ expr operator: +, -, *, /
^ constants (string or number or null)
^ token symbol
^ function application ($func(a,b,c))
low precedence infixl operator group
high precedence infixl operator group
| Interpret a JSON value, and unsafely apply fromRight | # LANGUAGE DeriveGeneric #
# LANGUAGE PatternSynonyms #
# LANGUAGE ViewPatterns #
module MiniLight.Loader.Internal.Resolver where
import Control.Applicative
import Control.Monad
import Data.Aeson hiding (Result)
import qualified Data.HashMap.Strict as HM
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.Scientific (fromFloatDigits)
import qualified Data.Vector as V
import GHC.Generics (Generic)
import MiniLight.Loader.Internal.Types
import Text.Trifecta
data Expr
= None
deriving (Eq, Show, Generic)
instance ToJSON Expr
instance FromJSON Expr
parser :: Parser Expr
parser = try reference <|> try variable <|> try (char '$' *> braces expr)
where
expr = chainl expr1 op1 None
expr1 = chainl expr2 op2 None
expr2 =
parens expr
<|> try apply
<|> try parameter
<|> try reference
<|> try variable
<|> try number
<|> try strlit
op1 = Op "+" <$ textSymbol "+" <|> Op "-" <$ textSymbol "-"
op2 = Op "*" <$ textSymbol "*" <|> Op "/" <$ textSymbol "/"
reference = char '$' *> do
braces $ text "ref:" *> (fmap (Ref . T.pack) (many (letter <|> oneOf ".")))
variable = char '$' *> do
braces $ text "var:" *> (fmap (Var . T.pack) (many (letter <|> oneOf ".")))
number = fmap (Constant . Number . either fromIntegral fromFloatDigits)
integerOrDouble
strlit = fmap (Constant . String) $ stringLiteral
parameter = char '$' *> do
fmap (Symbol . T.pack) $ (:) <$> letter <*> many (letter <|> digit)
apply = do
func <- parameter
exps <-
parens
$ option []
$ fmap (filter (/= None))
$ try
$ (:)
<$> expr
<*> expr
`sepBy` (char ',')
return $ App func exps
data Context = Context {
path :: V.Vector (Either Int T.Text),
variables :: Object,
values :: HM.HashMap T.Text Value
}
emptyContext :: Context
emptyContext = Context V.empty HM.empty HM.empty
getAt :: Value -> [Either Int T.Text] -> Either T.Text Value
getAt = go
where
go value [] = Right value
go (Object obj) (Right key:ps) | key `HM.member` obj = go (obj HM.! key) ps
go (Array arr) (Left i :ps) | 0 <= i && i < V.length arr = go (arr V.! i) ps
go v (p:_) =
Left
$ "TypeError: path `"
<> T.pack (show p)
<> "` is missing in `"
<> T.pack (show v)
<> "`"
normalize
:: V.Vector (Either Int T.Text) -> [Either Int T.Text] -> [Either Int T.Text]
normalize path1 ts = V.toList path1' ++ dropWhile (\v -> v == Right "") ts
where
depth = length $ takeWhile (\v -> v == Right "") ts
path1' = V.take (V.length path1 - depth - 1) path1
eval :: Context -> Value -> Expr -> Either T.Text Value
eval ctx target = go
where
go None = Right ""
go (Ref path') =
either (Left . (("Error in `${ref:" <> path' <> "}`\n") <>)) Right
$ getAt target (normalize (path ctx) (convertPath path'))
go (Var path') =
either (Left . (("Error in `${var:" <> path' <> "}`\n") <>)) Right
$ getAt (Object (variables ctx)) (normalize V.empty (convertPath path'))
go (Op "+" e1 e2) = runOp (+) e1 e2
go (Op "-" e1 e2) = runOp (-) e1 e2
go (Op "*" e1 e2) = runOp (*) e1 e2
go (Op "/" e1 e2) = runOp (/) e1 e2
go (Symbol t) =
maybe (Left $ "Symbol not defined: `" <> t <> "`") Right
$ HM.lookup t
$ values ctx
go expr = Left $ "Illegal expression: " <> T.pack (show expr)
runOp op e1 e2 =
fmap Number
$ join
$ (\x y -> op <$> asNumber x <*> asNumber y)
<$> go e1
<*> go e2
asNumber (Number x) = Right x
asNumber x = Left $ "Not a number: " <> T.pack (show x)
convertPath :: T.Text -> [Either Int T.Text]
convertPath =
map (\t -> either (\_ -> Right t) (Left . fromIntegral) $ parseText index t)
. T.splitOn "."
. (\t -> if T.length t > 0 && T.head t == '.' then T.tail t else t)
where index = char '[' *> natural <* char ']'
convert :: Context -> Value -> T.Text -> Either T.Text Value
convert ctx target t =
either (\_ -> Right $ String t) (eval ctx target) $ parseText parser t
parseText :: Parser a -> T.Text -> Either T.Text a
parseText parser =
foldResult (Left . T.pack . show) Right
. parseByteString parser mempty
. TE.encodeUtf8
resolveWith :: Context -> Value -> Either T.Text Value
resolveWith ctx target = go ctx target
where
go ctx (Object obj)
| "_vars" `HM.member` obj
= let vars = obj HM.! "_vars"
in go
( ctx
{ variables = HM.union ((\(Object o) -> o) $ vars) (variables ctx)
}
)
(Object (HM.delete "_vars" obj))
| otherwise
= fmap Object $ sequence $ HM.mapWithKey
(\key -> go (ctx { path = V.snoc (path ctx) (Right key) }))
obj
go ctx (Array arr) = fmap Array $ sequence $ V.imap
(\i -> go (ctx { path = V.snoc (path ctx) (Left i) }))
arr
go ctx (String t) = convert ctx target t
go _ (Number n) = Right $ Number n
go _ (Bool b) = Right $ Bool b
go _ Null = Right Null
resolve :: Value -> Value
resolve = (\(Right a) -> a) . resolveWith emptyContext
| Create ' AppConfig ' value from JSON value
parseAppConfig :: Value -> Either T.Text AppConfig
parseAppConfig = conf (Context V.empty HM.empty HM.empty)
where
conf :: Context -> Value -> Either T.Text AppConfig
conf ctx (Object obj) | "app" `HM.member` obj =
let
ctx' = maybe
ctx
( \vars -> ctx
{ variables = HM.union ((\(Object o) -> o) vars) (variables ctx)
}
)
(HM.lookup "_vars" obj)
in
fmap (\v -> AppConfig v V.empty) $ app ctx' (obj HM.! "app")
conf _ (Object obj) =
Left $ "path `app` is missing in " <> T.pack (show (Object obj))
conf _ ast = Left $ "Invalid format: " <> T.pack (show ast)
app :: Context -> Value -> Either T.Text (V.Vector ComponentConfig)
app ctx (Array vec) = V.mapM (component ctx) vec
app _ ast = Left $ "Invalid format: " <> T.pack (show ast)
component :: Context -> Value -> Either T.Text ComponentConfig
component ctx (Object obj) | all (`HM.member` obj) ["type", "properties"] = do
let
ctx' = maybe
ctx
( \vars -> ctx
{ variables = HM.union ((\(Object o) -> o) vars) (variables ctx)
}
)
(HM.lookup "_vars" obj)
nameValue <- resolveWith ctx' (obj HM.! "type")
case nameValue of
String name -> do
props <- resolveWith ctx' (obj HM.! "properties")
hooks <-
sequence
$ (fmap (\(Object o) -> mapM toHook o) $ HM.lookup "hooks" obj)
Right $ ComponentConfig name
(fmap (\(String s) -> s) $ HM.lookup "id" obj)
props
hooks
_ -> Left $ "Invalid format: " <> T.pack (show nameValue)
component _ ast = Left $ "Invalid format: " <> T.pack (show ast)
|
368dbc7c20e6687fbae9203b25d7d9840fe37cc90e93df30aec1a58bd884ebc4 | orchid-hybrid/microKanren-sagittarius | chicken.scm | (include "./srfi/95.sld")
(include "./test-check.sld")
(include "./miruKanren/kanren.sld")
(include "./miruKanren/utils.sld")
(include "./miruKanren/variables.sld")
(include "./miruKanren/monad.sld")
(include "./miruKanren/micro.sld")
(include "./miruKanren/mini.sld")
(include "./miruKanren/streams.sld")
(include "./miruKanren/unification.sld")
(include "./miruKanren/reification.sld")
(include "./miruKanren/run.sld")
(include "./miruKanren/disequality.sld")
(include "./miruKanren/eqeq-diseq.sld")
(include "./miruKanren/mk-diseq.sld")
(include "./miruKanren/eqeq.sld")
(include "./miruKanren/bijections.sld")
(include "./miruKanren/sorted-int-set.sld")
(include "./miruKanren/type.sld")
(include "./miruKanren/surveillance.sld")
(include "./miruKanren/eqeq-watch.sld")
(include "./miruKanren/mk-watch.sld")
(include "./miruKanren/eqeq-typeo.sld")
(include "./miruKanren/mk-basic.sld")
(include "./miruKanren/mk-types.sld")
(include "./miruKanren/copy-term.sld")
(include "./miruKanren/table.sld")
| null | https://raw.githubusercontent.com/orchid-hybrid/microKanren-sagittarius/9e740bbf94ed2930f88bbcf32636d3480934cfbb/chicken.scm | scheme | (include "./srfi/95.sld")
(include "./test-check.sld")
(include "./miruKanren/kanren.sld")
(include "./miruKanren/utils.sld")
(include "./miruKanren/variables.sld")
(include "./miruKanren/monad.sld")
(include "./miruKanren/micro.sld")
(include "./miruKanren/mini.sld")
(include "./miruKanren/streams.sld")
(include "./miruKanren/unification.sld")
(include "./miruKanren/reification.sld")
(include "./miruKanren/run.sld")
(include "./miruKanren/disequality.sld")
(include "./miruKanren/eqeq-diseq.sld")
(include "./miruKanren/mk-diseq.sld")
(include "./miruKanren/eqeq.sld")
(include "./miruKanren/bijections.sld")
(include "./miruKanren/sorted-int-set.sld")
(include "./miruKanren/type.sld")
(include "./miruKanren/surveillance.sld")
(include "./miruKanren/eqeq-watch.sld")
(include "./miruKanren/mk-watch.sld")
(include "./miruKanren/eqeq-typeo.sld")
(include "./miruKanren/mk-basic.sld")
(include "./miruKanren/mk-types.sld")
(include "./miruKanren/copy-term.sld")
(include "./miruKanren/table.sld")
| |
0215dc77f6f6e7967ffd5158cea446deb0e3a6486417ee00d4a82f515972eef0 | TOTBWF/teenytt | Tactic.hs | -- | Bidirectional Tactic for Elaboration
module TeenyTT.Elaborator.Tactic (
-- * Type Formation Tactics
Tp(..)
, runTp
-- * Check Tactics
, Chk(..)
, runChk
, chk
, match
-- * Synthesis Tactics
, Syn(..)
, runSyn
, ann
, observe
-- * Tactic Class
, Tactic(..)
) where
import TeenyTT.Base.Location
import TeenyTT.Core.Syntax qualified as S
import TeenyTT.Core.Domain qualified as D
import TeenyTT.Elaborator.Monad
class Tactic tac where
failure :: (forall a. ElabM a) -> tac
updateSpan :: Span -> tac -> tac
--------------------------------------------------------------------------------
-- Type Tactics
newtype Tp = Tp { unTp :: ElabM S.Type }
# INLINE runTp #
runTp :: Tp -> ElabM S.Type
runTp tac = tac.unTp
instance Tactic Tp where
failure err = Tp err
updateSpan sp (Tp m) = Tp $ withSpan sp m
--------------------------------------------------------------------------------
-- Check Tactics
newtype Chk = Chk { unChk :: D.Type -> ElabM S.Term }
# INLINE runChk #
runChk :: Chk -> D.Type -> ElabM S.Term
runChk tac = tac.unChk
instance Tactic Chk where
failure err = Chk \_ -> err
updateSpan sp (Chk k) = Chk \goal -> withSpan sp (k goal)
# INLINE chk #
chk :: Syn -> Chk
chk tac = Chk \goal -> do
(tm, vtp) <- runSyn tac
equateTp goal vtp
pure tm
failChk :: (forall a. ElabM a) -> Chk
failChk m = Chk \_ -> m
match :: (D.Type -> ElabM Chk) -> Chk
match k = Chk \goal -> do
tac <- k goal
runChk tac goal
--------------------------------------------------------------------------------
Synthesis Tactics
newtype Syn = Syn { unSyn :: ElabM (S.Term, D.Type) }
# INLINE runSyn #
runSyn :: Syn -> ElabM (S.Term, D.Type)
runSyn tac = tac.unSyn
instance Tactic Syn where
failure err = Syn err
updateSpan sp (Syn m) = Syn (withSpan sp m)
ann :: Chk -> Tp -> Syn
ann tac tpTac = Syn do
tp <- runTp tpTac
vtp <- evalTp tp
tm <- runChk tac vtp
pure (tm, vtp)
observe :: Syn -> (S.Term -> D.Type -> ElabM Syn) -> Syn
observe synTac k = Syn do
(tm, vtp) <- runSyn synTac
tac <- k tm vtp
runSyn tac
| null | https://raw.githubusercontent.com/TOTBWF/teenytt/b1363fe78183bb13ea447056a10ef1eac72dbff1/src/TeenyTT/Elaborator/Tactic.hs | haskell | | Bidirectional Tactic for Elaboration
* Type Formation Tactics
* Check Tactics
* Synthesis Tactics
* Tactic Class
------------------------------------------------------------------------------
Type Tactics
------------------------------------------------------------------------------
Check Tactics
------------------------------------------------------------------------------ | module TeenyTT.Elaborator.Tactic (
Tp(..)
, runTp
, Chk(..)
, runChk
, chk
, match
, Syn(..)
, runSyn
, ann
, observe
, Tactic(..)
) where
import TeenyTT.Base.Location
import TeenyTT.Core.Syntax qualified as S
import TeenyTT.Core.Domain qualified as D
import TeenyTT.Elaborator.Monad
class Tactic tac where
failure :: (forall a. ElabM a) -> tac
updateSpan :: Span -> tac -> tac
newtype Tp = Tp { unTp :: ElabM S.Type }
# INLINE runTp #
runTp :: Tp -> ElabM S.Type
runTp tac = tac.unTp
instance Tactic Tp where
failure err = Tp err
updateSpan sp (Tp m) = Tp $ withSpan sp m
newtype Chk = Chk { unChk :: D.Type -> ElabM S.Term }
# INLINE runChk #
runChk :: Chk -> D.Type -> ElabM S.Term
runChk tac = tac.unChk
instance Tactic Chk where
failure err = Chk \_ -> err
updateSpan sp (Chk k) = Chk \goal -> withSpan sp (k goal)
# INLINE chk #
chk :: Syn -> Chk
chk tac = Chk \goal -> do
(tm, vtp) <- runSyn tac
equateTp goal vtp
pure tm
failChk :: (forall a. ElabM a) -> Chk
failChk m = Chk \_ -> m
match :: (D.Type -> ElabM Chk) -> Chk
match k = Chk \goal -> do
tac <- k goal
runChk tac goal
Synthesis Tactics
newtype Syn = Syn { unSyn :: ElabM (S.Term, D.Type) }
# INLINE runSyn #
runSyn :: Syn -> ElabM (S.Term, D.Type)
runSyn tac = tac.unSyn
instance Tactic Syn where
failure err = Syn err
updateSpan sp (Syn m) = Syn (withSpan sp m)
ann :: Chk -> Tp -> Syn
ann tac tpTac = Syn do
tp <- runTp tpTac
vtp <- evalTp tp
tm <- runChk tac vtp
pure (tm, vtp)
observe :: Syn -> (S.Term -> D.Type -> ElabM Syn) -> Syn
observe synTac k = Syn do
(tm, vtp) <- runSyn synTac
tac <- k tm vtp
runSyn tac
|
260983b05c05a3ad615c991dd9d6c1163f6183d85ebf882b03f70089e35ba870 | uim/sigscheme | test-srfi43.scm | Filename : test-srfi43.scm
;; About : unit tests for SRFI-43
;;
Copyright ( c ) 2007 - 2008 SigScheme Project < uim - en AT googlegroups.com >
;;
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
1 . Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
2 . Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
3 . Neither the name of authors nor the names of its contributors
;; may be used to endorse or promote products derived from this software
;; without specific prior written permission.
;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS
;; IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
;; THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
;; PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
;; CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(require-extension (unittest) (srfi 43))
(test-begin "let-vector-start+end invalid forms")
(define vec (vector 'foo 'bar 'baz))
;; nonexistent <callee>
(test-error (let-vector-start+end nonexistent vec '() (start end) #t))
;; invalid <vector>
(test-error (let-vector-start+end vector-ref '() '() (start end) #t))
(test-error (let-vector-start+end vector-ref #f '() (start end) #t))
;; invalid <args>
(test-error (let-vector-start+end vector-ref vec '(#t) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(0 #t) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(0 1 2) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '#() (start end) #t))
(test-error (let-vector-start+end vector-ref vec #f (start end) #t))
;; malformed bindings
(test-error (let-vector-start+end vector-ref vec '() () #t))
(test-error (let-vector-start+end vector-ref vec '() (start) #t))
(test-error (let-vector-start+end vector-ref vec '() (start end extra) #t))
(test-error (let-vector-start+end vector-ref vec '() '(start end) #t))
(test-error (let-vector-start+end vector-ref vec '() #() #t))
(test-error (let-vector-start+end vector-ref vec '() '#() #t))
;; no body
(test-error (let-vector-start+end vector-ref vec '() (start end)))
(test-end)
(test-begin "let-vector-start+end null vector")
(test-error (let-vector-start+end vector-ref '#() '(-1) (start end) #t))
(test-equal '(0 0)
(let-vector-start+end vector-ref '#() '() (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref '#() '(0) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref '#() '(0 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref '#() '(0 0) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref '#() '(0 1) (start end) #t))
(test-error (let-vector-start+end vector-ref '#() '(1) (start end) #t))
(test-error (let-vector-start+end vector-ref '#() '(1 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref '#() '(1 0) (start end) #t))
(test-error (let-vector-start+end vector-ref '#() '(1 1) (start end) #t))
(test-end)
(test-begin "let-vector-start+end length 1")
(define vec (vector 'foo))
(test-error (let-vector-start+end vector-ref vec '(-1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 0) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 2) (start end) #t))
(test-equal '(0 1)
(let-vector-start+end vector-ref vec '() (start end)
(list start end)))
(test-equal '(0 1)
(let-vector-start+end vector-ref vec '(0) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(0 -1) (start end) #t))
(test-equal '(0 0)
(let-vector-start+end vector-ref vec '(0 0) (start end)
(list start end)))
(test-equal '(0 1)
(let-vector-start+end vector-ref vec '(0 1) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(0 2) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(1 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(1 0) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(1 1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(1 2) (start end) #t))
(test-end)
(test-begin "let-vector-start+end length 2")
(define vec (vector 'foo 'bar))
(test-error (let-vector-start+end vector-ref vec '(-1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 0) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 2) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 3) (start end) #t))
(test-equal '(0 2)
(let-vector-start+end vector-ref vec '() (start end)
(list start end)))
(test-equal '(0 2)
(let-vector-start+end vector-ref vec '(0) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(0 -1) (start end) #t))
(test-equal '(0 0)
(let-vector-start+end vector-ref vec '(0 0) (start end)
(list start end)))
(test-equal '(0 1)
(let-vector-start+end vector-ref vec '(0 1) (start end)
(list start end)))
(test-equal '(0 2)
(let-vector-start+end vector-ref vec '(0 2) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(0 3) (start end) #t))
(test-equal '(1 2)
(let-vector-start+end vector-ref vec '(1) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(1 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(1 0) (start end) #t))
(test-equal '(1 1)
(let-vector-start+end vector-ref vec '(1 1) (start end)
(list start end)))
(test-equal '(1 2)
(let-vector-start+end vector-ref vec '(1 2) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(1 3) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(2) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(2 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(2 0) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(2 1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(2 2) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(2 3) (start end) #t))
(test-end)
(test-begin "let-vector-start+end length 3")
(define vec (vector 'foo 'bar 'baz))
(test-error (let-vector-start+end vector-ref vec '(-1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 0) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 2) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 3) (start end) #t))
(test-equal '(0 3)
(let-vector-start+end vector-ref vec '() (start end)
(list start end)))
(test-equal '(0 3)
(let-vector-start+end vector-ref vec '(0) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(0 -1) (start end) #t))
(test-equal '(0 0)
(let-vector-start+end vector-ref vec '(0 0) (start end)
(list start end)))
(test-equal '(0 1)
(let-vector-start+end vector-ref vec '(0 1) (start end)
(list start end)))
(test-equal '(0 2)
(let-vector-start+end vector-ref vec '(0 2) (start end)
(list start end)))
(test-equal '(0 3)
(let-vector-start+end vector-ref vec '(0 3) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(0 4) (start end) #t))
(test-equal '(1 3)
(let-vector-start+end vector-ref vec '(1) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(1 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(1 0) (start end) #t))
(test-equal '(1 1)
(let-vector-start+end vector-ref vec '(1 1) (start end)
(list start end)))
(test-equal '(1 2)
(let-vector-start+end vector-ref vec '(1 2) (start end)
(list start end)))
(test-equal '(1 3)
(let-vector-start+end vector-ref vec '(1 3) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(1 4) (start end) #t))
(test-equal '(2 3)
(let-vector-start+end vector-ref vec '(2) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(2 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(2 0) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(2 1) (start end) #t))
(test-equal '(2 2)
(let-vector-start+end vector-ref vec '(2 2) (start end)
(list start end)))
(test-equal '(2 3)
(let-vector-start+end vector-ref vec '(2 3) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(2 4) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(3) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(3 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(3 0) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(3 1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(3 2) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(3 3) (start end) #t))
(test-end)
;; Test real let-vector-start+end use.
(test-begin "vector->list R5RS")
(test-equal '()
(vector->list '#()))
(test-equal '(0 1 2 3 4)
(vector->list '#(0 1 2 3 4)))
(test-end)
(test-begin "vector->list with start index")
(test-error (vector->list '#(0 1 2 3 4) -1))
(test-equal '(0 1 2 3 4)
(vector->list '#(0 1 2 3 4) 0))
(test-equal '(1 2 3 4)
(vector->list '#(0 1 2 3 4) 1))
(test-equal '(2 3 4)
(vector->list '#(0 1 2 3 4) 2))
(test-equal '(3 4)
(vector->list '#(0 1 2 3 4) 3))
(test-equal '(4)
(vector->list '#(0 1 2 3 4) 4))
(cond-expand
(gauche
(test-equal '()
(vector->list '#(0 1 2 3 4) 5)))
(else
(test-error (vector->list '#(0 1 2 3 4) 5))))
(test-error (vector->list '#(0 1 2 3 4) 6))
(test-end)
(test-begin "vector->list with start and end index")
(test-error (vector->list '#(0 1 2 3 4) 0 -1))
(test-equal '()
(vector->list '#(0 1 2 3 4) 0 0))
(test-equal '(0)
(vector->list '#(0 1 2 3 4) 0 1))
(test-equal '(0 1)
(vector->list '#(0 1 2 3 4) 0 2))
(test-equal '(0 1 2 3 4)
(vector->list '#(0 1 2 3 4) 0 5))
(test-error (vector->list '#(0 1 2 3 4) 0 6))
(test-error (vector->list '#(0 1 2 3 4) 1 0))
(test-equal '()
(vector->list '#(0 1 2 3 4) 1 1))
(test-equal '(1)
(vector->list '#(0 1 2 3 4) 1 2))
(test-equal '(1 2)
(vector->list '#(0 1 2 3 4) 1 3))
(test-equal '(1 2 3 4)
(vector->list '#(0 1 2 3 4) 1 5))
(test-error (vector->list '#(0 1 2 3 4) 4 3))
(test-equal '()
(vector->list '#(0 1 2 3 4) 4 4))
(test-equal '(4)
(vector->list '#(0 1 2 3 4) 4 5))
(cond-expand
(gauche
(test-equal '()
(vector->list '#(0 1 2 3 4) 5 5)))
(else
(test-error (vector->list '#(0 1 2 3 4) 5 5))))
(test-end)
(test-report-result)
| null | https://raw.githubusercontent.com/uim/sigscheme/ccf1f92d6c2a0f45c15d93da82e399c2a78fe5f3/test/test-srfi43.scm | scheme | About : unit tests for SRFI-43
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
may be used to endorse or promote products derived from this software
without specific prior written permission.
IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
LOSS OF USE , DATA , OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
nonexistent <callee>
invalid <vector>
invalid <args>
malformed bindings
no body
Test real let-vector-start+end use. | Filename : test-srfi43.scm
Copyright ( c ) 2007 - 2008 SigScheme Project < uim - en AT googlegroups.com >
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
3 . Neither the name of authors nor the names of its contributors
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS
EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
(require-extension (unittest) (srfi 43))
(test-begin "let-vector-start+end invalid forms")
(define vec (vector 'foo 'bar 'baz))
(test-error (let-vector-start+end nonexistent vec '() (start end) #t))
(test-error (let-vector-start+end vector-ref '() '() (start end) #t))
(test-error (let-vector-start+end vector-ref #f '() (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(#t) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(0 #t) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(0 1 2) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '#() (start end) #t))
(test-error (let-vector-start+end vector-ref vec #f (start end) #t))
(test-error (let-vector-start+end vector-ref vec '() () #t))
(test-error (let-vector-start+end vector-ref vec '() (start) #t))
(test-error (let-vector-start+end vector-ref vec '() (start end extra) #t))
(test-error (let-vector-start+end vector-ref vec '() '(start end) #t))
(test-error (let-vector-start+end vector-ref vec '() #() #t))
(test-error (let-vector-start+end vector-ref vec '() '#() #t))
(test-error (let-vector-start+end vector-ref vec '() (start end)))
(test-end)
(test-begin "let-vector-start+end null vector")
(test-error (let-vector-start+end vector-ref '#() '(-1) (start end) #t))
(test-equal '(0 0)
(let-vector-start+end vector-ref '#() '() (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref '#() '(0) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref '#() '(0 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref '#() '(0 0) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref '#() '(0 1) (start end) #t))
(test-error (let-vector-start+end vector-ref '#() '(1) (start end) #t))
(test-error (let-vector-start+end vector-ref '#() '(1 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref '#() '(1 0) (start end) #t))
(test-error (let-vector-start+end vector-ref '#() '(1 1) (start end) #t))
(test-end)
(test-begin "let-vector-start+end length 1")
(define vec (vector 'foo))
(test-error (let-vector-start+end vector-ref vec '(-1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 0) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 2) (start end) #t))
(test-equal '(0 1)
(let-vector-start+end vector-ref vec '() (start end)
(list start end)))
(test-equal '(0 1)
(let-vector-start+end vector-ref vec '(0) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(0 -1) (start end) #t))
(test-equal '(0 0)
(let-vector-start+end vector-ref vec '(0 0) (start end)
(list start end)))
(test-equal '(0 1)
(let-vector-start+end vector-ref vec '(0 1) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(0 2) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(1 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(1 0) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(1 1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(1 2) (start end) #t))
(test-end)
(test-begin "let-vector-start+end length 2")
(define vec (vector 'foo 'bar))
(test-error (let-vector-start+end vector-ref vec '(-1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 0) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 2) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 3) (start end) #t))
(test-equal '(0 2)
(let-vector-start+end vector-ref vec '() (start end)
(list start end)))
(test-equal '(0 2)
(let-vector-start+end vector-ref vec '(0) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(0 -1) (start end) #t))
(test-equal '(0 0)
(let-vector-start+end vector-ref vec '(0 0) (start end)
(list start end)))
(test-equal '(0 1)
(let-vector-start+end vector-ref vec '(0 1) (start end)
(list start end)))
(test-equal '(0 2)
(let-vector-start+end vector-ref vec '(0 2) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(0 3) (start end) #t))
(test-equal '(1 2)
(let-vector-start+end vector-ref vec '(1) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(1 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(1 0) (start end) #t))
(test-equal '(1 1)
(let-vector-start+end vector-ref vec '(1 1) (start end)
(list start end)))
(test-equal '(1 2)
(let-vector-start+end vector-ref vec '(1 2) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(1 3) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(2) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(2 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(2 0) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(2 1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(2 2) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(2 3) (start end) #t))
(test-end)
(test-begin "let-vector-start+end length 3")
(define vec (vector 'foo 'bar 'baz))
(test-error (let-vector-start+end vector-ref vec '(-1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 0) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 2) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(-1 3) (start end) #t))
(test-equal '(0 3)
(let-vector-start+end vector-ref vec '() (start end)
(list start end)))
(test-equal '(0 3)
(let-vector-start+end vector-ref vec '(0) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(0 -1) (start end) #t))
(test-equal '(0 0)
(let-vector-start+end vector-ref vec '(0 0) (start end)
(list start end)))
(test-equal '(0 1)
(let-vector-start+end vector-ref vec '(0 1) (start end)
(list start end)))
(test-equal '(0 2)
(let-vector-start+end vector-ref vec '(0 2) (start end)
(list start end)))
(test-equal '(0 3)
(let-vector-start+end vector-ref vec '(0 3) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(0 4) (start end) #t))
(test-equal '(1 3)
(let-vector-start+end vector-ref vec '(1) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(1 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(1 0) (start end) #t))
(test-equal '(1 1)
(let-vector-start+end vector-ref vec '(1 1) (start end)
(list start end)))
(test-equal '(1 2)
(let-vector-start+end vector-ref vec '(1 2) (start end)
(list start end)))
(test-equal '(1 3)
(let-vector-start+end vector-ref vec '(1 3) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(1 4) (start end) #t))
(test-equal '(2 3)
(let-vector-start+end vector-ref vec '(2) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(2 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(2 0) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(2 1) (start end) #t))
(test-equal '(2 2)
(let-vector-start+end vector-ref vec '(2 2) (start end)
(list start end)))
(test-equal '(2 3)
(let-vector-start+end vector-ref vec '(2 3) (start end)
(list start end)))
(test-error (let-vector-start+end vector-ref vec '(2 4) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(3) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(3 -1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(3 0) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(3 1) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(3 2) (start end) #t))
(test-error (let-vector-start+end vector-ref vec '(3 3) (start end) #t))
(test-end)
(test-begin "vector->list R5RS")
(test-equal '()
(vector->list '#()))
(test-equal '(0 1 2 3 4)
(vector->list '#(0 1 2 3 4)))
(test-end)
(test-begin "vector->list with start index")
(test-error (vector->list '#(0 1 2 3 4) -1))
(test-equal '(0 1 2 3 4)
(vector->list '#(0 1 2 3 4) 0))
(test-equal '(1 2 3 4)
(vector->list '#(0 1 2 3 4) 1))
(test-equal '(2 3 4)
(vector->list '#(0 1 2 3 4) 2))
(test-equal '(3 4)
(vector->list '#(0 1 2 3 4) 3))
(test-equal '(4)
(vector->list '#(0 1 2 3 4) 4))
(cond-expand
(gauche
(test-equal '()
(vector->list '#(0 1 2 3 4) 5)))
(else
(test-error (vector->list '#(0 1 2 3 4) 5))))
(test-error (vector->list '#(0 1 2 3 4) 6))
(test-end)
(test-begin "vector->list with start and end index")
(test-error (vector->list '#(0 1 2 3 4) 0 -1))
(test-equal '()
(vector->list '#(0 1 2 3 4) 0 0))
(test-equal '(0)
(vector->list '#(0 1 2 3 4) 0 1))
(test-equal '(0 1)
(vector->list '#(0 1 2 3 4) 0 2))
(test-equal '(0 1 2 3 4)
(vector->list '#(0 1 2 3 4) 0 5))
(test-error (vector->list '#(0 1 2 3 4) 0 6))
(test-error (vector->list '#(0 1 2 3 4) 1 0))
(test-equal '()
(vector->list '#(0 1 2 3 4) 1 1))
(test-equal '(1)
(vector->list '#(0 1 2 3 4) 1 2))
(test-equal '(1 2)
(vector->list '#(0 1 2 3 4) 1 3))
(test-equal '(1 2 3 4)
(vector->list '#(0 1 2 3 4) 1 5))
(test-error (vector->list '#(0 1 2 3 4) 4 3))
(test-equal '()
(vector->list '#(0 1 2 3 4) 4 4))
(test-equal '(4)
(vector->list '#(0 1 2 3 4) 4 5))
(cond-expand
(gauche
(test-equal '()
(vector->list '#(0 1 2 3 4) 5 5)))
(else
(test-error (vector->list '#(0 1 2 3 4) 5 5))))
(test-end)
(test-report-result)
|
a766b643530636710db6140408179c2a51061c6a114a34fb1610bcaf100bcff7 | migae/datastore | emap.clj | (ns test.emap
(:refer-clojure :exclude [name hash])
(:import [com.google.appengine.tools.development.testing
LocalServiceTestHelper
LocalServiceTestConfig
LocalMemcacheServiceTestConfig
LocalMemcacheServiceTestConfig$SizeUnit
LocalMailServiceTestConfig
LocalDatastoreServiceTestConfig
LocalUserServiceTestConfig]
[com.google.apphosting.api ApiProxy]
[com.google.appengine.api.datastore
EntityNotFoundException])
;; (:use [clj-logging-config.log4j])
(:require [clojure.test :refer :all]
[migae.datastore :as em]
[clojure.tools.logging :as log :only [trace debug info]]))
; [ring-zombie.core :as zombie]))
(defmacro should-fail [body]
`(let [report-type# (atom nil)]
(binding [clojure.test/report #(reset! report-type# (:type %))]
~body)
(testing "should fail"
(is (= @report-type# :fail )))))
;; (defn- make-local-services-fixture-fn [services hook-helper]
(defn- ds-fixture
[test-fn]
environment ( ApiProxy / getCurrentEnvironment )
delegate ( ApiProxy / getDelegate )
helper (LocalServiceTestHelper.
(into-array LocalServiceTestConfig
[(LocalDatastoreServiceTestConfig.)]))]
(do
(.setUp helper)
;; (em/init)
(test-fn)
(.tearDown helper))))
( ApiProxy / setEnvironmentForCurrentThread environment )
( ApiProxy / setDelegate delegate ) ) ) )
;(use-fixtures :once (fn [test-fn] (dss/get-datastore-service) (test-fn)))
(use-fixtures :each ds-fixture)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; entity-map create funcs
;; ! throw exception if already exists
;; ?-! ignore em arg if already exists
;; ?+! merge em arg if already exists
;; !! replace if existant (i.e. discard existing)
(deftest ^:entity-map entity-map!
(testing "Duplicate Key Exception"
(em/entity-map! [:Foo/Bar] {})
(let [e (try (em/entity-map! [:Foo/Bar] {})
(catch java.lang.Exception x (Throwable->map x)))]
(is (= (:cause e) "DuplicateKeyException")))))
;; (catch EntityNotFoundException e
;; (throw e)))
;; (is (= (try (em/entity-map?? [:A/B 'C/D])
( catch IllegalArgumentException e
;; (log/trace "Exception:" (.getMessage e))
;; (.getClass e)))
IllegalArgumentException ) )
;; ))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; ; FIXME
;; ;; (deftest ^:entity-map entity-map??
;; ;; (testing "entity-map?!"
; ; ( try ( em / entity - map ? ? ] )
;; ;; (catch EntityNotFoundException ex))
;; ;; ))
(deftest ^:entity-map entity-map1
(testing "entity-map key vector must not be empty"
(let [e (try (em/entity-map [] {})
(catch java.lang.IllegalArgumentException ex ex))]
(is (= "Null keychain '[]' not allowed for local ctor"
(.getMessage e))))))
(deftest ^:entity-map entity-map?
(testing "entitymap deftype"
(binding [*print-meta* true]
(let [em1 (em/entity-map [:Species/Felis_catus] {:name "Chibi"})
em2 (em/entity-map [:Genus/d99 :Species/Felis_catus] {:name "Chibi"})
em2b (em/entity-map [(keyword "Genus" "999") :Species/Felis_catus] {:name "Chibi"})
em2c (em/entity-map [:Genus/Felis :Species/Felis_catus] {:name "Chibi"})
em3 (em/entity-map [:Subfamily/Felinae :Genus/Felis :Species/Felis_catus] {:name "Chibi"})
em4 (em/entity-map [:Family/Felidae :Subfamily/Felinae :Genus/Felis :Species/Felis_catus] {:name "Chibi"})]
(log/trace "em1" em1)
(is (em/entity-map? em1))
(log/trace "em2" em2)
(is (em/entity-map? em2))
(log/trace "em3" em3)
(is (em/entity-map? em3))
(log/trace "em4" em4)
(is (em/entity-map? em4))
))))
(deftest ^:entity-map entity-map?!
(testing "entitymap deftype"
(binding [*print-meta* true]
(let [em1 (em/entity-map! [:Species/Felis_catus] {})
em2 (em/entity-map [:Genus/Felis :Species/Felis_catus] {})
em3 (em/entity-map [:Subfamily/Felinae :Genus/Felis :Species/Felis_catus] {})
em4 (em/entity-map [:Family/Felidae :Subfamily/Felinae :Genus/Felis :Species/Felis_catus] {})]
(is (em/entity-map? em1))
(is (em/entity-map? em2))
(is (em/entity-map? em3))
(is (em/entity-map? em4)))
(let [k [:Genus/Felis :Species/Felis_catus]]
;; FIXME: support this stuff?
( log / trace " ? ! " ( em / entity - map ? ! k { : name " " : size " small " : eyes 1 } ) )
; ; ( try ( em / entity - map ? ! k { : name " " : size " small " : eyes 1 } )
;; ;; (catch Exception e (log/trace "Exception:" (.getMessage e))))
;; ;; =? override maybe
( log / trace " = ? " ( em / entity - map= ? k { : name " " : size " large " } ) )
;; ;; +? - extend maybe
( log / trace " + ? " ( em / entity - map+ ? k { : name " " : size " large " : foo " bar " } ) )
;; ;; =! - override necessarily
( log / trace " = ! " ( em / entity - map= ! k { : name " " : size " large " } ) )
;; ;; !! - replace necessarily i.e. discard old and create new
( log / trace " ! ! " ( em / entity - map ! k { : name " " : size " medium " } ) )
;; ;; ?? - find maybe
;; (log/trace "??" (em/entity-map?? k))
)
)))
(deftest ^:emap emap-axioms
(testing "entity-map axioms"
(let [em1 (em/entity-map [:Species/Felis_catus] {:name "Chibi"})
]
(log/info "em1" (em/dump em1))
(log/info "em1 type:" (type em1))
(log/info "em1 kind:" (em/kind em1))
(log/info "em1 ident:" (em/identifier em1) " (type: " (type (em/identifier em1)) ")")
(log/info "em1 keychain:" (em/keychain em1))
(log/info "em1 keychain type:" (type (em/keychain em1)))
;; FIXME (log/info "em1 key:" (key em1))
;; FIXME (log/info "em1 key type:" (type (key em1)))
FIXME ( log / info " em1 content : " ( ) )
FIXME ( log / info " em1 content type : " ( type ( ) ) )
(is (em/entity-map? em1))
)))
(deftest ^:entity-map entity-map-props-1
(testing "entity-map! with properties"
;; (binding [*print-meta* true]
(let [k [:Genus/Felis :Species/Felis_catus]
_ (log/info "k:" k)
e1 (em/entity-map! k {:name "Chibi" :size "small" :eyes 1})
e2 (em/entity-map* k)
]
(log/info "e1: " e1 " type: " (type e1))
(log/info "e1 entity" (.content e1))
(log/info "e2: " e2 " type: " (type e2))
(log/info "e2 entity" (.content e2))
(flush)
(is (= (e1 :name) "Chibi"))
(is (= (e2 :name) "Chibi"))
;; (should-fail (is (= e1 e2)))
(is (em/keychains=? e1 e2))
)))
#_(deftest ^:entity-map entity-map-fetch
(testing "entity-map! new, update, replace"
;; ignore new if exists
(let [em1 (em/entity-map! [:Species/Felis_catus] {:name "Chibi"})]
FIXME : implement support for : or , meaning : fetch if exists , otherwise create and save
em2 ( em / entity - map ! : or [: Species / Felis_catus ] { : name " " } ) ]
( is ( em / ? ) )
( is (= ( get em1 : name ) " " ) )
( is (= ( get em2 : name ) " " ) )
)
;; ! do not override existing
( let [ em2 ( em / entity - map ! [: Species / Felis_catus ] { : name " " } ) ]
;; (log/trace "em2 " em2)
( is (= (: name ) " " ) ) )
;; ;; !! - update existing
( let [ em3 ( em / entity - map ! [: Species / Felis_catus ] { : name " " } )
em3 ( em / entity - map ! [: Species / Felis_catus ] { : name 4 } ) ]
;; (log/trace "em3 " em3)
( is (= (: name em3 ) [ " Chibi " , " Booger " 4 ] ) )
( is (= ( first (: name em3 ) ) " " ) ) )
;; ;; replace existing
( let [ ( em / alter ! [: Species / Felis_catus ] { : name " " } ) ]
( log / trace " " )
( is (= (: name ) " " ) ) )
;; (let [em5 (em/entity-map! [:Species/Felis_catus :Name/Chibi]
{ : name " " : size " small " : eyes 1 } )
;; em6 (em/alter! [:Species/Felis_catus :Name/Booger]
{ : name " " : size " lg " : eyes 2 } ) ]
;; (log/trace "em5" em5)
;; (log/trace "em6" em6))
))
#_(deftest ^:entity-map entity-map-fn
(testing "entity-map fn"
(let [em1 (em/entity-map! [:Species/Felis_catus] {:name "Chibi"})]
(log/trace em1))
))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
NB : the entity - maps ! family does not ( yet ) create entities
;; (deftest ^:entity-map entity-maps
;; (testing "entity-maps"
( let [ em1 ( em / entity - maps ! : Species ( > = : weight 5 ) )
; ; em2 ( em / entity - maps ! : Species ( and ( > = : weight 5 )
; ; ( < = : weight 7 ) ) )
;; ]
;; (log/trace em1)
;; )))
;;(run-tests)
| null | https://raw.githubusercontent.com/migae/datastore/61b2fc243cfd95956d531a57c86ea58eb19af7b7/test/clj/test/emap.clj | clojure | (:use [clj-logging-config.log4j])
[ring-zombie.core :as zombie]))
(defn- make-local-services-fixture-fn [services hook-helper]
(em/init)
(use-fixtures :once (fn [test-fn] (dss/get-datastore-service) (test-fn)))
entity-map create funcs
! throw exception if already exists
?-! ignore em arg if already exists
?+! merge em arg if already exists
!! replace if existant (i.e. discard existing)
(catch EntityNotFoundException e
(throw e)))
(is (= (try (em/entity-map?? [:A/B 'C/D])
(log/trace "Exception:" (.getMessage e))
(.getClass e)))
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; FIXME
;; (deftest ^:entity-map entity-map??
;; (testing "entity-map?!"
; ( try ( em / entity - map ? ? ] )
;; (catch EntityNotFoundException ex))
;; ))
FIXME: support this stuff?
; ( try ( em / entity - map ? ! k { : name " " : size " small " : eyes 1 } )
;; (catch Exception e (log/trace "Exception:" (.getMessage e))))
;; =? override maybe
;; +? - extend maybe
;; =! - override necessarily
;; !! - replace necessarily i.e. discard old and create new
;; ?? - find maybe
(log/trace "??" (em/entity-map?? k))
FIXME (log/info "em1 key:" (key em1))
FIXME (log/info "em1 key type:" (type (key em1)))
(binding [*print-meta* true]
(should-fail (is (= e1 e2)))
ignore new if exists
! do not override existing
(log/trace "em2 " em2)
;; !! - update existing
(log/trace "em3 " em3)
;; replace existing
(let [em5 (em/entity-map! [:Species/Felis_catus :Name/Chibi]
em6 (em/alter! [:Species/Felis_catus :Name/Booger]
(log/trace "em5" em5)
(log/trace "em6" em6))
(deftest ^:entity-map entity-maps
(testing "entity-maps"
; em2 ( em / entity - maps ! : Species ( and ( > = : weight 5 )
; ( < = : weight 7 ) ) )
]
(log/trace em1)
)))
(run-tests) | (ns test.emap
(:refer-clojure :exclude [name hash])
(:import [com.google.appengine.tools.development.testing
LocalServiceTestHelper
LocalServiceTestConfig
LocalMemcacheServiceTestConfig
LocalMemcacheServiceTestConfig$SizeUnit
LocalMailServiceTestConfig
LocalDatastoreServiceTestConfig
LocalUserServiceTestConfig]
[com.google.apphosting.api ApiProxy]
[com.google.appengine.api.datastore
EntityNotFoundException])
(:require [clojure.test :refer :all]
[migae.datastore :as em]
[clojure.tools.logging :as log :only [trace debug info]]))
(defmacro should-fail [body]
`(let [report-type# (atom nil)]
(binding [clojure.test/report #(reset! report-type# (:type %))]
~body)
(testing "should fail"
(is (= @report-type# :fail )))))
(defn- ds-fixture
[test-fn]
environment ( ApiProxy / getCurrentEnvironment )
delegate ( ApiProxy / getDelegate )
helper (LocalServiceTestHelper.
(into-array LocalServiceTestConfig
[(LocalDatastoreServiceTestConfig.)]))]
(do
(.setUp helper)
(test-fn)
(.tearDown helper))))
( ApiProxy / setEnvironmentForCurrentThread environment )
( ApiProxy / setDelegate delegate ) ) ) )
(use-fixtures :each ds-fixture)
(deftest ^:entity-map entity-map!
(testing "Duplicate Key Exception"
(em/entity-map! [:Foo/Bar] {})
(let [e (try (em/entity-map! [:Foo/Bar] {})
(catch java.lang.Exception x (Throwable->map x)))]
(is (= (:cause e) "DuplicateKeyException")))))
( catch IllegalArgumentException e
IllegalArgumentException ) )
(deftest ^:entity-map entity-map1
(testing "entity-map key vector must not be empty"
(let [e (try (em/entity-map [] {})
(catch java.lang.IllegalArgumentException ex ex))]
(is (= "Null keychain '[]' not allowed for local ctor"
(.getMessage e))))))
(deftest ^:entity-map entity-map?
(testing "entitymap deftype"
(binding [*print-meta* true]
(let [em1 (em/entity-map [:Species/Felis_catus] {:name "Chibi"})
em2 (em/entity-map [:Genus/d99 :Species/Felis_catus] {:name "Chibi"})
em2b (em/entity-map [(keyword "Genus" "999") :Species/Felis_catus] {:name "Chibi"})
em2c (em/entity-map [:Genus/Felis :Species/Felis_catus] {:name "Chibi"})
em3 (em/entity-map [:Subfamily/Felinae :Genus/Felis :Species/Felis_catus] {:name "Chibi"})
em4 (em/entity-map [:Family/Felidae :Subfamily/Felinae :Genus/Felis :Species/Felis_catus] {:name "Chibi"})]
(log/trace "em1" em1)
(is (em/entity-map? em1))
(log/trace "em2" em2)
(is (em/entity-map? em2))
(log/trace "em3" em3)
(is (em/entity-map? em3))
(log/trace "em4" em4)
(is (em/entity-map? em4))
))))
(deftest ^:entity-map entity-map?!
(testing "entitymap deftype"
(binding [*print-meta* true]
(let [em1 (em/entity-map! [:Species/Felis_catus] {})
em2 (em/entity-map [:Genus/Felis :Species/Felis_catus] {})
em3 (em/entity-map [:Subfamily/Felinae :Genus/Felis :Species/Felis_catus] {})
em4 (em/entity-map [:Family/Felidae :Subfamily/Felinae :Genus/Felis :Species/Felis_catus] {})]
(is (em/entity-map? em1))
(is (em/entity-map? em2))
(is (em/entity-map? em3))
(is (em/entity-map? em4)))
(let [k [:Genus/Felis :Species/Felis_catus]]
( log / trace " ? ! " ( em / entity - map ? ! k { : name " " : size " small " : eyes 1 } ) )
( log / trace " = ? " ( em / entity - map= ? k { : name " " : size " large " } ) )
( log / trace " + ? " ( em / entity - map+ ? k { : name " " : size " large " : foo " bar " } ) )
( log / trace " = ! " ( em / entity - map= ! k { : name " " : size " large " } ) )
( log / trace " ! ! " ( em / entity - map ! k { : name " " : size " medium " } ) )
)
)))
(deftest ^:emap emap-axioms
(testing "entity-map axioms"
(let [em1 (em/entity-map [:Species/Felis_catus] {:name "Chibi"})
]
(log/info "em1" (em/dump em1))
(log/info "em1 type:" (type em1))
(log/info "em1 kind:" (em/kind em1))
(log/info "em1 ident:" (em/identifier em1) " (type: " (type (em/identifier em1)) ")")
(log/info "em1 keychain:" (em/keychain em1))
(log/info "em1 keychain type:" (type (em/keychain em1)))
FIXME ( log / info " em1 content : " ( ) )
FIXME ( log / info " em1 content type : " ( type ( ) ) )
(is (em/entity-map? em1))
)))
(deftest ^:entity-map entity-map-props-1
(testing "entity-map! with properties"
(let [k [:Genus/Felis :Species/Felis_catus]
_ (log/info "k:" k)
e1 (em/entity-map! k {:name "Chibi" :size "small" :eyes 1})
e2 (em/entity-map* k)
]
(log/info "e1: " e1 " type: " (type e1))
(log/info "e1 entity" (.content e1))
(log/info "e2: " e2 " type: " (type e2))
(log/info "e2 entity" (.content e2))
(flush)
(is (= (e1 :name) "Chibi"))
(is (= (e2 :name) "Chibi"))
(is (em/keychains=? e1 e2))
)))
#_(deftest ^:entity-map entity-map-fetch
(testing "entity-map! new, update, replace"
(let [em1 (em/entity-map! [:Species/Felis_catus] {:name "Chibi"})]
FIXME : implement support for : or , meaning : fetch if exists , otherwise create and save
em2 ( em / entity - map ! : or [: Species / Felis_catus ] { : name " " } ) ]
( is ( em / ? ) )
( is (= ( get em1 : name ) " " ) )
( is (= ( get em2 : name ) " " ) )
)
( let [ em2 ( em / entity - map ! [: Species / Felis_catus ] { : name " " } ) ]
( is (= (: name ) " " ) ) )
( let [ em3 ( em / entity - map ! [: Species / Felis_catus ] { : name " " } )
em3 ( em / entity - map ! [: Species / Felis_catus ] { : name 4 } ) ]
( is (= (: name em3 ) [ " Chibi " , " Booger " 4 ] ) )
( is (= ( first (: name em3 ) ) " " ) ) )
( let [ ( em / alter ! [: Species / Felis_catus ] { : name " " } ) ]
( log / trace " " )
( is (= (: name ) " " ) ) )
{ : name " " : size " small " : eyes 1 } )
{ : name " " : size " lg " : eyes 2 } ) ]
))
#_(deftest ^:entity-map entity-map-fn
(testing "entity-map fn"
(let [em1 (em/entity-map! [:Species/Felis_catus] {:name "Chibi"})]
(log/trace em1))
))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
NB : the entity - maps ! family does not ( yet ) create entities
( let [ em1 ( em / entity - maps ! : Species ( > = : weight 5 ) )
|
8d138a1e62b741c6ad530018bb267ae6e0837bca7c1534c1b530d9f58c0b008e | spechub/Hets | Prove.hs | # LANGUAGE CPP #
|
Module : ./VSE / Prove.hs
Description : Interface to the VSE prover
Copyright : ( c ) , DFKI 2008
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : needs POSIX
call an adaption of VSE II to hets
Module : ./VSE/Prove.hs
Description : Interface to the VSE prover
Copyright : (c) C. Maeder, DFKI 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : needs POSIX
call an adaption of VSE II to hets
-}
module VSE.Prove where
import Logic.Prover
import VSE.As
import VSE.Ana
import VSE.ToSExpr
import Common.AS_Annotation
import Common.IO
import Common.ProverTools
import Common.SExpr
import Common.Utils
import Data.Char
import Data.Maybe
import Data.List
import qualified Data.Map as Map
import System.Process
import System.IO
import Text.ParserCombinators.Parsec
#ifdef TAR_PACKAGE
import Control.Monad
import System.Directory
import qualified Codec.Archive.Tar as Tar
#endif
vseProverName :: String
vseProverName = "VSE"
mkVseProofStatus :: String -> [String] -> ProofStatus ()
mkVseProofStatus n axs = (openProofStatus n vseProverName ())
{ goalStatus = Proved True
, usedAxioms = axs }
vse :: Prover VSESign Sentence VSEMor () ()
vse = (mkProverTemplate vseProverName () prove)
{ proverUsable = vseBinary >>= checkBinary }
nameP :: String
nameP = "SPECIFICATION-NAMES"
linksP :: String
linksP = "IN-LINKS"
sigP :: String
sigP = "SIG"
lemsP :: String
lemsP = "LEMMABASE"
prx :: String -> String
prx = ("(API::GET-" ++)
data MaybeChar = Wait | Stop | JustChar Char
vseErrFile :: String
vseErrFile = "hetsvse.out"
readUntilMatchParen :: ProcessHandle -> Handle -> String -> IO String
readUntilMatchParen = readUntilMatchParenAux 10000
readUntilMatchParenAux :: Int -> ProcessHandle -> Handle -> String -> IO String
readUntilMatchParenAux n cp h str =
let os = length $ filter (== '(') str
cs = length $ filter (== ')') str
in if n < 1 then do
appendFile vseErrFile $ "readUntilMatchParen failed after\n" ++ str ++ "\n"
return ""
else if os == cs && os > 0 then return str
else do
mc <- myGetChar cp h
case mc of
Wait -> do
appendFile vseErrFile "waiting for character ...\n"
readUntilMatchParenAux (n - 1) cp h str
Stop -> return str
JustChar c -> readUntilMatchParen cp h $ c : str
myGetChar :: ProcessHandle -> Handle -> IO MaybeChar
myGetChar cp h = do
mc <- catchIOException Wait (fmap JustChar $ hGetChar h)
case mc of
Wait -> do
ms <- getProcessExitCode cp
return $ case ms of
Nothing -> mc
Just _ -> Stop
_ -> return mc
readMyMsg :: ProcessHandle -> Handle -> String -> IO String
readMyMsg = readMyMsgAux 1000
readMyMsgAux :: Int -> ProcessHandle -> Handle -> String -> IO String
readMyMsgAux n cp h expect = if n < 1 then do
appendFile vseErrFile $ "gave up waiting for: " ++ expect ++ "\n"
return ""
else do
mc <- myGetChar cp h
case mc of
Wait -> do
appendFile vseErrFile "waiting for first character ...\n"
readMyMsgAux (n - 1) cp h expect
Stop -> return ""
JustChar c -> do
r <- readUntilMatchParen cp h [c]
let rr = reverse r
if isPrefixOf (prx expect) $ dropWhile (/= '(') rr
then return rr else do
appendFile vseErrFile $ "waiting for '" ++ expect ++ "' got:\n" ++ rr
++ "\ntrying again\n"
readMyMsgAux (n - 1) cp h expect -- try again
sendMyMsg :: Handle -> String -> IO ()
sendMyMsg cp str = catchIOException () $ hPutStrLn cp str >> hFlush cp
readRest :: ProcessHandle -> Handle -> String -> IO String
readRest cp out str = do
mc <- myGetChar cp out
case mc of
Wait -> readRest cp out str
Stop -> return str
JustChar c -> readRest cp out $ c : str
parseSymbol :: Parser SExpr
parseSymbol = skipWhite
$ fmap SSymbol $ many1 $ satisfy $ \ c -> not (isSpace c || elem c "()")
parseList :: Parser SExpr
parseList = do
skipWhite $ char '('
l <- many parseSExpr
skipWhite $ char ')'
return $ SList l
parseSExpr :: Parser SExpr
parseSExpr = parseList <|> parseSymbol
skipWhite :: Parser a -> Parser a
skipWhite p = do
a <- p
spaces
return a
skipJunk :: Parser ()
skipJunk = skipMany $ satisfy (/= '(')
parseSExprs :: Parser [SExpr]
parseSExprs = do
skipJunk
sepEndBy parseSExpr skipJunk
findState :: SExpr -> Maybe (String, String)
findState sexpr = case sexpr of
SList (SSymbol "API::SET-SENTENCE" : SSymbol nodeStr :
SList (SSymbol "API::ASENTENCE" : SSymbol senStr :
SSymbol "API::OBLIGATION" : SSymbol "API::PROVED" : _) : _)
| isPrefixOf "API::" nodeStr && isPrefixOf "API::" senStr
-> Just (drop 5 nodeStr, drop 5 senStr)
_ -> Nothing
specDir :: String
specDir = "specifications"
allSpecFile :: String
allSpecFile = "all-specifications"
allSpecInDir :: String
allSpecInDir = specDir ++ "/" ++ allSpecFile
#ifdef TAR_PACKAGE
createVSETarFile :: FilePath -> IO ()
createVSETarFile tar = do
hasSpecDir <- doesDirectoryExist specDir
hasAllSpecFile <- doesFileExist allSpecFile
if (hasSpecDir && hasAllSpecFile) then do
renameFile allSpecFile allSpecInDir
Tar.create (tar ++ ".tar") "" [specDir]
else putStrLn $ "hetsvse did not create: "
++ if hasSpecDir then allSpecFile else specDir
moveVSEFiles :: FilePath -> IO ()
moveVSEFiles str = do
let tarFile = str ++ ".tar"
hasTarFile <- doesFileExist tarFile
hasSpecDir <- doesDirectoryExist specDir
hasAllSpecFile <- doesFileExist allSpecFile
when (hasSpecDir && hasAllSpecFile) $ do
createVSETarFile (specDir ++ ".bak")
removeDirectoryRecursive specDir
when hasTarFile $ do
Tar.extract "" tarFile
renameFile allSpecInDir allSpecFile
#endif
vseBinary :: IO String
vseBinary = getEnvDef "HETS_VSE" "hetsvse"
prepareAndCallVSE :: IO (Handle, Handle, ProcessHandle)
prepareAndCallVSE = do
vseBin <- vseBinary
(inp, out, _, cp) <-
runInteractiveProcess vseBin ["-std"] Nothing Nothing
readMyMsg cp out nameP
return (inp, out, cp)
readFinalVSEOutput :: ProcessHandle -> Handle
-> IO (Maybe (Map.Map String [String]))
readFinalVSEOutput cp out = do
ms <- getProcessExitCode cp
case ms of
Just _ -> do
appendFile vseErrFile "hetsvse unavailable\n"
return Nothing
Nothing -> do
revres <- readRest cp out ""
let res = reverse revres
writeFile "hetsvse-debug.txt" res
case parse parseSExprs vseErrFile res of
Right l -> return $ Just $ readLemmas l
Left e -> do
print e
appendFile vseErrFile $ res ++ "\n"
return Nothing
readLemmas :: [SExpr] -> Map.Map String [String]
readLemmas =
foldr (\ (node, sen) -> Map.insertWith (++) node [sen]) Map.empty
. mapMaybe findState
prove :: String -> Theory VSESign Sentence () -> a -> IO [ProofStatus ()]
prove ostr (Theory sig thsens) _freedefs = do
let str = map (\ c -> if c == '/' then '-' else c) ostr
oSens = toNamedList thsens
(fsig, sens) = addUniformRestr sig oSens
(disAxs, disGoals) = partition isAxiom oSens
rMap = Map.fromList $ map (\ SenAttr { senAttr = n } ->
(map toUpper $ transString n, n)) disGoals
#ifdef TAR_PACKAGE
moveVSEFiles str
#endif
(inp, out, cp) <- prepareAndCallVSE
sendMyMsg inp $ "(" ++ str ++ ")"
readMyMsg cp out linksP
sendMyMsg inp "nil"
readMyMsg cp out sigP
sendMyMsg inp $ show $ prettySExpr $ vseSignToSExpr fsig
readMyMsg cp out lemsP
sendMyMsg inp $ show $ prettySExpr $ SList $ map (namedSenToSExpr fsig) sens
ms <- readFinalVSEOutput cp out
#ifdef TAR_PACKAGE
createVSETarFile str
#endif
case ms of
Nothing -> return []
Just lemMap -> return
$ foldr (\ s r -> case Map.lookup s rMap of
Nothing -> r
Just n -> mkVseProofStatus n (map senAttr disAxs) : r) []
$ Map.findWithDefault [] (map toUpper str) lemMap
| null | https://raw.githubusercontent.com/spechub/Hets/af7b628a75aab0d510b8ae7f067a5c9bc48d0f9e/VSE/Prove.hs | haskell | try again | # LANGUAGE CPP #
|
Module : ./VSE / Prove.hs
Description : Interface to the VSE prover
Copyright : ( c ) , DFKI 2008
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : needs POSIX
call an adaption of VSE II to hets
Module : ./VSE/Prove.hs
Description : Interface to the VSE prover
Copyright : (c) C. Maeder, DFKI 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : needs POSIX
call an adaption of VSE II to hets
-}
module VSE.Prove where
import Logic.Prover
import VSE.As
import VSE.Ana
import VSE.ToSExpr
import Common.AS_Annotation
import Common.IO
import Common.ProverTools
import Common.SExpr
import Common.Utils
import Data.Char
import Data.Maybe
import Data.List
import qualified Data.Map as Map
import System.Process
import System.IO
import Text.ParserCombinators.Parsec
#ifdef TAR_PACKAGE
import Control.Monad
import System.Directory
import qualified Codec.Archive.Tar as Tar
#endif
vseProverName :: String
vseProverName = "VSE"
mkVseProofStatus :: String -> [String] -> ProofStatus ()
mkVseProofStatus n axs = (openProofStatus n vseProverName ())
{ goalStatus = Proved True
, usedAxioms = axs }
vse :: Prover VSESign Sentence VSEMor () ()
vse = (mkProverTemplate vseProverName () prove)
{ proverUsable = vseBinary >>= checkBinary }
nameP :: String
nameP = "SPECIFICATION-NAMES"
linksP :: String
linksP = "IN-LINKS"
sigP :: String
sigP = "SIG"
lemsP :: String
lemsP = "LEMMABASE"
prx :: String -> String
prx = ("(API::GET-" ++)
data MaybeChar = Wait | Stop | JustChar Char
vseErrFile :: String
vseErrFile = "hetsvse.out"
readUntilMatchParen :: ProcessHandle -> Handle -> String -> IO String
readUntilMatchParen = readUntilMatchParenAux 10000
readUntilMatchParenAux :: Int -> ProcessHandle -> Handle -> String -> IO String
readUntilMatchParenAux n cp h str =
let os = length $ filter (== '(') str
cs = length $ filter (== ')') str
in if n < 1 then do
appendFile vseErrFile $ "readUntilMatchParen failed after\n" ++ str ++ "\n"
return ""
else if os == cs && os > 0 then return str
else do
mc <- myGetChar cp h
case mc of
Wait -> do
appendFile vseErrFile "waiting for character ...\n"
readUntilMatchParenAux (n - 1) cp h str
Stop -> return str
JustChar c -> readUntilMatchParen cp h $ c : str
myGetChar :: ProcessHandle -> Handle -> IO MaybeChar
myGetChar cp h = do
mc <- catchIOException Wait (fmap JustChar $ hGetChar h)
case mc of
Wait -> do
ms <- getProcessExitCode cp
return $ case ms of
Nothing -> mc
Just _ -> Stop
_ -> return mc
readMyMsg :: ProcessHandle -> Handle -> String -> IO String
readMyMsg = readMyMsgAux 1000
readMyMsgAux :: Int -> ProcessHandle -> Handle -> String -> IO String
readMyMsgAux n cp h expect = if n < 1 then do
appendFile vseErrFile $ "gave up waiting for: " ++ expect ++ "\n"
return ""
else do
mc <- myGetChar cp h
case mc of
Wait -> do
appendFile vseErrFile "waiting for first character ...\n"
readMyMsgAux (n - 1) cp h expect
Stop -> return ""
JustChar c -> do
r <- readUntilMatchParen cp h [c]
let rr = reverse r
if isPrefixOf (prx expect) $ dropWhile (/= '(') rr
then return rr else do
appendFile vseErrFile $ "waiting for '" ++ expect ++ "' got:\n" ++ rr
++ "\ntrying again\n"
sendMyMsg :: Handle -> String -> IO ()
sendMyMsg cp str = catchIOException () $ hPutStrLn cp str >> hFlush cp
readRest :: ProcessHandle -> Handle -> String -> IO String
readRest cp out str = do
mc <- myGetChar cp out
case mc of
Wait -> readRest cp out str
Stop -> return str
JustChar c -> readRest cp out $ c : str
parseSymbol :: Parser SExpr
parseSymbol = skipWhite
$ fmap SSymbol $ many1 $ satisfy $ \ c -> not (isSpace c || elem c "()")
parseList :: Parser SExpr
parseList = do
skipWhite $ char '('
l <- many parseSExpr
skipWhite $ char ')'
return $ SList l
parseSExpr :: Parser SExpr
parseSExpr = parseList <|> parseSymbol
skipWhite :: Parser a -> Parser a
skipWhite p = do
a <- p
spaces
return a
skipJunk :: Parser ()
skipJunk = skipMany $ satisfy (/= '(')
parseSExprs :: Parser [SExpr]
parseSExprs = do
skipJunk
sepEndBy parseSExpr skipJunk
findState :: SExpr -> Maybe (String, String)
findState sexpr = case sexpr of
SList (SSymbol "API::SET-SENTENCE" : SSymbol nodeStr :
SList (SSymbol "API::ASENTENCE" : SSymbol senStr :
SSymbol "API::OBLIGATION" : SSymbol "API::PROVED" : _) : _)
| isPrefixOf "API::" nodeStr && isPrefixOf "API::" senStr
-> Just (drop 5 nodeStr, drop 5 senStr)
_ -> Nothing
specDir :: String
specDir = "specifications"
allSpecFile :: String
allSpecFile = "all-specifications"
allSpecInDir :: String
allSpecInDir = specDir ++ "/" ++ allSpecFile
#ifdef TAR_PACKAGE
createVSETarFile :: FilePath -> IO ()
createVSETarFile tar = do
hasSpecDir <- doesDirectoryExist specDir
hasAllSpecFile <- doesFileExist allSpecFile
if (hasSpecDir && hasAllSpecFile) then do
renameFile allSpecFile allSpecInDir
Tar.create (tar ++ ".tar") "" [specDir]
else putStrLn $ "hetsvse did not create: "
++ if hasSpecDir then allSpecFile else specDir
moveVSEFiles :: FilePath -> IO ()
moveVSEFiles str = do
let tarFile = str ++ ".tar"
hasTarFile <- doesFileExist tarFile
hasSpecDir <- doesDirectoryExist specDir
hasAllSpecFile <- doesFileExist allSpecFile
when (hasSpecDir && hasAllSpecFile) $ do
createVSETarFile (specDir ++ ".bak")
removeDirectoryRecursive specDir
when hasTarFile $ do
Tar.extract "" tarFile
renameFile allSpecInDir allSpecFile
#endif
vseBinary :: IO String
vseBinary = getEnvDef "HETS_VSE" "hetsvse"
prepareAndCallVSE :: IO (Handle, Handle, ProcessHandle)
prepareAndCallVSE = do
vseBin <- vseBinary
(inp, out, _, cp) <-
runInteractiveProcess vseBin ["-std"] Nothing Nothing
readMyMsg cp out nameP
return (inp, out, cp)
readFinalVSEOutput :: ProcessHandle -> Handle
-> IO (Maybe (Map.Map String [String]))
readFinalVSEOutput cp out = do
ms <- getProcessExitCode cp
case ms of
Just _ -> do
appendFile vseErrFile "hetsvse unavailable\n"
return Nothing
Nothing -> do
revres <- readRest cp out ""
let res = reverse revres
writeFile "hetsvse-debug.txt" res
case parse parseSExprs vseErrFile res of
Right l -> return $ Just $ readLemmas l
Left e -> do
print e
appendFile vseErrFile $ res ++ "\n"
return Nothing
readLemmas :: [SExpr] -> Map.Map String [String]
readLemmas =
foldr (\ (node, sen) -> Map.insertWith (++) node [sen]) Map.empty
. mapMaybe findState
prove :: String -> Theory VSESign Sentence () -> a -> IO [ProofStatus ()]
prove ostr (Theory sig thsens) _freedefs = do
let str = map (\ c -> if c == '/' then '-' else c) ostr
oSens = toNamedList thsens
(fsig, sens) = addUniformRestr sig oSens
(disAxs, disGoals) = partition isAxiom oSens
rMap = Map.fromList $ map (\ SenAttr { senAttr = n } ->
(map toUpper $ transString n, n)) disGoals
#ifdef TAR_PACKAGE
moveVSEFiles str
#endif
(inp, out, cp) <- prepareAndCallVSE
sendMyMsg inp $ "(" ++ str ++ ")"
readMyMsg cp out linksP
sendMyMsg inp "nil"
readMyMsg cp out sigP
sendMyMsg inp $ show $ prettySExpr $ vseSignToSExpr fsig
readMyMsg cp out lemsP
sendMyMsg inp $ show $ prettySExpr $ SList $ map (namedSenToSExpr fsig) sens
ms <- readFinalVSEOutput cp out
#ifdef TAR_PACKAGE
createVSETarFile str
#endif
case ms of
Nothing -> return []
Just lemMap -> return
$ foldr (\ s r -> case Map.lookup s rMap of
Nothing -> r
Just n -> mkVseProofStatus n (map senAttr disAxs) : r) []
$ Map.findWithDefault [] (map toUpper str) lemMap
|
257277f9d49363445ac1a542e596242089874e9b0adb6826e6ebb1b2017b41ad | eslick/cl-registry | presentation-protocol.lisp | (in-package :registry)
;;;; * web presentations
nominally we 'd use a protocl based object system here , but CLOS
;;;; is fine.
(defvar *web-field-counter* 0)
(defun genweb-field-name ()
(format nil "web-field-~D" (incf *web-field-counter*)))
(defclass web-field-presentation ()
((client-value :accessor client-value :initform "")
(query-name :initarg :query-name
:initform (genweb-field-name)
:accessor query-name)
(css-class :initarg :css-class :initform nil :reader css-class)
(css-style :initarg :css-style :initform nil :reader css-style)
(dom-id :initarg :dom-id :initform (genweb-field-name) :accessor dom-id)
(on-change-validation :initarg :on-change-validation
:reader on-change-validation
:initform nil)
(required :accessor required :initarg :required :initform nil)
(validators :accessor validators :initarg :validators :initform '())
(prompt :accessor prompt :initarg :prompt :initform nil)
(warning-message :accessor warning-message :initform nil
:documentation "If NIL this field's value is
currently valid, otherwise a string explaining why
the field's current value isn't valid.")
(metadata :accessor metadata :initarg :metadata :initform nil)))
(defmethod print-object ((field web-field-presentation) stream)
(print-unreadable-object (field stream :type t :identity t)
(format stream "query-name: ~S client-value: ~S" (query-name field) (client-value field))))
(defmethod shared-initialize :after ((presentation web-field-presentation) slot-names
&rest args &key (lisp-value nil lisp-value-p) (client-value nil client-value-p))
(declare (ignore args client-value slot-names))
(when lisp-value-p
(when client-value-p
(error "Can not initialize a presentation object with both a lisp-value and client-value."))
(setf (lisp-value presentation) lisp-value))
(when (slot-boundp presentation 'query-name)
(setf (query-name presentation)
(etypecase (query-name presentation)
(string
weblocks wants to down case strings in attributes . i
;; don't know why.
(string-downcase (query-name presentation)))
(symbol
(string-downcase (symbol-name (query-name presentation))))))))
(defgeneric lisp-value (presentation))
(defmacro define-lisp-value-getter (presentation-class-name slots &body body)
`(defmethod lisp-value ((,presentation-class-name ,presentation-class-name))
(with-accessors ,(mapcar (lambda (slot-name)
(list slot-name slot-name))
slots)
,presentation-class-name
,@body)))
(defgeneric (setf lisp-value) (new-value presentation))
(defmacro define-lisp-value-setter (presentation-class-name (new-value &rest slots) &body body)
`(defmethod (setf lisp-value) (,new-value (,presentation-class-name ,presentation-class-name))
(with-accessors ,(mapcar (lambda (slot-name)
(list slot-name slot-name))
slots)
,presentation-class-name
(setf (client-value ,presentation-class-name) (progn ,@body))
(setf (warning-message ,presentation-class-name)
(multiple-value-bind (validp error-message)
(validp ,presentation-class-name)
(if validp nil error-message)))
,new-value)))
(defgeneric render-presentation (presentation)
(:method ((presentation web-field-presentation))
(with-html
(if (or (css-class presentation) (dom-id presentation))
(htm (:span :id (dom-id presentation)
:class (css-class presentation)
(str (client-value presentation))))
(str (client-value presentation))))))
(defun present-as-static (type value &rest presentation-init-args)
"This could use a better name, but present-as used in the blog widget
displayed an input, we probably want a present-as for non forms and
present-as-editable for forms"
(render-presentation (apply #'make-instance
type :lisp-value value
presentation-init-args)))
(defgeneric render-prompt (presentation)
(:method ((presentation web-field-presentation))
(with-html
(:label :for (query-name presentation)
(str (find-translation (prompt presentation)))))))
(defgeneric render-presentation-editable (presentation))
(defun present-as (type value &rest presentation-init-args)
(render-presentation-editable (apply #'make-instance
type :lisp-value value
presentation-init-args)))
(defclass web-field-validator ()
())
(defgeneric validp (presentation)
(:documentation "If PRESENTATION is valid according to its
validators returns T, otherwise returns three values: NIL, an error
message describing the failure and the web-field-validator object
which failed.")
(:method ((presentation web-field-presentation))
(when (and (null (lisp-value presentation))
(not (required presentation)))
(return-from validp t))
(dolist (validator (validators presentation))
(multiple-value-bind (validp error-message)
(lisp-validate validator (lisp-value presentation))
(when (not validp)
(return-from validp (values nil error-message validator)))))
t))
(define-condition invalid-presentation-value (error)
((message :initarg :message :reader message
:documentation "A string, currently not localized,
describing the validation failure.")
(failed-validator :initarg :failed-validator :reader failed-validator
:documentation "The web-field-validator object
which failed."))
(:documentation "Condition signaled by ENSURE-VALID when a
presentation fails its validation."))
(defgeneric ensure-valid (presentation)
(:documentation "If PRESENTATION is not valid signals an error, otherwise returns T.")
(:method ((presentation web-field-presentation))
(multiple-value-bind (validp error-message failed-validator)
(validp presentation)
(if validp
t
(error 'invalid-presentation-value
:message error-message
:failed-validator failed-validator)))))
(defgeneric lisp-validate (validator lisp-value)
(:documentation "If LISP-VALUE passes VALIDATOR's validation returns
T. Otherwise returns 2 values: NIL and an error message.")
(:method ((validator web-field-validator) (lisp-value t))
t))
(defgeneric client-validate (validator client-value)
(:documentation "Test the string client-value against
VALIDATOR. Returns two values like lisp-validate.")
(:method ((validator web-field-validator) (client-value string))
t))
(defun fail-validation (message &rest message-args)
"Utility fuction for signaling a failed validatien. Returns two
values: NIL and the string resulting from message-args applied to
message (via format)."
(values nil (if message-args
(apply #'format nil message message-args)
message)))
(defclass non-nil-validator (web-field-validator)
((error-message :reader error-message :initarg :error-message)))
(defmethod lisp-validate ((validator non-nil-validator) (lisp-value t))
(if lisp-value
t
(fail-validation (error-message validator))))
(defmethod update-presentation ((presentation web-field-presentation) args)
"Update a presentation's client-state from the appropriate arglist"
(let ((provided-value (getf-all args (as-argument-keyword (query-name presentation))))
(prior-value (client-value presentation)))
(when (equal provided-value prior-value)
(return-from update-presentation (values t provided-value nil)))
(when (and (or (null provided-value)
(equal provided-value ""))
(not (required presentation)))
(setf (client-value presentation) nil)
(return-from update-presentation (values t "" (if (not prior-value) nil t))))
(block test-validity
(dolist (validator (validators presentation))
(multiple-value-bind (validp error-message)
(client-validate validator provided-value)
(when (not validp)
(setf (warning-message presentation) error-message)
;; don't update the client-value with invalid text. return
NIL as the primary value .
(return-from test-validity (values nil provided-value nil)))))
(setf (client-value presentation) provided-value)
;; now check if the lisp value is also valid.
(setf (warning-message presentation)
(multiple-value-bind (validp error-message)
(validp presentation)
(if validp nil error-message)))
return T as the primary value only if the value is valid , third value is ' changed '
(values (not (warning-message presentation)) provided-value t))))
| null | https://raw.githubusercontent.com/eslick/cl-registry/d4015c400dc6abf0eeaf908ed9056aac956eee82/src/libs/presentations/presentation-protocol.lisp | lisp | * web presentations
is fine.
don't know why.
don't update the client-value with invalid text. return
now check if the lisp value is also valid. | (in-package :registry)
nominally we 'd use a protocl based object system here , but CLOS
(defvar *web-field-counter* 0)
(defun genweb-field-name ()
(format nil "web-field-~D" (incf *web-field-counter*)))
(defclass web-field-presentation ()
((client-value :accessor client-value :initform "")
(query-name :initarg :query-name
:initform (genweb-field-name)
:accessor query-name)
(css-class :initarg :css-class :initform nil :reader css-class)
(css-style :initarg :css-style :initform nil :reader css-style)
(dom-id :initarg :dom-id :initform (genweb-field-name) :accessor dom-id)
(on-change-validation :initarg :on-change-validation
:reader on-change-validation
:initform nil)
(required :accessor required :initarg :required :initform nil)
(validators :accessor validators :initarg :validators :initform '())
(prompt :accessor prompt :initarg :prompt :initform nil)
(warning-message :accessor warning-message :initform nil
:documentation "If NIL this field's value is
currently valid, otherwise a string explaining why
the field's current value isn't valid.")
(metadata :accessor metadata :initarg :metadata :initform nil)))
(defmethod print-object ((field web-field-presentation) stream)
(print-unreadable-object (field stream :type t :identity t)
(format stream "query-name: ~S client-value: ~S" (query-name field) (client-value field))))
(defmethod shared-initialize :after ((presentation web-field-presentation) slot-names
&rest args &key (lisp-value nil lisp-value-p) (client-value nil client-value-p))
(declare (ignore args client-value slot-names))
(when lisp-value-p
(when client-value-p
(error "Can not initialize a presentation object with both a lisp-value and client-value."))
(setf (lisp-value presentation) lisp-value))
(when (slot-boundp presentation 'query-name)
(setf (query-name presentation)
(etypecase (query-name presentation)
(string
weblocks wants to down case strings in attributes . i
(string-downcase (query-name presentation)))
(symbol
(string-downcase (symbol-name (query-name presentation))))))))
(defgeneric lisp-value (presentation))
(defmacro define-lisp-value-getter (presentation-class-name slots &body body)
`(defmethod lisp-value ((,presentation-class-name ,presentation-class-name))
(with-accessors ,(mapcar (lambda (slot-name)
(list slot-name slot-name))
slots)
,presentation-class-name
,@body)))
(defgeneric (setf lisp-value) (new-value presentation))
(defmacro define-lisp-value-setter (presentation-class-name (new-value &rest slots) &body body)
`(defmethod (setf lisp-value) (,new-value (,presentation-class-name ,presentation-class-name))
(with-accessors ,(mapcar (lambda (slot-name)
(list slot-name slot-name))
slots)
,presentation-class-name
(setf (client-value ,presentation-class-name) (progn ,@body))
(setf (warning-message ,presentation-class-name)
(multiple-value-bind (validp error-message)
(validp ,presentation-class-name)
(if validp nil error-message)))
,new-value)))
(defgeneric render-presentation (presentation)
(:method ((presentation web-field-presentation))
(with-html
(if (or (css-class presentation) (dom-id presentation))
(htm (:span :id (dom-id presentation)
:class (css-class presentation)
(str (client-value presentation))))
(str (client-value presentation))))))
(defun present-as-static (type value &rest presentation-init-args)
"This could use a better name, but present-as used in the blog widget
displayed an input, we probably want a present-as for non forms and
present-as-editable for forms"
(render-presentation (apply #'make-instance
type :lisp-value value
presentation-init-args)))
(defgeneric render-prompt (presentation)
(:method ((presentation web-field-presentation))
(with-html
(:label :for (query-name presentation)
(str (find-translation (prompt presentation)))))))
(defgeneric render-presentation-editable (presentation))
(defun present-as (type value &rest presentation-init-args)
(render-presentation-editable (apply #'make-instance
type :lisp-value value
presentation-init-args)))
(defclass web-field-validator ()
())
(defgeneric validp (presentation)
(:documentation "If PRESENTATION is valid according to its
validators returns T, otherwise returns three values: NIL, an error
message describing the failure and the web-field-validator object
which failed.")
(:method ((presentation web-field-presentation))
(when (and (null (lisp-value presentation))
(not (required presentation)))
(return-from validp t))
(dolist (validator (validators presentation))
(multiple-value-bind (validp error-message)
(lisp-validate validator (lisp-value presentation))
(when (not validp)
(return-from validp (values nil error-message validator)))))
t))
(define-condition invalid-presentation-value (error)
((message :initarg :message :reader message
:documentation "A string, currently not localized,
describing the validation failure.")
(failed-validator :initarg :failed-validator :reader failed-validator
:documentation "The web-field-validator object
which failed."))
(:documentation "Condition signaled by ENSURE-VALID when a
presentation fails its validation."))
(defgeneric ensure-valid (presentation)
(:documentation "If PRESENTATION is not valid signals an error, otherwise returns T.")
(:method ((presentation web-field-presentation))
(multiple-value-bind (validp error-message failed-validator)
(validp presentation)
(if validp
t
(error 'invalid-presentation-value
:message error-message
:failed-validator failed-validator)))))
(defgeneric lisp-validate (validator lisp-value)
(:documentation "If LISP-VALUE passes VALIDATOR's validation returns
T. Otherwise returns 2 values: NIL and an error message.")
(:method ((validator web-field-validator) (lisp-value t))
t))
(defgeneric client-validate (validator client-value)
(:documentation "Test the string client-value against
VALIDATOR. Returns two values like lisp-validate.")
(:method ((validator web-field-validator) (client-value string))
t))
(defun fail-validation (message &rest message-args)
"Utility fuction for signaling a failed validatien. Returns two
values: NIL and the string resulting from message-args applied to
message (via format)."
(values nil (if message-args
(apply #'format nil message message-args)
message)))
(defclass non-nil-validator (web-field-validator)
((error-message :reader error-message :initarg :error-message)))
(defmethod lisp-validate ((validator non-nil-validator) (lisp-value t))
(if lisp-value
t
(fail-validation (error-message validator))))
(defmethod update-presentation ((presentation web-field-presentation) args)
"Update a presentation's client-state from the appropriate arglist"
(let ((provided-value (getf-all args (as-argument-keyword (query-name presentation))))
(prior-value (client-value presentation)))
(when (equal provided-value prior-value)
(return-from update-presentation (values t provided-value nil)))
(when (and (or (null provided-value)
(equal provided-value ""))
(not (required presentation)))
(setf (client-value presentation) nil)
(return-from update-presentation (values t "" (if (not prior-value) nil t))))
(block test-validity
(dolist (validator (validators presentation))
(multiple-value-bind (validp error-message)
(client-validate validator provided-value)
(when (not validp)
(setf (warning-message presentation) error-message)
NIL as the primary value .
(return-from test-validity (values nil provided-value nil)))))
(setf (client-value presentation) provided-value)
(setf (warning-message presentation)
(multiple-value-bind (validp error-message)
(validp presentation)
(if validp nil error-message)))
return T as the primary value only if the value is valid , third value is ' changed '
(values (not (warning-message presentation)) provided-value t))))
|
b677b30f6ec41c27ff71ce7a91b7a04d345115801cadaa05755b94d89ddb000e | int28h/HaskellTasks | 0030.hs |
Напишите реализацию функции concatList > concatList [ [ 1,2],[],[3 ] ]
[ 1,2,3 ]
Напишите реализацию функции concatList через foldr
GHCi> concatList [[1,2],[],[3]]
[1,2,3]
-}
concatList :: [[a]] -> [a]
concatList = foldr (++) [] | null | https://raw.githubusercontent.com/int28h/HaskellTasks/38aa6c1d461ca5774350c68fa7dd631932f10f84/src/0030.hs | haskell |
Напишите реализацию функции concatList > concatList [ [ 1,2],[],[3 ] ]
[ 1,2,3 ]
Напишите реализацию функции concatList через foldr
GHCi> concatList [[1,2],[],[3]]
[1,2,3]
-}
concatList :: [[a]] -> [a]
concatList = foldr (++) [] | |
3ad8d2917d7acc224dba73263bd2866e393c62bcd44de2f7c06c66ec6f4a6d49 | google/ormolu | Foreign.hs | # LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE OverloadedStrings #-}
module Ormolu.Printer.Meat.Declaration.Foreign
( p_foreignDecl,
)
where
import BasicTypes
import Control.Monad
import Data.Text
import ForeignCall
import GHC
import Ormolu.Printer.Combinators
import Ormolu.Printer.Meat.Common
import Ormolu.Printer.Meat.Declaration.Signature
p_foreignDecl :: ForeignDecl GhcPs -> R ()
p_foreignDecl = \case
fd@ForeignImport {fd_fi} -> do
p_foreignImport fd_fi
p_foreignTypeSig fd
fd@ForeignExport {fd_fe} -> do
p_foreignExport fd_fe
p_foreignTypeSig fd
XForeignDecl x -> noExtCon x
-- | Printer for the last part of an import\/export, which is function name
-- and type signature.
p_foreignTypeSig :: ForeignDecl GhcPs -> R ()
p_foreignTypeSig fd = do
breakpoint
inci
. switchLayout
[ getLoc (fd_name fd),
(getLoc . hsib_body . fd_sig_ty) fd
]
$ do
p_rdrName (fd_name fd)
p_typeAscription (HsWC NoExtField (fd_sig_ty fd))
| Printer for ' ForeignImport ' .
--
-- These have the form:
--
-- > foreign import callingConvention [safety] [identifier]
--
-- We need to check whether the safety has a good source, span, as it
-- defaults to 'PlaySafe' if you don't have anything in the source.
--
-- We also layout the identifier using the 'SourceText', because printing
with the other two fields of ' CImport ' is very complicated . See the
' Outputable ' instance of ' ForeignImport ' for details .
p_foreignImport :: ForeignImport -> R ()
p_foreignImport (CImport cCallConv safety _ _ sourceText) = do
txt "foreign import"
space
located cCallConv atom
-- Need to check for 'noLoc' for the 'safe' annotation
when (isGoodSrcSpan $ getLoc safety) (space >> atom safety)
located sourceText p_sourceText
p_foreignExport :: ForeignExport -> R ()
p_foreignExport (CExport (L loc (CExportStatic _ _ cCallConv)) sourceText) = do
txt "foreign export"
space
located (L loc cCallConv) atom
located sourceText p_sourceText
p_sourceText :: SourceText -> R ()
p_sourceText = \case
NoSourceText -> pure ()
SourceText s -> space >> txt (pack s)
| null | https://raw.githubusercontent.com/google/ormolu/ffdf145bbdf917d54a3ef4951fc2655e35847ff0/src/Ormolu/Printer/Meat/Declaration/Foreign.hs | haskell | # LANGUAGE OverloadedStrings #
| Printer for the last part of an import\/export, which is function name
and type signature.
These have the form:
> foreign import callingConvention [safety] [identifier]
We need to check whether the safety has a good source, span, as it
defaults to 'PlaySafe' if you don't have anything in the source.
We also layout the identifier using the 'SourceText', because printing
Need to check for 'noLoc' for the 'safe' annotation | # LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
module Ormolu.Printer.Meat.Declaration.Foreign
( p_foreignDecl,
)
where
import BasicTypes
import Control.Monad
import Data.Text
import ForeignCall
import GHC
import Ormolu.Printer.Combinators
import Ormolu.Printer.Meat.Common
import Ormolu.Printer.Meat.Declaration.Signature
p_foreignDecl :: ForeignDecl GhcPs -> R ()
p_foreignDecl = \case
fd@ForeignImport {fd_fi} -> do
p_foreignImport fd_fi
p_foreignTypeSig fd
fd@ForeignExport {fd_fe} -> do
p_foreignExport fd_fe
p_foreignTypeSig fd
XForeignDecl x -> noExtCon x
p_foreignTypeSig :: ForeignDecl GhcPs -> R ()
p_foreignTypeSig fd = do
breakpoint
inci
. switchLayout
[ getLoc (fd_name fd),
(getLoc . hsib_body . fd_sig_ty) fd
]
$ do
p_rdrName (fd_name fd)
p_typeAscription (HsWC NoExtField (fd_sig_ty fd))
| Printer for ' ForeignImport ' .
with the other two fields of ' CImport ' is very complicated . See the
' Outputable ' instance of ' ForeignImport ' for details .
p_foreignImport :: ForeignImport -> R ()
p_foreignImport (CImport cCallConv safety _ _ sourceText) = do
txt "foreign import"
space
located cCallConv atom
when (isGoodSrcSpan $ getLoc safety) (space >> atom safety)
located sourceText p_sourceText
p_foreignExport :: ForeignExport -> R ()
p_foreignExport (CExport (L loc (CExportStatic _ _ cCallConv)) sourceText) = do
txt "foreign export"
space
located (L loc cCallConv) atom
located sourceText p_sourceText
p_sourceText :: SourceText -> R ()
p_sourceText = \case
NoSourceText -> pure ()
SourceText s -> space >> txt (pack s)
|
f882168dc79704cad23d2d0a71baba4b1bfa65f79e9416889bef25c622e00c37 | nd/sicp | 4.43.scm | ;;inefficient solution
(define (girls)
(let ((boat-of-mur (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(boat-of-dauning (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(boat-of-hall (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(boat-of-barnakl (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(boat-of-parker (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(daughter-of-mur (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(daughter-of-dauning (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(daughter-of-hall (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(daughter-of-barnakl (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(daughter-of-parker (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa)))
(define (boat-of-father-of-gabriella)
(cond ((eq? daughter-of-mur 'gabriella) boat-of-mur)
((eq? daughter-of-dauning 'gabriella) boat-of-dauning)
((eq? daughter-of-hall 'gabriella) boat-of-hall)
((eq? daughter-of-barnakl 'gabriella) boat-of-barnakl)
((eq? daughter-of-parker 'gabriella) boat-of-parker)))
(require (eq? boat-of-barnakl 'gabriella))
(require (eq? boat-of-mur 'lorna))
(require (eq? boat-of-hall 'rozalinda))
(require (eq? boat-of-dauning 'mellisa))
(require (eq? boat-of-dauning daughter-of-barnakl))
(require (not (eq? boat-of-mur daughter-of-mur)))
(require (not (eq? boat-of-dauning daughter-of-dauning)))
(require (not (eq? boat-of-hall daughter-of-hall)))
(require (not (eq? boat-of-barnakl daughter-of-barnakl)))
(require (not (eq? boat-of-parker daughter-of-parker)))
(require (eq? (boat-of-father-of-gabriella) daughter-of-parker))
(distinct? (list boat-of-mur boat-of-dauning boat-of-hall boat-of-barnakl boat-of-parker))
(distinct? (list daughter-of-mur daughter-of-dauning daughter-of-hall daughter-of-barnakl daughter-of-parker))))
| null | https://raw.githubusercontent.com/nd/sicp/d8587a0403d95af7c7bcf59b812f98c4f8550afd/ch04/4.43.scm | scheme | inefficient solution | (define (girls)
(let ((boat-of-mur (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(boat-of-dauning (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(boat-of-hall (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(boat-of-barnakl (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(boat-of-parker (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(daughter-of-mur (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(daughter-of-dauning (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(daughter-of-hall (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(daughter-of-barnakl (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa))
(daughter-of-parker (amb 'marry-ann 'gabriella 'lorna 'rozalinda 'mellisa)))
(define (boat-of-father-of-gabriella)
(cond ((eq? daughter-of-mur 'gabriella) boat-of-mur)
((eq? daughter-of-dauning 'gabriella) boat-of-dauning)
((eq? daughter-of-hall 'gabriella) boat-of-hall)
((eq? daughter-of-barnakl 'gabriella) boat-of-barnakl)
((eq? daughter-of-parker 'gabriella) boat-of-parker)))
(require (eq? boat-of-barnakl 'gabriella))
(require (eq? boat-of-mur 'lorna))
(require (eq? boat-of-hall 'rozalinda))
(require (eq? boat-of-dauning 'mellisa))
(require (eq? boat-of-dauning daughter-of-barnakl))
(require (not (eq? boat-of-mur daughter-of-mur)))
(require (not (eq? boat-of-dauning daughter-of-dauning)))
(require (not (eq? boat-of-hall daughter-of-hall)))
(require (not (eq? boat-of-barnakl daughter-of-barnakl)))
(require (not (eq? boat-of-parker daughter-of-parker)))
(require (eq? (boat-of-father-of-gabriella) daughter-of-parker))
(distinct? (list boat-of-mur boat-of-dauning boat-of-hall boat-of-barnakl boat-of-parker))
(distinct? (list daughter-of-mur daughter-of-dauning daughter-of-hall daughter-of-barnakl daughter-of-parker))))
|
c00c50ee76823706c7bbe9b818bc15557810bce5eaa70f4c580c958bbcdaab1a | brendanhay/gogol | Run.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
-- |
Module : . Run
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
Deploy and manage user provided container images that scale automatically based on incoming requests . The Cloud Run Admin API v1 follows the Knative Serving API specification , while v2 is aligned with Google Cloud AIP - based API standards , as described in https:\/\/google.aip.dev\/.
--
-- /See:/ </ Cloud Run Admin API Reference>
module Gogol.Run
( -- * Configuration
runService,
* OAuth
CloudPlatform'FullControl,
-- * Resources
-- ** run.projects.locations.operations.delete
RunProjectsLocationsOperationsDeleteResource,
RunProjectsLocationsOperationsDelete (..),
newRunProjectsLocationsOperationsDelete,
-- ** run.projects.locations.operations.get
RunProjectsLocationsOperationsGetResource,
RunProjectsLocationsOperationsGet (..),
newRunProjectsLocationsOperationsGet,
-- ** run.projects.locations.operations.list
RunProjectsLocationsOperationsListResource,
RunProjectsLocationsOperationsList (..),
newRunProjectsLocationsOperationsList,
-- ** run.projects.locations.services.create
RunProjectsLocationsServicesCreateResource,
RunProjectsLocationsServicesCreate (..),
newRunProjectsLocationsServicesCreate,
-- ** run.projects.locations.services.delete
RunProjectsLocationsServicesDeleteResource,
RunProjectsLocationsServicesDelete (..),
newRunProjectsLocationsServicesDelete,
-- ** run.projects.locations.services.get
RunProjectsLocationsServicesGetResource,
RunProjectsLocationsServicesGet (..),
newRunProjectsLocationsServicesGet,
-- ** run.projects.locations.services.getIamPolicy
RunProjectsLocationsServicesGetIamPolicyResource,
RunProjectsLocationsServicesGetIamPolicy (..),
newRunProjectsLocationsServicesGetIamPolicy,
-- ** run.projects.locations.services.list
RunProjectsLocationsServicesListResource,
RunProjectsLocationsServicesList (..),
newRunProjectsLocationsServicesList,
-- ** run.projects.locations.services.patch
RunProjectsLocationsServicesPatchResource,
RunProjectsLocationsServicesPatch (..),
newRunProjectsLocationsServicesPatch,
-- ** run.projects.locations.services.revisions.delete
RunProjectsLocationsServicesRevisionsDeleteResource,
RunProjectsLocationsServicesRevisionsDelete (..),
newRunProjectsLocationsServicesRevisionsDelete,
-- ** run.projects.locations.services.revisions.get
RunProjectsLocationsServicesRevisionsGetResource,
RunProjectsLocationsServicesRevisionsGet (..),
newRunProjectsLocationsServicesRevisionsGet,
-- ** run.projects.locations.services.revisions.list
RunProjectsLocationsServicesRevisionsListResource,
RunProjectsLocationsServicesRevisionsList (..),
newRunProjectsLocationsServicesRevisionsList,
-- ** run.projects.locations.services.setIamPolicy
RunProjectsLocationsServicesSetIamPolicyResource,
RunProjectsLocationsServicesSetIamPolicy (..),
newRunProjectsLocationsServicesSetIamPolicy,
-- ** run.projects.locations.services.testIamPermissions
RunProjectsLocationsServicesTestIamPermissionsResource,
RunProjectsLocationsServicesTestIamPermissions (..),
newRunProjectsLocationsServicesTestIamPermissions,
-- * Types
-- ** Xgafv
Xgafv (..),
-- ** GoogleCloudRunV2BinaryAuthorization
GoogleCloudRunV2BinaryAuthorization (..),
newGoogleCloudRunV2BinaryAuthorization,
-- ** GoogleCloudRunV2CloudSqlInstance
GoogleCloudRunV2CloudSqlInstance (..),
newGoogleCloudRunV2CloudSqlInstance,
-- ** GoogleCloudRunV2Condition
GoogleCloudRunV2Condition (..),
newGoogleCloudRunV2Condition,
-- ** GoogleCloudRunV2Condition_DomainMappingReason
GoogleCloudRunV2Condition_DomainMappingReason (..),
-- ** GoogleCloudRunV2Condition_ExecutionReason
GoogleCloudRunV2Condition_ExecutionReason (..),
-- ** GoogleCloudRunV2Condition_InternalReason
GoogleCloudRunV2Condition_InternalReason (..),
-- ** GoogleCloudRunV2Condition_Reason
GoogleCloudRunV2Condition_Reason (..),
* *
GoogleCloudRunV2Condition_RevisionReason (..),
-- ** GoogleCloudRunV2Condition_Severity
GoogleCloudRunV2Condition_Severity (..),
-- ** GoogleCloudRunV2Condition_State
GoogleCloudRunV2Condition_State (..),
-- ** GoogleCloudRunV2Container
GoogleCloudRunV2Container (..),
newGoogleCloudRunV2Container,
-- ** GoogleCloudRunV2ContainerPort
GoogleCloudRunV2ContainerPort (..),
newGoogleCloudRunV2ContainerPort,
* *
GoogleCloudRunV2EnvVar (..),
newGoogleCloudRunV2EnvVar,
-- ** GoogleCloudRunV2EnvVarSource
GoogleCloudRunV2EnvVarSource (..),
newGoogleCloudRunV2EnvVarSource,
* *
GoogleCloudRunV2ListRevisionsResponse (..),
newGoogleCloudRunV2ListRevisionsResponse,
-- ** GoogleCloudRunV2ListServicesResponse
GoogleCloudRunV2ListServicesResponse (..),
newGoogleCloudRunV2ListServicesResponse,
* *
GoogleCloudRunV2ResourceRequirements (..),
newGoogleCloudRunV2ResourceRequirements,
* *
GoogleCloudRunV2ResourceRequirements_Limits (..),
newGoogleCloudRunV2ResourceRequirements_Limits,
* * GoogleCloudRunV2Revision
GoogleCloudRunV2Revision (..),
newGoogleCloudRunV2Revision,
-- ** GoogleCloudRunV2Revision_Annotations
GoogleCloudRunV2Revision_Annotations (..),
newGoogleCloudRunV2Revision_Annotations,
-- ** GoogleCloudRunV2Revision_ExecutionEnvironment
GoogleCloudRunV2Revision_ExecutionEnvironment (..),
-- ** GoogleCloudRunV2Revision_Labels
GoogleCloudRunV2Revision_Labels (..),
newGoogleCloudRunV2Revision_Labels,
-- ** GoogleCloudRunV2Revision_LaunchStage
GoogleCloudRunV2Revision_LaunchStage (..),
-- ** GoogleCloudRunV2RevisionScaling
GoogleCloudRunV2RevisionScaling (..),
newGoogleCloudRunV2RevisionScaling,
-- ** GoogleCloudRunV2RevisionTemplate
GoogleCloudRunV2RevisionTemplate (..),
newGoogleCloudRunV2RevisionTemplate,
-- ** GoogleCloudRunV2RevisionTemplate_Annotations
GoogleCloudRunV2RevisionTemplate_Annotations (..),
newGoogleCloudRunV2RevisionTemplate_Annotations,
-- ** GoogleCloudRunV2RevisionTemplate_ExecutionEnvironment
GoogleCloudRunV2RevisionTemplate_ExecutionEnvironment (..),
-- ** GoogleCloudRunV2RevisionTemplate_Labels
GoogleCloudRunV2RevisionTemplate_Labels (..),
newGoogleCloudRunV2RevisionTemplate_Labels,
-- ** GoogleCloudRunV2SecretKeySelector
GoogleCloudRunV2SecretKeySelector (..),
newGoogleCloudRunV2SecretKeySelector,
-- ** GoogleCloudRunV2SecretVolumeSource
GoogleCloudRunV2SecretVolumeSource (..),
newGoogleCloudRunV2SecretVolumeSource,
-- ** GoogleCloudRunV2Service
GoogleCloudRunV2Service (..),
newGoogleCloudRunV2Service,
-- ** GoogleCloudRunV2Service_Annotations
GoogleCloudRunV2Service_Annotations (..),
newGoogleCloudRunV2Service_Annotations,
-- ** GoogleCloudRunV2Service_Ingress
GoogleCloudRunV2Service_Ingress (..),
-- ** GoogleCloudRunV2Service_Labels
GoogleCloudRunV2Service_Labels (..),
newGoogleCloudRunV2Service_Labels,
-- ** GoogleCloudRunV2Service_LaunchStage
GoogleCloudRunV2Service_LaunchStage (..),
-- ** GoogleCloudRunV2TrafficTarget
GoogleCloudRunV2TrafficTarget (..),
newGoogleCloudRunV2TrafficTarget,
-- ** GoogleCloudRunV2TrafficTarget_Type
GoogleCloudRunV2TrafficTarget_Type (..),
-- ** GoogleCloudRunV2TrafficTargetStatus
GoogleCloudRunV2TrafficTargetStatus (..),
newGoogleCloudRunV2TrafficTargetStatus,
* *
GoogleCloudRunV2TrafficTargetStatus_Type (..),
-- ** GoogleCloudRunV2VersionToPath
GoogleCloudRunV2VersionToPath (..),
newGoogleCloudRunV2VersionToPath,
-- ** GoogleCloudRunV2Volume
GoogleCloudRunV2Volume (..),
newGoogleCloudRunV2Volume,
-- ** GoogleCloudRunV2VolumeMount
GoogleCloudRunV2VolumeMount (..),
newGoogleCloudRunV2VolumeMount,
* *
GoogleCloudRunV2VpcAccess (..),
newGoogleCloudRunV2VpcAccess,
-- ** GoogleCloudRunV2VpcAccess_Egress
GoogleCloudRunV2VpcAccess_Egress (..),
-- ** GoogleIamV1AuditConfig
GoogleIamV1AuditConfig (..),
newGoogleIamV1AuditConfig,
* * GoogleIamV1AuditLogConfig
GoogleIamV1AuditLogConfig (..),
newGoogleIamV1AuditLogConfig,
-- ** GoogleIamV1AuditLogConfig_LogType
GoogleIamV1AuditLogConfig_LogType (..),
-- ** GoogleIamV1Binding
GoogleIamV1Binding (..),
newGoogleIamV1Binding,
* *
GoogleIamV1Policy (..),
newGoogleIamV1Policy,
-- ** GoogleIamV1SetIamPolicyRequest
GoogleIamV1SetIamPolicyRequest (..),
newGoogleIamV1SetIamPolicyRequest,
-- ** GoogleIamV1TestIamPermissionsRequest
GoogleIamV1TestIamPermissionsRequest (..),
newGoogleIamV1TestIamPermissionsRequest,
-- ** GoogleIamV1TestIamPermissionsResponse
GoogleIamV1TestIamPermissionsResponse (..),
newGoogleIamV1TestIamPermissionsResponse,
* * GoogleLongrunningListOperationsResponse
GoogleLongrunningListOperationsResponse (..),
newGoogleLongrunningListOperationsResponse,
-- ** GoogleLongrunningOperation
GoogleLongrunningOperation (..),
newGoogleLongrunningOperation,
-- ** GoogleLongrunningOperation_Metadata
GoogleLongrunningOperation_Metadata (..),
newGoogleLongrunningOperation_Metadata,
-- ** GoogleLongrunningOperation_Response
GoogleLongrunningOperation_Response (..),
newGoogleLongrunningOperation_Response,
-- ** GoogleProtobufEmpty
GoogleProtobufEmpty (..),
newGoogleProtobufEmpty,
* * GoogleRpcStatus
GoogleRpcStatus (..),
newGoogleRpcStatus,
* *
GoogleRpcStatus_DetailsItem (..),
newGoogleRpcStatus_DetailsItem,
-- ** GoogleTypeExpr
GoogleTypeExpr (..),
newGoogleTypeExpr,
)
where
import Gogol.Run.Projects.Locations.Operations.Delete
import Gogol.Run.Projects.Locations.Operations.Get
import Gogol.Run.Projects.Locations.Operations.List
import Gogol.Run.Projects.Locations.Services.Create
import Gogol.Run.Projects.Locations.Services.Delete
import Gogol.Run.Projects.Locations.Services.Get
import Gogol.Run.Projects.Locations.Services.GetIamPolicy
import Gogol.Run.Projects.Locations.Services.List
import Gogol.Run.Projects.Locations.Services.Patch
import Gogol.Run.Projects.Locations.Services.Revisions.Delete
import Gogol.Run.Projects.Locations.Services.Revisions.Get
import Gogol.Run.Projects.Locations.Services.Revisions.List
import Gogol.Run.Projects.Locations.Services.SetIamPolicy
import Gogol.Run.Projects.Locations.Services.TestIamPermissions
import Gogol.Run.Types
| null | https://raw.githubusercontent.com/brendanhay/gogol/fffd4d98a1996d0ffd4cf64545c5e8af9c976cda/lib/services/gogol-run/gen/Gogol/Run.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
/See:/ </ Cloud Run Admin API Reference>
* Configuration
* Resources
** run.projects.locations.operations.delete
** run.projects.locations.operations.get
** run.projects.locations.operations.list
** run.projects.locations.services.create
** run.projects.locations.services.delete
** run.projects.locations.services.get
** run.projects.locations.services.getIamPolicy
** run.projects.locations.services.list
** run.projects.locations.services.patch
** run.projects.locations.services.revisions.delete
** run.projects.locations.services.revisions.get
** run.projects.locations.services.revisions.list
** run.projects.locations.services.setIamPolicy
** run.projects.locations.services.testIamPermissions
* Types
** Xgafv
** GoogleCloudRunV2BinaryAuthorization
** GoogleCloudRunV2CloudSqlInstance
** GoogleCloudRunV2Condition
** GoogleCloudRunV2Condition_DomainMappingReason
** GoogleCloudRunV2Condition_ExecutionReason
** GoogleCloudRunV2Condition_InternalReason
** GoogleCloudRunV2Condition_Reason
** GoogleCloudRunV2Condition_Severity
** GoogleCloudRunV2Condition_State
** GoogleCloudRunV2Container
** GoogleCloudRunV2ContainerPort
** GoogleCloudRunV2EnvVarSource
** GoogleCloudRunV2ListServicesResponse
** GoogleCloudRunV2Revision_Annotations
** GoogleCloudRunV2Revision_ExecutionEnvironment
** GoogleCloudRunV2Revision_Labels
** GoogleCloudRunV2Revision_LaunchStage
** GoogleCloudRunV2RevisionScaling
** GoogleCloudRunV2RevisionTemplate
** GoogleCloudRunV2RevisionTemplate_Annotations
** GoogleCloudRunV2RevisionTemplate_ExecutionEnvironment
** GoogleCloudRunV2RevisionTemplate_Labels
** GoogleCloudRunV2SecretKeySelector
** GoogleCloudRunV2SecretVolumeSource
** GoogleCloudRunV2Service
** GoogleCloudRunV2Service_Annotations
** GoogleCloudRunV2Service_Ingress
** GoogleCloudRunV2Service_Labels
** GoogleCloudRunV2Service_LaunchStage
** GoogleCloudRunV2TrafficTarget
** GoogleCloudRunV2TrafficTarget_Type
** GoogleCloudRunV2TrafficTargetStatus
** GoogleCloudRunV2VersionToPath
** GoogleCloudRunV2Volume
** GoogleCloudRunV2VolumeMount
** GoogleCloudRunV2VpcAccess_Egress
** GoogleIamV1AuditConfig
** GoogleIamV1AuditLogConfig_LogType
** GoogleIamV1Binding
** GoogleIamV1SetIamPolicyRequest
** GoogleIamV1TestIamPermissionsRequest
** GoogleIamV1TestIamPermissionsResponse
** GoogleLongrunningOperation
** GoogleLongrunningOperation_Metadata
** GoogleLongrunningOperation_Response
** GoogleProtobufEmpty
** GoogleTypeExpr | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Module : . Run
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
Deploy and manage user provided container images that scale automatically based on incoming requests . The Cloud Run Admin API v1 follows the Knative Serving API specification , while v2 is aligned with Google Cloud AIP - based API standards , as described in https:\/\/google.aip.dev\/.
module Gogol.Run
runService,
* OAuth
CloudPlatform'FullControl,
RunProjectsLocationsOperationsDeleteResource,
RunProjectsLocationsOperationsDelete (..),
newRunProjectsLocationsOperationsDelete,
RunProjectsLocationsOperationsGetResource,
RunProjectsLocationsOperationsGet (..),
newRunProjectsLocationsOperationsGet,
RunProjectsLocationsOperationsListResource,
RunProjectsLocationsOperationsList (..),
newRunProjectsLocationsOperationsList,
RunProjectsLocationsServicesCreateResource,
RunProjectsLocationsServicesCreate (..),
newRunProjectsLocationsServicesCreate,
RunProjectsLocationsServicesDeleteResource,
RunProjectsLocationsServicesDelete (..),
newRunProjectsLocationsServicesDelete,
RunProjectsLocationsServicesGetResource,
RunProjectsLocationsServicesGet (..),
newRunProjectsLocationsServicesGet,
RunProjectsLocationsServicesGetIamPolicyResource,
RunProjectsLocationsServicesGetIamPolicy (..),
newRunProjectsLocationsServicesGetIamPolicy,
RunProjectsLocationsServicesListResource,
RunProjectsLocationsServicesList (..),
newRunProjectsLocationsServicesList,
RunProjectsLocationsServicesPatchResource,
RunProjectsLocationsServicesPatch (..),
newRunProjectsLocationsServicesPatch,
RunProjectsLocationsServicesRevisionsDeleteResource,
RunProjectsLocationsServicesRevisionsDelete (..),
newRunProjectsLocationsServicesRevisionsDelete,
RunProjectsLocationsServicesRevisionsGetResource,
RunProjectsLocationsServicesRevisionsGet (..),
newRunProjectsLocationsServicesRevisionsGet,
RunProjectsLocationsServicesRevisionsListResource,
RunProjectsLocationsServicesRevisionsList (..),
newRunProjectsLocationsServicesRevisionsList,
RunProjectsLocationsServicesSetIamPolicyResource,
RunProjectsLocationsServicesSetIamPolicy (..),
newRunProjectsLocationsServicesSetIamPolicy,
RunProjectsLocationsServicesTestIamPermissionsResource,
RunProjectsLocationsServicesTestIamPermissions (..),
newRunProjectsLocationsServicesTestIamPermissions,
Xgafv (..),
GoogleCloudRunV2BinaryAuthorization (..),
newGoogleCloudRunV2BinaryAuthorization,
GoogleCloudRunV2CloudSqlInstance (..),
newGoogleCloudRunV2CloudSqlInstance,
GoogleCloudRunV2Condition (..),
newGoogleCloudRunV2Condition,
GoogleCloudRunV2Condition_DomainMappingReason (..),
GoogleCloudRunV2Condition_ExecutionReason (..),
GoogleCloudRunV2Condition_InternalReason (..),
GoogleCloudRunV2Condition_Reason (..),
* *
GoogleCloudRunV2Condition_RevisionReason (..),
GoogleCloudRunV2Condition_Severity (..),
GoogleCloudRunV2Condition_State (..),
GoogleCloudRunV2Container (..),
newGoogleCloudRunV2Container,
GoogleCloudRunV2ContainerPort (..),
newGoogleCloudRunV2ContainerPort,
* *
GoogleCloudRunV2EnvVar (..),
newGoogleCloudRunV2EnvVar,
GoogleCloudRunV2EnvVarSource (..),
newGoogleCloudRunV2EnvVarSource,
* *
GoogleCloudRunV2ListRevisionsResponse (..),
newGoogleCloudRunV2ListRevisionsResponse,
GoogleCloudRunV2ListServicesResponse (..),
newGoogleCloudRunV2ListServicesResponse,
* *
GoogleCloudRunV2ResourceRequirements (..),
newGoogleCloudRunV2ResourceRequirements,
* *
GoogleCloudRunV2ResourceRequirements_Limits (..),
newGoogleCloudRunV2ResourceRequirements_Limits,
* * GoogleCloudRunV2Revision
GoogleCloudRunV2Revision (..),
newGoogleCloudRunV2Revision,
GoogleCloudRunV2Revision_Annotations (..),
newGoogleCloudRunV2Revision_Annotations,
GoogleCloudRunV2Revision_ExecutionEnvironment (..),
GoogleCloudRunV2Revision_Labels (..),
newGoogleCloudRunV2Revision_Labels,
GoogleCloudRunV2Revision_LaunchStage (..),
GoogleCloudRunV2RevisionScaling (..),
newGoogleCloudRunV2RevisionScaling,
GoogleCloudRunV2RevisionTemplate (..),
newGoogleCloudRunV2RevisionTemplate,
GoogleCloudRunV2RevisionTemplate_Annotations (..),
newGoogleCloudRunV2RevisionTemplate_Annotations,
GoogleCloudRunV2RevisionTemplate_ExecutionEnvironment (..),
GoogleCloudRunV2RevisionTemplate_Labels (..),
newGoogleCloudRunV2RevisionTemplate_Labels,
GoogleCloudRunV2SecretKeySelector (..),
newGoogleCloudRunV2SecretKeySelector,
GoogleCloudRunV2SecretVolumeSource (..),
newGoogleCloudRunV2SecretVolumeSource,
GoogleCloudRunV2Service (..),
newGoogleCloudRunV2Service,
GoogleCloudRunV2Service_Annotations (..),
newGoogleCloudRunV2Service_Annotations,
GoogleCloudRunV2Service_Ingress (..),
GoogleCloudRunV2Service_Labels (..),
newGoogleCloudRunV2Service_Labels,
GoogleCloudRunV2Service_LaunchStage (..),
GoogleCloudRunV2TrafficTarget (..),
newGoogleCloudRunV2TrafficTarget,
GoogleCloudRunV2TrafficTarget_Type (..),
GoogleCloudRunV2TrafficTargetStatus (..),
newGoogleCloudRunV2TrafficTargetStatus,
* *
GoogleCloudRunV2TrafficTargetStatus_Type (..),
GoogleCloudRunV2VersionToPath (..),
newGoogleCloudRunV2VersionToPath,
GoogleCloudRunV2Volume (..),
newGoogleCloudRunV2Volume,
GoogleCloudRunV2VolumeMount (..),
newGoogleCloudRunV2VolumeMount,
* *
GoogleCloudRunV2VpcAccess (..),
newGoogleCloudRunV2VpcAccess,
GoogleCloudRunV2VpcAccess_Egress (..),
GoogleIamV1AuditConfig (..),
newGoogleIamV1AuditConfig,
* * GoogleIamV1AuditLogConfig
GoogleIamV1AuditLogConfig (..),
newGoogleIamV1AuditLogConfig,
GoogleIamV1AuditLogConfig_LogType (..),
GoogleIamV1Binding (..),
newGoogleIamV1Binding,
* *
GoogleIamV1Policy (..),
newGoogleIamV1Policy,
GoogleIamV1SetIamPolicyRequest (..),
newGoogleIamV1SetIamPolicyRequest,
GoogleIamV1TestIamPermissionsRequest (..),
newGoogleIamV1TestIamPermissionsRequest,
GoogleIamV1TestIamPermissionsResponse (..),
newGoogleIamV1TestIamPermissionsResponse,
* * GoogleLongrunningListOperationsResponse
GoogleLongrunningListOperationsResponse (..),
newGoogleLongrunningListOperationsResponse,
GoogleLongrunningOperation (..),
newGoogleLongrunningOperation,
GoogleLongrunningOperation_Metadata (..),
newGoogleLongrunningOperation_Metadata,
GoogleLongrunningOperation_Response (..),
newGoogleLongrunningOperation_Response,
GoogleProtobufEmpty (..),
newGoogleProtobufEmpty,
* * GoogleRpcStatus
GoogleRpcStatus (..),
newGoogleRpcStatus,
* *
GoogleRpcStatus_DetailsItem (..),
newGoogleRpcStatus_DetailsItem,
GoogleTypeExpr (..),
newGoogleTypeExpr,
)
where
import Gogol.Run.Projects.Locations.Operations.Delete
import Gogol.Run.Projects.Locations.Operations.Get
import Gogol.Run.Projects.Locations.Operations.List
import Gogol.Run.Projects.Locations.Services.Create
import Gogol.Run.Projects.Locations.Services.Delete
import Gogol.Run.Projects.Locations.Services.Get
import Gogol.Run.Projects.Locations.Services.GetIamPolicy
import Gogol.Run.Projects.Locations.Services.List
import Gogol.Run.Projects.Locations.Services.Patch
import Gogol.Run.Projects.Locations.Services.Revisions.Delete
import Gogol.Run.Projects.Locations.Services.Revisions.Get
import Gogol.Run.Projects.Locations.Services.Revisions.List
import Gogol.Run.Projects.Locations.Services.SetIamPolicy
import Gogol.Run.Projects.Locations.Services.TestIamPermissions
import Gogol.Run.Types
|
a0388e6dbe0e5051704f205a42484d1fe50c228fccfc6dde43a3454dc600723a | aeternity/aeternity | aesc_create_tx.erl | %%%=============================================================================
2018 , Aeternity Anstalt
%%% @doc
Module defining the State Channel create transaction
%%% @end
%%%=============================================================================
-module(aesc_create_tx).
-behavior(aetx).
-behaviour(aesc_signable_transaction).
%% Behavior API
-export([new/1,
type/0,
fee/1,
gas/1,
ttl/1,
nonce/1,
origin/1,
check/3,
process/3,
signers/2,
version/1,
serialization_template/1,
serialize/1,
deserialize/2,
for_client/1,
valid_at_protocol/2
]).
%% Getters
-export([initiator_id/1,
initiator_pubkey/1,
initiator_amount/1,
channel_reserve/1,
lock_period/1,
responder_id/1,
responder_amount/1,
responder_pubkey/1,
delegate_ids/1,
delegate_pubkeys/1
]).
% aesc_signable_transaction callbacks
-export([channel_id/1,
channel_pubkey/1,
state_hash/1,
round/1]).
-ifdef(TEST).
-export([set_state_hash/2]).
-endif.
-include_lib("aecontract/include/hard_forks.hrl").
%%%===================================================================
%%% Types
%%%===================================================================
-define(CHANNEL_CREATE_TX_VSN, 1).
-define(CHANNEL_CREATE_TX_VSN_DELEGATES, 2).
-define(CHANNEL_CREATE_TX_TYPE, channel_create_tx).
-type vsn() :: non_neg_integer().
-record(channel_create_tx, {
initiator_id :: aeser_id:id(),
initiator_amount :: non_neg_integer(),
responder_id :: aeser_id:id(),
responder_amount :: non_neg_integer(),
channel_reserve :: non_neg_integer(),
lock_period :: non_neg_integer(),
ttl :: aetx:tx_ttl(),
fee :: non_neg_integer(),
delegate_ids :: [aeser_id:id()] | {[aeser_id:id()], [aeser_id:id()]},
state_hash :: binary(),
nonce :: non_neg_integer()
}).
-opaque tx() :: #channel_create_tx{}.
-export_type([tx/0]).
-compile({no_auto_import, [round/1]}).
%%%===================================================================
%%% Behaviour API
%%%===================================================================
-spec new(map()) -> {ok, aetx:tx()}.
new(#{initiator_id := InitiatorId,
initiator_amount := InitiatorAmount,
responder_id := ResponderId,
responder_amount := ResponderAmount,
channel_reserve := ChannelReserve,
lock_period := LockPeriod,
fee := Fee,
state_hash := StateHash,
nonce := Nonce} = Args) ->
true = aesc_utils:check_state_hash_size(StateHash),
ValidateAccounts =
fun(Ids) ->
lists:foreach(fun(D) -> account = aeser_id:specialize_type(D) end, Ids) end,
Note that delegate_ids are required from hardfork on
DelegateIds =
case maps:get(delegate_ids, Args, []) of
L when is_list(L) ->
ValidateAccounts(L),
L;
{IIds, RIds} = DIds when is_list(IIds), is_list(RIds) ->
ValidateAccounts(IIds),
ValidateAccounts(RIds),
DIds
end,
account = aeser_id:specialize_type(InitiatorId),
account = aeser_id:specialize_type(ResponderId),
Tx = #channel_create_tx{initiator_id = InitiatorId,
responder_id = ResponderId,
initiator_amount = InitiatorAmount,
responder_amount = ResponderAmount,
channel_reserve = ChannelReserve,
lock_period = LockPeriod,
ttl = maps:get(ttl, Args, 0),
fee = Fee,
delegate_ids = DelegateIds,
state_hash = StateHash,
nonce = Nonce},
{ok, aetx:new(?MODULE, Tx)}.
type() ->
?CHANNEL_CREATE_TX_TYPE.
-spec fee(tx()) -> non_neg_integer().
fee(#channel_create_tx{fee = Fee}) ->
Fee.
-spec gas(tx()) -> non_neg_integer().
gas(#channel_create_tx{}) ->
0.
-spec ttl(tx()) -> aetx:tx_ttl().
ttl(#channel_create_tx{ttl = TTL}) ->
TTL.
-spec nonce(tx()) -> non_neg_integer().
nonce(#channel_create_tx{nonce = Nonce}) ->
Nonce.
-spec origin(tx()) -> aec_keys:pubkey().
origin(#channel_create_tx{} = Tx) ->
initiator_pubkey(Tx).
-spec check(tx(), aec_trees:trees(), aetx_env:env()) -> {ok, aec_trees:trees()} | {error, term()}.
check(#channel_create_tx{}, Trees,_Env) ->
%% Checks are in process/3
{ok, Trees}.
-spec process(tx(), aec_trees:trees(), aetx_env:env()) -> {ok, aec_trees:trees(), aetx_env:env()}.
process(#channel_create_tx{} = Tx, Trees, Env) ->
{value, SignedTx} = aetx_env:signed_tx(Env),
{ok, ChannelPubkey} = aesc_utils:channel_pubkey(SignedTx),
Instructions =
aeprimop:channel_create_tx_instructions(
initiator_pubkey(Tx),
initiator_amount(Tx),
responder_pubkey(Tx),
responder_amount(Tx),
channel_reserve(Tx),
delegate_pubkeys(Tx),
state_hash(Tx),
lock_period(Tx),
fee(Tx),
nonce(Tx),
round(Tx),
ChannelPubkey),
aeprimop:eval(Instructions, Trees, Env).
-spec signers(tx(), aec_trees:trees()) -> {ok, list(aec_keys:pubkey())}.
signers(#channel_create_tx{} = Tx, _) ->
{ok, [initiator_pubkey(Tx), responder_pubkey(Tx)]}.
-spec serialize(tx()) -> {vsn(), list()}.
serialize(#channel_create_tx{initiator_id = InitiatorId,
initiator_amount = InitiatorAmount,
responder_id = ResponderId,
responder_amount = ResponderAmount,
channel_reserve = ChannelReserve,
lock_period = LockPeriod,
ttl = TTL,
fee = Fee,
delegate_ids = DelegateIds,
state_hash = StateHash,
nonce = Nonce} = Tx) ->
Version = version(Tx),
Fields =
case Version of
?CHANNEL_CREATE_TX_VSN ->
[ {initiator_id , InitiatorId}
, {initiator_amount , InitiatorAmount}
, {responder_id , ResponderId}
, {responder_amount , ResponderAmount}
, {channel_reserve , ChannelReserve}
, {lock_period , LockPeriod}
, {ttl , TTL}
, {fee , Fee}
, {delegate_ids , DelegateIds}
, {state_hash , StateHash}
, {nonce , Nonce}
];
?CHANNEL_CREATE_TX_VSN_DELEGATES ->
{IIds, RIds} = DelegateIds,
[ {initiator_id , InitiatorId}
, {initiator_amount , InitiatorAmount}
, {responder_id , ResponderId}
, {responder_amount , ResponderAmount}
, {channel_reserve , ChannelReserve}
, {lock_period , LockPeriod}
, {ttl , TTL}
, {fee , Fee}
, {initiator_delegate_ids , IIds}
, {responder_delegate_ids , RIds}
, {state_hash , StateHash}
, {nonce , Nonce}
]
end,
{Version, Fields}.
-spec deserialize(vsn(), list()) -> tx().
deserialize(Vsn, Fields) ->
ValidateAccounts =
fun(Ids) ->
lists:foreach(fun(D) -> account = aeser_id:specialize_type(D) end, Ids) end,
case {Vsn, Fields} of
{?CHANNEL_CREATE_TX_VSN,
[ {initiator_id , InitiatorId}
, {initiator_amount , InitiatorAmount}
, {responder_id , ResponderId}
, {responder_amount , ResponderAmount}
, {channel_reserve , ChannelReserve}
, {lock_period , LockPeriod}
, {ttl , TTL}
, {fee , Fee}
, {delegate_ids , DelegateIds}
, {state_hash , StateHash}
, {nonce , Nonce}]} ->
ValidateAccounts(DelegateIds),
pass;
{?CHANNEL_CREATE_TX_VSN_DELEGATES,
[ {initiator_id , InitiatorId}
, {initiator_amount , InitiatorAmount}
, {responder_id , ResponderId}
, {responder_amount , ResponderAmount}
, {channel_reserve , ChannelReserve}
, {lock_period , LockPeriod}
, {ttl , TTL}
, {fee , Fee}
, {initiator_delegate_ids , IIds}
, {responder_delegate_ids , RIds}
, {state_hash , StateHash}
, {nonce , Nonce}]} ->
ValidateAccounts(IIds),
ValidateAccounts(RIds),
DelegateIds = {IIds, RIds}
end,
account = aeser_id:specialize_type(InitiatorId),
account = aeser_id:specialize_type(ResponderId),
true = aesc_utils:check_state_hash_size(StateHash),
#channel_create_tx{initiator_id = InitiatorId,
initiator_amount = InitiatorAmount,
responder_id = ResponderId,
responder_amount = ResponderAmount,
channel_reserve = ChannelReserve,
lock_period = LockPeriod,
ttl = TTL,
fee = Fee,
delegate_ids = DelegateIds,
state_hash = StateHash,
nonce = Nonce}.
-spec for_client(tx()) -> map().
for_client(#channel_create_tx{initiator_id = InitiatorId,
initiator_amount = InitiatorAmount,
responder_id = ResponderId,
responder_amount = ResponderAmount,
channel_reserve = ChannelReserve,
lock_period = LockPeriod,
nonce = Nonce,
ttl = TTL,
delegate_ids = DelegateIds0,
state_hash = StateHash,
fee = Fee}) ->
EncodeIds =
fun(Ids) -> [aeser_api_encoder:encode(id_hash, D) || D <- Ids] end,
DelegateIds =
case DelegateIds0 of
L when is_list(L) -> EncodeIds(L);
{IL, RL} when is_list(IL), is_list(RL) ->
#{ <<"initiator">> => EncodeIds(IL)
, <<"responder">> => EncodeIds(RL)}
end,
#{<<"initiator_id">> => aeser_api_encoder:encode(id_hash, InitiatorId),
<<"initiator_amount">> => InitiatorAmount,
<<"responder_id">> => aeser_api_encoder:encode(id_hash, ResponderId),
<<"responder_amount">> => ResponderAmount,
<<"channel_reserve">> => ChannelReserve,
<<"lock_period">> => LockPeriod,
<<"nonce">> => Nonce,
<<"ttl">> => TTL,
<<"delegate_ids">> => DelegateIds,
<<"state_hash">> => aeser_api_encoder:encode(state, StateHash),
<<"fee">> => Fee}.
serialization_template(?CHANNEL_CREATE_TX_VSN) ->
[ {initiator_id , id}
, {initiator_amount , int}
, {responder_id , id}
, {responder_amount , int}
, {channel_reserve , int}
, {lock_period , int}
, {ttl , int}
, {fee , int}
, {delegate_ids , [id]}
, {state_hash , binary}
, {nonce , int}
];
serialization_template(?CHANNEL_CREATE_TX_VSN_DELEGATES) ->
[ {initiator_id , id}
, {initiator_amount , int}
, {responder_id , id}
, {responder_amount , int}
, {channel_reserve , int}
, {lock_period , int}
, {ttl , int}
, {fee , int}
, {initiator_delegate_ids , [id]}
, {responder_delegate_ids , [id]}
, {state_hash , binary}
, {nonce , int}
].
%%%===================================================================
%%% Getters
%%%===================================================================
-spec initiator_id(tx()) -> aeser_id:id().
initiator_id(#channel_create_tx{initiator_id = InitiatorId}) ->
InitiatorId.
-spec initiator_pubkey(tx()) -> aec_keys:pubkey().
initiator_pubkey(#channel_create_tx{initiator_id = InitiatorId}) ->
aeser_id:specialize(InitiatorId, account).
-spec initiator_amount(tx()) -> non_neg_integer().
initiator_amount(#channel_create_tx{initiator_amount = InitiatorAmount}) ->
InitiatorAmount.
-spec channel_reserve(tx()) -> non_neg_integer().
channel_reserve(#channel_create_tx{channel_reserve = ChannelReserve}) ->
ChannelReserve.
-spec lock_period(tx()) -> non_neg_integer().
lock_period(#channel_create_tx{lock_period = LockPeriod}) ->
LockPeriod.
-spec responder_id(tx()) -> aeser_id:id().
responder_id(#channel_create_tx{responder_id = ResponderId}) ->
ResponderId.
-spec responder_pubkey(tx()) -> aec_keys:pubkey().
responder_pubkey(#channel_create_tx{responder_id = ResponderId}) ->
aeser_id:specialize(ResponderId, account).
-spec responder_amount(tx()) -> non_neg_integer().
responder_amount(#channel_create_tx{responder_amount = ResponderAmount}) ->
ResponderAmount.
-spec channel_pubkey(tx()) -> aesc_channels:pubkey().
channel_pubkey(#channel_create_tx{nonce = Nonce} = Tx) ->
aesc_channels:pubkey(initiator_pubkey(Tx), Nonce, responder_pubkey(Tx)).
-spec channel_id(tx()) -> aesc_channels:id().
channel_id(#channel_create_tx{} = Tx) ->
Key = channel_pubkey(Tx),
aeser_id:create(channel, Key).
-spec state_hash(tx()) -> binary().
state_hash(#channel_create_tx{state_hash = StateHash}) -> StateHash.
-spec round(tx()) -> non_neg_integer().
round(#channel_create_tx{}) ->
1.
delegate_ids(#channel_create_tx{delegate_ids = DelegateIds}) ->
DelegateIds.
-spec delegate_pubkeys(tx()) -> [aec_keys:pubkey()] | {[aec_keys:pubkey()],
[aec_keys:pubkey()]}.
delegate_pubkeys(#channel_create_tx{} = Tx) ->
Specialize = fun(Ids) -> [aeser_id:specialize(D, account) || D <- Ids] end,
case delegate_ids(Tx) of
{IL, RL} -> {Specialize(IL), Specialize(RL)};
L -> Specialize(L)
end.
-spec version(tx()) -> non_neg_integer().
version(#channel_create_tx{delegate_ids = DelegateIds}) ->
case DelegateIds of
L when is_list(L) -> ?CHANNEL_CREATE_TX_VSN;
{IL, RL} when is_list(IL), is_list(RL) ->
?CHANNEL_CREATE_TX_VSN_DELEGATES
end.
-spec valid_at_protocol(aec_hard_forks:protocol_vsn(), tx()) -> boolean().
valid_at_protocol(Protocol, Tx) ->
case version(Tx) of
?CHANNEL_CREATE_TX_VSN when Protocol < ?IRIS_PROTOCOL_VSN -> true;
?CHANNEL_CREATE_TX_VSN_DELEGATES when Protocol >= ?IRIS_PROTOCOL_VSN -> true;
_ -> false
end.
%%%===================================================================
%%% Test setters
%%%===================================================================
-ifdef(TEST).
set_state_hash(Tx, Hash) ->
Tx#channel_create_tx{state_hash = Hash}.
-endif.
| null | https://raw.githubusercontent.com/aeternity/aeternity/b7ce6ae15dab7fa22287c2da3d4405c29bb4edd7/apps/aechannel/src/aesc_create_tx.erl | erlang | =============================================================================
@doc
@end
=============================================================================
Behavior API
Getters
aesc_signable_transaction callbacks
===================================================================
Types
===================================================================
===================================================================
Behaviour API
===================================================================
Checks are in process/3
===================================================================
Getters
===================================================================
===================================================================
Test setters
=================================================================== | 2018 , Aeternity Anstalt
Module defining the State Channel create transaction
-module(aesc_create_tx).
-behavior(aetx).
-behaviour(aesc_signable_transaction).
-export([new/1,
type/0,
fee/1,
gas/1,
ttl/1,
nonce/1,
origin/1,
check/3,
process/3,
signers/2,
version/1,
serialization_template/1,
serialize/1,
deserialize/2,
for_client/1,
valid_at_protocol/2
]).
-export([initiator_id/1,
initiator_pubkey/1,
initiator_amount/1,
channel_reserve/1,
lock_period/1,
responder_id/1,
responder_amount/1,
responder_pubkey/1,
delegate_ids/1,
delegate_pubkeys/1
]).
-export([channel_id/1,
channel_pubkey/1,
state_hash/1,
round/1]).
-ifdef(TEST).
-export([set_state_hash/2]).
-endif.
-include_lib("aecontract/include/hard_forks.hrl").
-define(CHANNEL_CREATE_TX_VSN, 1).
-define(CHANNEL_CREATE_TX_VSN_DELEGATES, 2).
-define(CHANNEL_CREATE_TX_TYPE, channel_create_tx).
-type vsn() :: non_neg_integer().
-record(channel_create_tx, {
initiator_id :: aeser_id:id(),
initiator_amount :: non_neg_integer(),
responder_id :: aeser_id:id(),
responder_amount :: non_neg_integer(),
channel_reserve :: non_neg_integer(),
lock_period :: non_neg_integer(),
ttl :: aetx:tx_ttl(),
fee :: non_neg_integer(),
delegate_ids :: [aeser_id:id()] | {[aeser_id:id()], [aeser_id:id()]},
state_hash :: binary(),
nonce :: non_neg_integer()
}).
-opaque tx() :: #channel_create_tx{}.
-export_type([tx/0]).
-compile({no_auto_import, [round/1]}).
-spec new(map()) -> {ok, aetx:tx()}.
new(#{initiator_id := InitiatorId,
initiator_amount := InitiatorAmount,
responder_id := ResponderId,
responder_amount := ResponderAmount,
channel_reserve := ChannelReserve,
lock_period := LockPeriod,
fee := Fee,
state_hash := StateHash,
nonce := Nonce} = Args) ->
true = aesc_utils:check_state_hash_size(StateHash),
ValidateAccounts =
fun(Ids) ->
lists:foreach(fun(D) -> account = aeser_id:specialize_type(D) end, Ids) end,
Note that delegate_ids are required from hardfork on
DelegateIds =
case maps:get(delegate_ids, Args, []) of
L when is_list(L) ->
ValidateAccounts(L),
L;
{IIds, RIds} = DIds when is_list(IIds), is_list(RIds) ->
ValidateAccounts(IIds),
ValidateAccounts(RIds),
DIds
end,
account = aeser_id:specialize_type(InitiatorId),
account = aeser_id:specialize_type(ResponderId),
Tx = #channel_create_tx{initiator_id = InitiatorId,
responder_id = ResponderId,
initiator_amount = InitiatorAmount,
responder_amount = ResponderAmount,
channel_reserve = ChannelReserve,
lock_period = LockPeriod,
ttl = maps:get(ttl, Args, 0),
fee = Fee,
delegate_ids = DelegateIds,
state_hash = StateHash,
nonce = Nonce},
{ok, aetx:new(?MODULE, Tx)}.
type() ->
?CHANNEL_CREATE_TX_TYPE.
-spec fee(tx()) -> non_neg_integer().
fee(#channel_create_tx{fee = Fee}) ->
Fee.
-spec gas(tx()) -> non_neg_integer().
gas(#channel_create_tx{}) ->
0.
-spec ttl(tx()) -> aetx:tx_ttl().
ttl(#channel_create_tx{ttl = TTL}) ->
TTL.
-spec nonce(tx()) -> non_neg_integer().
nonce(#channel_create_tx{nonce = Nonce}) ->
Nonce.
-spec origin(tx()) -> aec_keys:pubkey().
origin(#channel_create_tx{} = Tx) ->
initiator_pubkey(Tx).
-spec check(tx(), aec_trees:trees(), aetx_env:env()) -> {ok, aec_trees:trees()} | {error, term()}.
check(#channel_create_tx{}, Trees,_Env) ->
{ok, Trees}.
-spec process(tx(), aec_trees:trees(), aetx_env:env()) -> {ok, aec_trees:trees(), aetx_env:env()}.
process(#channel_create_tx{} = Tx, Trees, Env) ->
{value, SignedTx} = aetx_env:signed_tx(Env),
{ok, ChannelPubkey} = aesc_utils:channel_pubkey(SignedTx),
Instructions =
aeprimop:channel_create_tx_instructions(
initiator_pubkey(Tx),
initiator_amount(Tx),
responder_pubkey(Tx),
responder_amount(Tx),
channel_reserve(Tx),
delegate_pubkeys(Tx),
state_hash(Tx),
lock_period(Tx),
fee(Tx),
nonce(Tx),
round(Tx),
ChannelPubkey),
aeprimop:eval(Instructions, Trees, Env).
-spec signers(tx(), aec_trees:trees()) -> {ok, list(aec_keys:pubkey())}.
signers(#channel_create_tx{} = Tx, _) ->
{ok, [initiator_pubkey(Tx), responder_pubkey(Tx)]}.
-spec serialize(tx()) -> {vsn(), list()}.
serialize(#channel_create_tx{initiator_id = InitiatorId,
initiator_amount = InitiatorAmount,
responder_id = ResponderId,
responder_amount = ResponderAmount,
channel_reserve = ChannelReserve,
lock_period = LockPeriod,
ttl = TTL,
fee = Fee,
delegate_ids = DelegateIds,
state_hash = StateHash,
nonce = Nonce} = Tx) ->
Version = version(Tx),
Fields =
case Version of
?CHANNEL_CREATE_TX_VSN ->
[ {initiator_id , InitiatorId}
, {initiator_amount , InitiatorAmount}
, {responder_id , ResponderId}
, {responder_amount , ResponderAmount}
, {channel_reserve , ChannelReserve}
, {lock_period , LockPeriod}
, {ttl , TTL}
, {fee , Fee}
, {delegate_ids , DelegateIds}
, {state_hash , StateHash}
, {nonce , Nonce}
];
?CHANNEL_CREATE_TX_VSN_DELEGATES ->
{IIds, RIds} = DelegateIds,
[ {initiator_id , InitiatorId}
, {initiator_amount , InitiatorAmount}
, {responder_id , ResponderId}
, {responder_amount , ResponderAmount}
, {channel_reserve , ChannelReserve}
, {lock_period , LockPeriod}
, {ttl , TTL}
, {fee , Fee}
, {initiator_delegate_ids , IIds}
, {responder_delegate_ids , RIds}
, {state_hash , StateHash}
, {nonce , Nonce}
]
end,
{Version, Fields}.
-spec deserialize(vsn(), list()) -> tx().
deserialize(Vsn, Fields) ->
ValidateAccounts =
fun(Ids) ->
lists:foreach(fun(D) -> account = aeser_id:specialize_type(D) end, Ids) end,
case {Vsn, Fields} of
{?CHANNEL_CREATE_TX_VSN,
[ {initiator_id , InitiatorId}
, {initiator_amount , InitiatorAmount}
, {responder_id , ResponderId}
, {responder_amount , ResponderAmount}
, {channel_reserve , ChannelReserve}
, {lock_period , LockPeriod}
, {ttl , TTL}
, {fee , Fee}
, {delegate_ids , DelegateIds}
, {state_hash , StateHash}
, {nonce , Nonce}]} ->
ValidateAccounts(DelegateIds),
pass;
{?CHANNEL_CREATE_TX_VSN_DELEGATES,
[ {initiator_id , InitiatorId}
, {initiator_amount , InitiatorAmount}
, {responder_id , ResponderId}
, {responder_amount , ResponderAmount}
, {channel_reserve , ChannelReserve}
, {lock_period , LockPeriod}
, {ttl , TTL}
, {fee , Fee}
, {initiator_delegate_ids , IIds}
, {responder_delegate_ids , RIds}
, {state_hash , StateHash}
, {nonce , Nonce}]} ->
ValidateAccounts(IIds),
ValidateAccounts(RIds),
DelegateIds = {IIds, RIds}
end,
account = aeser_id:specialize_type(InitiatorId),
account = aeser_id:specialize_type(ResponderId),
true = aesc_utils:check_state_hash_size(StateHash),
#channel_create_tx{initiator_id = InitiatorId,
initiator_amount = InitiatorAmount,
responder_id = ResponderId,
responder_amount = ResponderAmount,
channel_reserve = ChannelReserve,
lock_period = LockPeriod,
ttl = TTL,
fee = Fee,
delegate_ids = DelegateIds,
state_hash = StateHash,
nonce = Nonce}.
-spec for_client(tx()) -> map().
for_client(#channel_create_tx{initiator_id = InitiatorId,
initiator_amount = InitiatorAmount,
responder_id = ResponderId,
responder_amount = ResponderAmount,
channel_reserve = ChannelReserve,
lock_period = LockPeriod,
nonce = Nonce,
ttl = TTL,
delegate_ids = DelegateIds0,
state_hash = StateHash,
fee = Fee}) ->
EncodeIds =
fun(Ids) -> [aeser_api_encoder:encode(id_hash, D) || D <- Ids] end,
DelegateIds =
case DelegateIds0 of
L when is_list(L) -> EncodeIds(L);
{IL, RL} when is_list(IL), is_list(RL) ->
#{ <<"initiator">> => EncodeIds(IL)
, <<"responder">> => EncodeIds(RL)}
end,
#{<<"initiator_id">> => aeser_api_encoder:encode(id_hash, InitiatorId),
<<"initiator_amount">> => InitiatorAmount,
<<"responder_id">> => aeser_api_encoder:encode(id_hash, ResponderId),
<<"responder_amount">> => ResponderAmount,
<<"channel_reserve">> => ChannelReserve,
<<"lock_period">> => LockPeriod,
<<"nonce">> => Nonce,
<<"ttl">> => TTL,
<<"delegate_ids">> => DelegateIds,
<<"state_hash">> => aeser_api_encoder:encode(state, StateHash),
<<"fee">> => Fee}.
serialization_template(?CHANNEL_CREATE_TX_VSN) ->
[ {initiator_id , id}
, {initiator_amount , int}
, {responder_id , id}
, {responder_amount , int}
, {channel_reserve , int}
, {lock_period , int}
, {ttl , int}
, {fee , int}
, {delegate_ids , [id]}
, {state_hash , binary}
, {nonce , int}
];
serialization_template(?CHANNEL_CREATE_TX_VSN_DELEGATES) ->
[ {initiator_id , id}
, {initiator_amount , int}
, {responder_id , id}
, {responder_amount , int}
, {channel_reserve , int}
, {lock_period , int}
, {ttl , int}
, {fee , int}
, {initiator_delegate_ids , [id]}
, {responder_delegate_ids , [id]}
, {state_hash , binary}
, {nonce , int}
].
-spec initiator_id(tx()) -> aeser_id:id().
initiator_id(#channel_create_tx{initiator_id = InitiatorId}) ->
InitiatorId.
-spec initiator_pubkey(tx()) -> aec_keys:pubkey().
initiator_pubkey(#channel_create_tx{initiator_id = InitiatorId}) ->
aeser_id:specialize(InitiatorId, account).
-spec initiator_amount(tx()) -> non_neg_integer().
initiator_amount(#channel_create_tx{initiator_amount = InitiatorAmount}) ->
InitiatorAmount.
-spec channel_reserve(tx()) -> non_neg_integer().
channel_reserve(#channel_create_tx{channel_reserve = ChannelReserve}) ->
ChannelReserve.
-spec lock_period(tx()) -> non_neg_integer().
lock_period(#channel_create_tx{lock_period = LockPeriod}) ->
LockPeriod.
-spec responder_id(tx()) -> aeser_id:id().
responder_id(#channel_create_tx{responder_id = ResponderId}) ->
ResponderId.
-spec responder_pubkey(tx()) -> aec_keys:pubkey().
responder_pubkey(#channel_create_tx{responder_id = ResponderId}) ->
aeser_id:specialize(ResponderId, account).
-spec responder_amount(tx()) -> non_neg_integer().
responder_amount(#channel_create_tx{responder_amount = ResponderAmount}) ->
ResponderAmount.
-spec channel_pubkey(tx()) -> aesc_channels:pubkey().
channel_pubkey(#channel_create_tx{nonce = Nonce} = Tx) ->
aesc_channels:pubkey(initiator_pubkey(Tx), Nonce, responder_pubkey(Tx)).
-spec channel_id(tx()) -> aesc_channels:id().
channel_id(#channel_create_tx{} = Tx) ->
Key = channel_pubkey(Tx),
aeser_id:create(channel, Key).
-spec state_hash(tx()) -> binary().
state_hash(#channel_create_tx{state_hash = StateHash}) -> StateHash.
-spec round(tx()) -> non_neg_integer().
round(#channel_create_tx{}) ->
1.
delegate_ids(#channel_create_tx{delegate_ids = DelegateIds}) ->
DelegateIds.
-spec delegate_pubkeys(tx()) -> [aec_keys:pubkey()] | {[aec_keys:pubkey()],
[aec_keys:pubkey()]}.
delegate_pubkeys(#channel_create_tx{} = Tx) ->
Specialize = fun(Ids) -> [aeser_id:specialize(D, account) || D <- Ids] end,
case delegate_ids(Tx) of
{IL, RL} -> {Specialize(IL), Specialize(RL)};
L -> Specialize(L)
end.
-spec version(tx()) -> non_neg_integer().
version(#channel_create_tx{delegate_ids = DelegateIds}) ->
case DelegateIds of
L when is_list(L) -> ?CHANNEL_CREATE_TX_VSN;
{IL, RL} when is_list(IL), is_list(RL) ->
?CHANNEL_CREATE_TX_VSN_DELEGATES
end.
-spec valid_at_protocol(aec_hard_forks:protocol_vsn(), tx()) -> boolean().
valid_at_protocol(Protocol, Tx) ->
case version(Tx) of
?CHANNEL_CREATE_TX_VSN when Protocol < ?IRIS_PROTOCOL_VSN -> true;
?CHANNEL_CREATE_TX_VSN_DELEGATES when Protocol >= ?IRIS_PROTOCOL_VSN -> true;
_ -> false
end.
-ifdef(TEST).
set_state_hash(Tx, Hash) ->
Tx#channel_create_tx{state_hash = Hash}.
-endif.
|
99fdd61433bcbfb248ee7e3fe0d50bee8ec64ba9924a9aabfce9ad0ffef9d845 | zakwilson/ceilingbounce | main.clj | (ns com.flashlightdb.ceilingbounce.main
(:require [neko.activity :refer [defactivity set-content-view!]]
[neko.notify :as notify]
[neko.resource :as res]
[neko.find-view :refer [find-view]]
[neko.threading :refer [on-ui]]
[neko.action-bar :refer [setup-action-bar tab-listener]]
[neko.log :as log]
[neko.ui :as ui]
neko.tools.repl
[clojure.java.io :as io]
[clojure.core.async
:as a
:refer [>! <! >!! <!! go chan buffer close! thread
alts! alts!! timeout]]
[com.flashlightdb.ceilingbounce.runtime :as runtime]
[com.flashlightdb.ceilingbounce.lumens :as lumens]
[com.flashlightdb.ceilingbounce.throw :as throw]
[com.flashlightdb.ceilingbounce.common
:as common
:refer [identity* config main-activity do-nothing]])
(:import android.widget.EditText
[android.hardware
SensorManager
SensorEventListener
Sensor
SensorEvent
SensorListener]
[android.app
Activity]
neko.App))
;; We execute this function to import all subclasses of R class. This gives us
;; access to all application resources.
(res/import-all)
(declare ^android.app.Activity com.flashlightdb.ceilingbounce.MainActivity)
(defactivity com.flashlightdb.ceilingbounce.MainActivity
:key :main
(onCreate [this bundle]
(swap! main-activity
identity* this)
(common/read-config)
(def sm (cast SensorManager (.getSystemService ^Activity this "sensor")))
(def light-sensor (.getDefaultSensor ^SensorManager sm
(Sensor/TYPE_LIGHT)))
(def sensor-listener
(let [activity this]
(reify SensorEventListener
(onSensorChanged [this evt]
(let [lux (first (.values evt))]
(swap! common/lux identity* lux)))
(onAccuracyChanged [this s a]
(do-nothing)))))
(.superOnCreate this bundle)
(neko.debug/keep-screen-on this)
(runtime/setup-chart)
(on-ui
FIXME why does this error ?
(setup-action-bar this
{:navigation-mode :tabs
:id ::action-bar
:tabs [[:tab {:text "Lumens"
:tab-listener (tab-listener
:on-tab-selected @#'lumens/activate-tab
:on-tab-unselected @#'lumens/deactivate-tab)}]
[:tab {:text "Throw"
:tab-listener (tab-listener
:on-tab-selected @#'throw/activate-tab
:on-tab-unselected @#'throw/deactivate-tab)}]
[:tab {:text "Runtime"
:tab-listener (tab-listener
:on-tab-selected @#'runtime/activate-tab
:on-tab-unselected @#'runtime/deactivate-tab)}]]})
(catch Exception e nil))))
(onResume [this]
(.registerListener sm
sensor-listener
light-sensor
200000)
(.superOnResume this))
(onPause [this]
(.unregisterListener sm sensor-listener)
(.superOnPause this)))
| null | https://raw.githubusercontent.com/zakwilson/ceilingbounce/3701bf2f316b7b720701b7af0ca7a34cd01e7d72/src/clojure/com/flashlightdb/ceilingbounce/main.clj | clojure | We execute this function to import all subclasses of R class. This gives us
access to all application resources. | (ns com.flashlightdb.ceilingbounce.main
(:require [neko.activity :refer [defactivity set-content-view!]]
[neko.notify :as notify]
[neko.resource :as res]
[neko.find-view :refer [find-view]]
[neko.threading :refer [on-ui]]
[neko.action-bar :refer [setup-action-bar tab-listener]]
[neko.log :as log]
[neko.ui :as ui]
neko.tools.repl
[clojure.java.io :as io]
[clojure.core.async
:as a
:refer [>! <! >!! <!! go chan buffer close! thread
alts! alts!! timeout]]
[com.flashlightdb.ceilingbounce.runtime :as runtime]
[com.flashlightdb.ceilingbounce.lumens :as lumens]
[com.flashlightdb.ceilingbounce.throw :as throw]
[com.flashlightdb.ceilingbounce.common
:as common
:refer [identity* config main-activity do-nothing]])
(:import android.widget.EditText
[android.hardware
SensorManager
SensorEventListener
Sensor
SensorEvent
SensorListener]
[android.app
Activity]
neko.App))
(res/import-all)
(declare ^android.app.Activity com.flashlightdb.ceilingbounce.MainActivity)
(defactivity com.flashlightdb.ceilingbounce.MainActivity
:key :main
(onCreate [this bundle]
(swap! main-activity
identity* this)
(common/read-config)
(def sm (cast SensorManager (.getSystemService ^Activity this "sensor")))
(def light-sensor (.getDefaultSensor ^SensorManager sm
(Sensor/TYPE_LIGHT)))
(def sensor-listener
(let [activity this]
(reify SensorEventListener
(onSensorChanged [this evt]
(let [lux (first (.values evt))]
(swap! common/lux identity* lux)))
(onAccuracyChanged [this s a]
(do-nothing)))))
(.superOnCreate this bundle)
(neko.debug/keep-screen-on this)
(runtime/setup-chart)
(on-ui
FIXME why does this error ?
(setup-action-bar this
{:navigation-mode :tabs
:id ::action-bar
:tabs [[:tab {:text "Lumens"
:tab-listener (tab-listener
:on-tab-selected @#'lumens/activate-tab
:on-tab-unselected @#'lumens/deactivate-tab)}]
[:tab {:text "Throw"
:tab-listener (tab-listener
:on-tab-selected @#'throw/activate-tab
:on-tab-unselected @#'throw/deactivate-tab)}]
[:tab {:text "Runtime"
:tab-listener (tab-listener
:on-tab-selected @#'runtime/activate-tab
:on-tab-unselected @#'runtime/deactivate-tab)}]]})
(catch Exception e nil))))
(onResume [this]
(.registerListener sm
sensor-listener
light-sensor
200000)
(.superOnResume this))
(onPause [this]
(.unregisterListener sm sensor-listener)
(.superOnPause this)))
|
250369fc669d1753ac3822a0c36f8bb076f064670a0326f1764d6be8f5bc2b1e | astine/Sacraspot | utilities.lisp | website utilities.lisp - Andrew Stine ( C ) 2009 - 2010
(in-package #:sacraspot)
;;;
;;; General language extensions
;;;
(defun alist-to-plist (alist)
"Converts an association list to a properties list"
(declare (type list alist))
(mapcan #'(lambda (pair)
(list (car pair) (cdr pair)))
alist))
(defmacro with-gensyms (symbols &body body)
"Provides generated, unique symbols for use within the body of a macro
(to avoid namecapture)"
`(let ,(mapcar #'(lambda (symbol)
`(,symbol (gensym)))
symbols)
,@body))
( ( name lambda - list & body body )
;"Defines a function with a cache that dispatches on its argument list."
;(with-gensyms (table value found)
;(let ((params (loop for param in lambda-list
when ( not ( or ( eql param ' & optional )
( eql param ' & keys )
( eql param ' & rest )
( eql param ' & body ) ) )
collect ( if ( ) ( car param ) param ) ) ) )
;`(let ((,table (make-hash-table :test #'equal)))
;(defun ,name ,lambda-list
;(multiple-value-bind (,value ,found)
( gethash ( list , @params ) , table )
;(if ,found
;,value
( setf ( gethash ( list , @params ) , table )
( progn , @body ) ) ) ) ) ) ) ) )
(eval-when (:compile-toplevel :load-toplevel) ;evaluated early so macros can use this
(defun group (list n)
"Partitions a list into a list of sublists of length 'n'"
(cond ((null list)
nil)
((<= (list-length list) n)
(list list))
(t
(cons (subseq list 0 n)
(group (subseq list n) n))))))
(defmacro while (condition &body body)
"Loops indefinitely while condition is true"
`(do () ((not ,condition)) ,@body))
(defmacro aif (condition &body body)
"anaphoric if"
`(let ((it ,condition))
(if it ,@body)))
(defmacro awhile (condition &body body)
"anaphoric while"
`(do ((it ,condition ,condition))
((not it)) ,@body))
(defmacro arc-if (&body forms)
"Alternate syntax for cond/if statments
(borrowed from arc lisp)"
`(cond ,@(mapcar #'(lambda (clause)
(if (= (list-length clause) 2)
clause
(cons 't clause)))
(sacraspot::group forms 2))))
(defun get-range (begin end)
"Generates a list of numbers between begin and end"
(declare (type integer begin end))
(if (<= begin end)
(cons begin (get-range (1+ begin) end))))
(defmacro range (begin &optional end)
"Returns a list of numbers between 'begin' and 'end'
(will attempt to generate at compile time if possible)"
(arc-if (and (listp begin)
(null end))
`(apply #'get-range ,begin)
(and (integerp begin)
(integerp end))
`(list ,@(get-range begin end))
`(funcall #'get-range ,begin ,end)))
(defun make-set (list &optional (eql-test #'=) (predicate #'<))
"sorts a list and filters out duplicates"
(declare (type list list))
(labels ((filter-dups (lst)
(arc-if (null lst)
nil
(equal (list-length lst) 1)
lst
(funcall eql-test (first lst) (second lst))
(filter-dups (rest lst))
(cons (first lst) (filter-dups (rest lst))))))
(filter-dups (sort list predicate))))
(defmacro call-with (function parameters lambda-list)
`(lambda ,parameters (funcall ,function ,@lambda-list)))
(defun to-list (item)
"Wraps an item in a list, unless the item is :null or nil, in which case, return the empty list"
(and (coalesce item) (list item)))
(defun greater (a b &optional (test #'>))
(if (funcall test a b)
a
b))
;;; patch hunchentoot to allow for prefix URIs
(in-package #:hunchentoot)
(defvar *root-uri* nil)
(export '*root-uri*)
(defun dispatch-easy-handlers (request)
"This is a dispatcher which returns the appropriate handler
defined with DEFINE-EASY-HANDLER, if there is one."
;(lambda (&key) (format nil ":~A:~A:" *root-uri* (script-name* *request*))))
(loop for (uri acceptor-names easy-handler) in *easy-handler-alist*
when (and (or (eq acceptor-names t)
(find (acceptor-name *acceptor*) acceptor-names :test #'eq))
(cond ((stringp uri)
(string= (script-name request) (concatenate 'string *root-uri* uri)))
(t (funcall uri request))))
do (return easy-handler)))
(in-package #:sacraspot)
;;;
;;; Functions and macros dealing with sacraspot specific issues
;;;
(define-condition bad-input-error (error)
((input :initarg :input :reader input)
(param :initarg :param :reader param)
(expected :initarg :expected :reader expected))
(:report (lambda (condition stream)
(format stream "Bad input ~:[~;for ~:*~A~]: ~A, ~A expected."
(param condition)
(input condition)
(expected condition))))
(:documentation "Error signaled when invalid or incorrect input is provided to an server call"))
(defun fetch-parameter (parameter-name &key default typespec
(parser (lambda (param)
(unless (equal param "")
(read-from-string param)))))
"A function to encapsulate some of the routine details of dealing with http
parameters in hunchentoot handlers."
(declare (type string parameter-name)
(type (or null function) parser))
(restart-case
(aif (parameter parameter-name)
(if parser
(let ((input (funcall parser it)))
(progn
(when typespec
(assert (subtypep (type-of input) typespec)
(input) 'bad-input-error
:param parameter-name
:input (write-to-string input)
:expected typespec))
input))
it)
default)
(use-default () default)
(use-other-value (value) value)))
(defmacro with-location (&body body)
"When called within the body of a handler, determines the location of the remote client
by first checking for explicit latitude and longitude parameters and secondly by checking the
ip against the geolocation database."
(with-gensyms (lat-long)
`(handler-bind ((geolocation-error (lambda (c)
(when (equal (real-remote-addr) (ip c))
(invoke-restart 'try-other-ip (real-remote-addr))))))
(let* ((ip (fetch-parameter "ip" :default (real-remote-addr) :parser nil :typespec 'string))
(,lat-long (unless (and (parameter "latitude")
(parameter "longitude"))
(latitude-and-longitude ip)))
(latitude (fetch-parameter "latitude" :default (first ,lat-long) :typespec 'float))
(longitude (fetch-parameter "longitude" :default (second ,lat-long) :typespec 'float)))
,@body))))
(defun parse-number-span (span)
"Take a string of the form '1-3, 5, 8-10', and returns an ordered
list of every number, represented by the string"
(declare (type string span))
(make-set
(mapcan #'(lambda (part)
(cond ((cl-ppcre:scan "[0-9]+-[0-9]+" part)
(range (mapcar #'read-from-string
(split-sequence:split-sequence #\- part))))
((cl-ppcre:scan "[0-9]+" part)
(list (read-from-string part)))))
(split-sequence:split-sequence #\, span :remove-empty-subseqs t))))
(defun make-number-span (number-list)
"Takes a list of numbers and returns a string of the form:
'1-3, 5, 8-10', representing the numbers in the list"
(declare (type list number-list))
(labels ((scan-list (nums curr acc)
(cond ((null nums)
(cons curr acc))
((null curr)
(scan-list (rest nums) (cons (first nums) curr) acc))
((= (first nums) (1+ (first curr)))
(scan-list (rest nums) (cons (first nums) curr) acc))
(t (scan-list nums nil (cons curr acc))))))
(reduce #'(lambda (x y) (concatenate 'string y ", " x))
(mapcar #'(lambda (sublist) (if (= (list-length sublist) 1)
(format nil "~A" (car sublist))
(format nil "~A-~A" (car (last sublist))
(first sublist))))
(scan-list (make-set number-list) nil nil)))))
(defun digit-p (digit)
(<= 48 (char-code digit) 57))
(defun standard-phone-number-p (number)
"Checks that a phone number string is complete and not malformed"
(declare (type string number))
(and (equal (length number) 10)
(every #'digit-p number)))
(defun clean-phone (number)
"Reduces a phone number to a string of numerals"
(declare (type string number))
(with-output-to-string (out)
(with-input-from-string (in number)
(awhile (read-char in nil nil)
(if (digit-p it)
(princ it out))))))
(defun pretty-print-phone (number)
(declare (type string number))
"Takes a string of numberals and prints it in the American phone number format"
(handler-case
(concatenate 'string
"("
(subseq number 0 3)
") "
(subseq number 3 6)
"-"
(subseq number 6))
(condition () (error "Problem pretty printing phone number: ~a" number))))
(defun format-hr-timestamp (time)
"Formats a timestamp to a string of the form: MM DD, YYYY HH:MM AM/PM"
(declare (type (or null local-time:timestamp) time))
(when time
(format-timestring nil time
:format '(:short-month " " :day ", " :year " ":hour12 ":" (:min 2) " " :ampm))))
extension to yason JSON encoder
(defmethod yason:encode ((object float) &optional (stream *standard-output*))
(format stream "~F" object))
| null | https://raw.githubusercontent.com/astine/Sacraspot/9cdce12e8b15b7a00e40c9150fbafa04034f17f0/utilities.lisp | lisp |
General language extensions
"Defines a function with a cache that dispatches on its argument list."
(with-gensyms (table value found)
(let ((params (loop for param in lambda-list
`(let ((,table (make-hash-table :test #'equal)))
(defun ,name ,lambda-list
(multiple-value-bind (,value ,found)
(if ,found
,value
evaluated early so macros can use this
patch hunchentoot to allow for prefix URIs
(lambda (&key) (format nil ":~A:~A:" *root-uri* (script-name* *request*))))
Functions and macros dealing with sacraspot specific issues
| website utilities.lisp - Andrew Stine ( C ) 2009 - 2010
(in-package #:sacraspot)
(defun alist-to-plist (alist)
"Converts an association list to a properties list"
(declare (type list alist))
(mapcan #'(lambda (pair)
(list (car pair) (cdr pair)))
alist))
(defmacro with-gensyms (symbols &body body)
"Provides generated, unique symbols for use within the body of a macro
(to avoid namecapture)"
`(let ,(mapcar #'(lambda (symbol)
`(,symbol (gensym)))
symbols)
,@body))
( ( name lambda - list & body body )
when ( not ( or ( eql param ' & optional )
( eql param ' & keys )
( eql param ' & rest )
( eql param ' & body ) ) )
collect ( if ( ) ( car param ) param ) ) ) )
( gethash ( list , @params ) , table )
( setf ( gethash ( list , @params ) , table )
( progn , @body ) ) ) ) ) ) ) ) )
(defun group (list n)
"Partitions a list into a list of sublists of length 'n'"
(cond ((null list)
nil)
((<= (list-length list) n)
(list list))
(t
(cons (subseq list 0 n)
(group (subseq list n) n))))))
(defmacro while (condition &body body)
"Loops indefinitely while condition is true"
`(do () ((not ,condition)) ,@body))
(defmacro aif (condition &body body)
"anaphoric if"
`(let ((it ,condition))
(if it ,@body)))
(defmacro awhile (condition &body body)
"anaphoric while"
`(do ((it ,condition ,condition))
((not it)) ,@body))
(defmacro arc-if (&body forms)
"Alternate syntax for cond/if statments
(borrowed from arc lisp)"
`(cond ,@(mapcar #'(lambda (clause)
(if (= (list-length clause) 2)
clause
(cons 't clause)))
(sacraspot::group forms 2))))
(defun get-range (begin end)
"Generates a list of numbers between begin and end"
(declare (type integer begin end))
(if (<= begin end)
(cons begin (get-range (1+ begin) end))))
(defmacro range (begin &optional end)
"Returns a list of numbers between 'begin' and 'end'
(will attempt to generate at compile time if possible)"
(arc-if (and (listp begin)
(null end))
`(apply #'get-range ,begin)
(and (integerp begin)
(integerp end))
`(list ,@(get-range begin end))
`(funcall #'get-range ,begin ,end)))
(defun make-set (list &optional (eql-test #'=) (predicate #'<))
"sorts a list and filters out duplicates"
(declare (type list list))
(labels ((filter-dups (lst)
(arc-if (null lst)
nil
(equal (list-length lst) 1)
lst
(funcall eql-test (first lst) (second lst))
(filter-dups (rest lst))
(cons (first lst) (filter-dups (rest lst))))))
(filter-dups (sort list predicate))))
(defmacro call-with (function parameters lambda-list)
`(lambda ,parameters (funcall ,function ,@lambda-list)))
(defun to-list (item)
"Wraps an item in a list, unless the item is :null or nil, in which case, return the empty list"
(and (coalesce item) (list item)))
(defun greater (a b &optional (test #'>))
(if (funcall test a b)
a
b))
(in-package #:hunchentoot)
(defvar *root-uri* nil)
(export '*root-uri*)
(defun dispatch-easy-handlers (request)
"This is a dispatcher which returns the appropriate handler
defined with DEFINE-EASY-HANDLER, if there is one."
(loop for (uri acceptor-names easy-handler) in *easy-handler-alist*
when (and (or (eq acceptor-names t)
(find (acceptor-name *acceptor*) acceptor-names :test #'eq))
(cond ((stringp uri)
(string= (script-name request) (concatenate 'string *root-uri* uri)))
(t (funcall uri request))))
do (return easy-handler)))
(in-package #:sacraspot)
(define-condition bad-input-error (error)
((input :initarg :input :reader input)
(param :initarg :param :reader param)
(expected :initarg :expected :reader expected))
(:report (lambda (condition stream)
(format stream "Bad input ~:[~;for ~:*~A~]: ~A, ~A expected."
(param condition)
(input condition)
(expected condition))))
(:documentation "Error signaled when invalid or incorrect input is provided to an server call"))
(defun fetch-parameter (parameter-name &key default typespec
(parser (lambda (param)
(unless (equal param "")
(read-from-string param)))))
"A function to encapsulate some of the routine details of dealing with http
parameters in hunchentoot handlers."
(declare (type string parameter-name)
(type (or null function) parser))
(restart-case
(aif (parameter parameter-name)
(if parser
(let ((input (funcall parser it)))
(progn
(when typespec
(assert (subtypep (type-of input) typespec)
(input) 'bad-input-error
:param parameter-name
:input (write-to-string input)
:expected typespec))
input))
it)
default)
(use-default () default)
(use-other-value (value) value)))
(defmacro with-location (&body body)
"When called within the body of a handler, determines the location of the remote client
by first checking for explicit latitude and longitude parameters and secondly by checking the
ip against the geolocation database."
(with-gensyms (lat-long)
`(handler-bind ((geolocation-error (lambda (c)
(when (equal (real-remote-addr) (ip c))
(invoke-restart 'try-other-ip (real-remote-addr))))))
(let* ((ip (fetch-parameter "ip" :default (real-remote-addr) :parser nil :typespec 'string))
(,lat-long (unless (and (parameter "latitude")
(parameter "longitude"))
(latitude-and-longitude ip)))
(latitude (fetch-parameter "latitude" :default (first ,lat-long) :typespec 'float))
(longitude (fetch-parameter "longitude" :default (second ,lat-long) :typespec 'float)))
,@body))))
(defun parse-number-span (span)
"Take a string of the form '1-3, 5, 8-10', and returns an ordered
list of every number, represented by the string"
(declare (type string span))
(make-set
(mapcan #'(lambda (part)
(cond ((cl-ppcre:scan "[0-9]+-[0-9]+" part)
(range (mapcar #'read-from-string
(split-sequence:split-sequence #\- part))))
((cl-ppcre:scan "[0-9]+" part)
(list (read-from-string part)))))
(split-sequence:split-sequence #\, span :remove-empty-subseqs t))))
(defun make-number-span (number-list)
"Takes a list of numbers and returns a string of the form:
'1-3, 5, 8-10', representing the numbers in the list"
(declare (type list number-list))
(labels ((scan-list (nums curr acc)
(cond ((null nums)
(cons curr acc))
((null curr)
(scan-list (rest nums) (cons (first nums) curr) acc))
((= (first nums) (1+ (first curr)))
(scan-list (rest nums) (cons (first nums) curr) acc))
(t (scan-list nums nil (cons curr acc))))))
(reduce #'(lambda (x y) (concatenate 'string y ", " x))
(mapcar #'(lambda (sublist) (if (= (list-length sublist) 1)
(format nil "~A" (car sublist))
(format nil "~A-~A" (car (last sublist))
(first sublist))))
(scan-list (make-set number-list) nil nil)))))
(defun digit-p (digit)
(<= 48 (char-code digit) 57))
(defun standard-phone-number-p (number)
"Checks that a phone number string is complete and not malformed"
(declare (type string number))
(and (equal (length number) 10)
(every #'digit-p number)))
(defun clean-phone (number)
"Reduces a phone number to a string of numerals"
(declare (type string number))
(with-output-to-string (out)
(with-input-from-string (in number)
(awhile (read-char in nil nil)
(if (digit-p it)
(princ it out))))))
(defun pretty-print-phone (number)
(declare (type string number))
"Takes a string of numberals and prints it in the American phone number format"
(handler-case
(concatenate 'string
"("
(subseq number 0 3)
") "
(subseq number 3 6)
"-"
(subseq number 6))
(condition () (error "Problem pretty printing phone number: ~a" number))))
(defun format-hr-timestamp (time)
"Formats a timestamp to a string of the form: MM DD, YYYY HH:MM AM/PM"
(declare (type (or null local-time:timestamp) time))
(when time
(format-timestring nil time
:format '(:short-month " " :day ", " :year " ":hour12 ":" (:min 2) " " :ampm))))
extension to yason JSON encoder
(defmethod yason:encode ((object float) &optional (stream *standard-output*))
(format stream "~F" object))
|
dd2e4b96fd745c233f93b70335b00a8a9d6ad271cce742919161a27560b76bbe | ZHaskell/z-data | Builder.hs | |
Module : Z.Data . Builder
Description : Efficient serialization / format .
Copyright : ( c ) , 2017 - 2018
License : BSD
Maintainer :
Stability : experimental
Portability : non - portable
A ' Builder ' records a buffer writing function , which can be ' mappend ' in O(1 )
via composition . This module provides many functions to turn basic data types
into ' Builder 's , which can used to build strict ' Bytes ' or list of ' Bytes ' chunks .
Module : Z.Data.Builder
Description : Efficient serialization/format.
Copyright : (c) Dong Han, 2017-2018
License : BSD
Maintainer :
Stability : experimental
Portability : non-portable
A 'Builder' records a buffer writing function, which can be 'mappend' in O(1)
via composition. This module provides many functions to turn basic data types
into 'Builder's, which can used to build strict 'Bytes' or list of 'Bytes' chunks.
-}
module Z.Data.Builder
( -- * Builder type
Builder
, append
-- * Running builders
, build
, buildWith
, buildChunks
, buildChunksWith
, buildText
, unsafeBuildText
-- * Basic buiders
, bytes
, ensureN
, writeN
* Pritimive builders
, encodePrim
, BE(..), LE(..)
, encodePrimLE
, encodePrimBE
-- * More builders
, stringModifiedUTF8, charModifiedUTF8, stringUTF8
, charUTF8, string7, char7, word7, string8, char8, word8, word8N, text
-- * Numeric builders
-- ** Integral type formatting
, IFormat(..)
, defaultIFormat
, Padding(..)
, int
, intWith
, integer
* * size hexidecimal formatting
, hex, hexUpper
-- ** IEEE float formating
, FFormat(..)
, double
, doubleWith
, float
, floatWith
, scientific
, scientific'
, scientificWith
-- * Builder helpers
, paren, parenWhen, curly, square, angle, quotes, squotes, colon, comma, intercalateVec, intercalateList
-- * Time
, day
, timeOfDay
, timeZone
, utcTime
, localTime
, zonedTime
-- * UUID
, uuid, uuidUpper, encodeUUID
-- * Specialized primitive builder
, encodeWord , encodeWord64, encodeWord32, encodeWord16, encodeWord8
, encodeInt , encodeInt64 , encodeInt32 , encodeInt16 , encodeInt8 , encodeDouble, encodeFloat
, encodeWordLE , encodeWord64LE , encodeWord32LE , encodeWord16LE
, encodeIntLE , encodeInt64LE , encodeInt32LE , encodeInt16LE , encodeDoubleLE , encodeFloatLE
, encodeWordBE , encodeWord64BE , encodeWord32BE , encodeWord16BE
, encodeIntBE , encodeInt64BE , encodeInt32BE , encodeInt16BE , encodeDoubleBE , encodeFloatBE
) where
import Z.Data.Builder.Base
import Z.Data.Builder.Numeric
import Z.Data.Builder.Time
import Z.Data.Builder.UUID
import Prelude ()
| null | https://raw.githubusercontent.com/ZHaskell/z-data/64f43e58c608b322dbe05ff7e3773f79ec6b1d39/Z/Data/Builder.hs | haskell | * Builder type
* Running builders
* Basic buiders
* More builders
* Numeric builders
** Integral type formatting
** IEEE float formating
* Builder helpers
* Time
* UUID
* Specialized primitive builder | |
Module : Z.Data . Builder
Description : Efficient serialization / format .
Copyright : ( c ) , 2017 - 2018
License : BSD
Maintainer :
Stability : experimental
Portability : non - portable
A ' Builder ' records a buffer writing function , which can be ' mappend ' in O(1 )
via composition . This module provides many functions to turn basic data types
into ' Builder 's , which can used to build strict ' Bytes ' or list of ' Bytes ' chunks .
Module : Z.Data.Builder
Description : Efficient serialization/format.
Copyright : (c) Dong Han, 2017-2018
License : BSD
Maintainer :
Stability : experimental
Portability : non-portable
A 'Builder' records a buffer writing function, which can be 'mappend' in O(1)
via composition. This module provides many functions to turn basic data types
into 'Builder's, which can used to build strict 'Bytes' or list of 'Bytes' chunks.
-}
module Z.Data.Builder
Builder
, append
, build
, buildWith
, buildChunks
, buildChunksWith
, buildText
, unsafeBuildText
, bytes
, ensureN
, writeN
* Pritimive builders
, encodePrim
, BE(..), LE(..)
, encodePrimLE
, encodePrimBE
, stringModifiedUTF8, charModifiedUTF8, stringUTF8
, charUTF8, string7, char7, word7, string8, char8, word8, word8N, text
, IFormat(..)
, defaultIFormat
, Padding(..)
, int
, intWith
, integer
* * size hexidecimal formatting
, hex, hexUpper
, FFormat(..)
, double
, doubleWith
, float
, floatWith
, scientific
, scientific'
, scientificWith
, paren, parenWhen, curly, square, angle, quotes, squotes, colon, comma, intercalateVec, intercalateList
, day
, timeOfDay
, timeZone
, utcTime
, localTime
, zonedTime
, uuid, uuidUpper, encodeUUID
, encodeWord , encodeWord64, encodeWord32, encodeWord16, encodeWord8
, encodeInt , encodeInt64 , encodeInt32 , encodeInt16 , encodeInt8 , encodeDouble, encodeFloat
, encodeWordLE , encodeWord64LE , encodeWord32LE , encodeWord16LE
, encodeIntLE , encodeInt64LE , encodeInt32LE , encodeInt16LE , encodeDoubleLE , encodeFloatLE
, encodeWordBE , encodeWord64BE , encodeWord32BE , encodeWord16BE
, encodeIntBE , encodeInt64BE , encodeInt32BE , encodeInt16BE , encodeDoubleBE , encodeFloatBE
) where
import Z.Data.Builder.Base
import Z.Data.Builder.Numeric
import Z.Data.Builder.Time
import Z.Data.Builder.UUID
import Prelude ()
|
41ad28b7177f5837f6b927b2aedfaf747be524cf90e334040c9f486dc5eb93dc | ctford/whelmed | dolorem_ipsum.clj | (ns whelmed.songs.dolorem-ipsum
(:require
[leipzig.melody :refer :all]
[leipzig.live :refer :all]
[whelmed.melody :refer :all]
[leipzig.scale :refer :all]
[leipzig.chord :refer :all]
[leipzig.canon :refer :all]
[leipzig.temperament :as temperament]
[whelmed.instrument :refer :all]))
; Extra concepts
(defn arpeggiate [chord ks duration]
(map
(fn [k time] {:time time :pitch (chord k) :duration duration})
ks
(reductions + 0 (repeat duration))))
(def sixth (-> triad (assoc :vi 5)))
; Melody
(def neque
(->>
(phrase
[1/2 1/2 1/2 1/4 1/4 1/2 1/2 1/2 1/4 1/4]
[4 4 5 4 5 6 8 5 4 5])
(times 2)
(but 3.5 4 (phrase [1/8 1/8 1/8 1/8] [4 5 4 5]))
(all :part ::melody)))
(def sit-amet
(->>
(phrase
[4 1 3]
[4 6 5])
(all :part ::melody)))
(def notice
(->>
(phrase
[1 5/2 1/4 1/4 2 2 4 1 2.5 1/4 1/4 4 4]
[5 4 2 3 4 7 6 6 5 4 3 4 2.5])
(all :part ::melody)))
(def finale
(let [alt-chords [(-> triad (inversion 2) (root 3) (update-in [:i] #(- % 1/2)))
(-> triad (inversion 1) (root 6))]]
(->>
(times 2 (mapthen #(->> (arpeggiate % [:i :v :i :iii] 1/4) (times 4)) alt-chords))
(then (times 2 (mapthen #(->> (arpeggiate % [:i :v :i :iii] 1/2) (times 2)) alt-chords)))
(all :part ::arpeggios)
(with (->> (phrase (repeat 8 4) (cycle [0 -1])) (all :part ::oooh))))))
; Arpeggios
(def theme
(let [up
#(-> % (augment :iii 1) (augment :v 1))
chords
[triad (up triad) (up (up triad)) (up triad)]]
(->> chords
(mapthen #(arpeggiate % [:v :i :iii :v] 1/4))
(times 2)
(all :part ::arpeggios))))
(def response
(->>
(arpeggiate (-> triad (root 4) (inversion 2))
[:i :v :i :iii] 1/4)
(times 4)
(then
(->> (arpeggiate (-> sixth (root 1))
[:v :iii :i :vi] 1/4)
(times 4)))
(all :part ::arpeggios)))
(def wander
(->>
(arpeggiate (-> triad (root 2))
[:iii :i :iii :v] 1/4)
(times 4)
(wherever (between? 15/4 16/4), :pitch inc)
(then
(->> (arpeggiate (-> sixth (root 2))
[:v :iii :i :vi] 1/4)
(times 4)))
(then
response)
(then
(->> (arpeggiate (-> triad (root 4) (inversion 2))
[:i :v :i :iii] 1/4)
(times 4)))
(then
(->> (arpeggiate
(-> triad (root 4) (inversion 2) (augment :i -3/2))
[:i :v :i :iii] 1/4)
(times 4)))
(all :part ::arpeggios)))
; Oooh
(def aaah
(->> (phrase [1 1] [6 5]) (times 4)
(all :part ::oooh)))
(def oooh-aaah
(->>
(phrase
[1 1 1 1]
[2 3 4 3])
(canon (interval -5))
(with (phrase [1 1 1 1] [0 0 0 0]))
(times 2)
(then
(->> aaah (with (phrase [2 2 2 2] [4 4 3 3]))
(with (phrase [1 1 1 1] [1 1 1 1]))))
(all :part ::oooh)
(with (->> (phrase (repeat 16 1/2) (repeat 7))
(then (phrase (repeat 8 1/2) (repeat 4)))
(then (phrase (repeat 8 1/2) (repeat 1)))
(all :part ::arpeggios)))))
(def la-la-la-la
(->>
(phrase [2 1 1/2 1/2 2 1 1/2 1/2 4]
[4 8 6 4 2 8 6 4 1])
(then (phrase [4] [3]))
(times 2)
(all :part ::oooh)))
(def wa-wa-wa-wa
(->>
(phrase [4 4 4 4 4 4] [4 7 8 10 11 8])
(all :part ::oooh)))
; Pull it all together
(def dolorem-ipsum
"Neque porro quisquam est
qui dolorem ipsum quia dolor sit amet,
consectetur,
adipisci velit.
I am the captain of my fate.
I don't choose pain for its own sake.
It's just a trick to hold my place.
I've lost my sense but not my shape."
(let [lorem (->> theme (then response))
intro (->> lorem (with (->> neque (then sit-amet))) (times 2))
development (->> wander (with notice))]
(->> lorem
(then intro)
(then development)
(then (->> theme (wherever (between? 4 8), :pitch raise)))
(then (->> theme (with neque)))
(then oooh-aaah)
(then (->> intro (with la-la-la-la)
(then (with development wa-wa-wa-wa))
(then finale)))
(tempo (comp (bpm 40) (accelerando 0 4 1/2)))
(where :pitch (comp temperament/equal F lydian)))))
; The arrangement
(defmethod play-note ::melody [{:keys [pitch duration]}]
(some-> pitch (bell (* 7 duration) :position 1/8 :wet 0.5 :volume 0.5))
(some-> pitch (bell (* 8 duration) :position 1/9 :wet 0.9 :room 0.2 :volume 0.3)))
(defmethod play-note ::arpeggios [{:keys [pitch duration]}]
(some-> pitch (/ 2) (brassy duration 0.3 0.1 :noise 9 :pan -1/3 :p 3/3 :wet 0.4 :vol 0.2 :p 8/6))
(some-> pitch (/ 2) (corgan 0.2 :depth 0.3 :walk 0.5 :pan 1/3 :wet 0.4 :vol 0.4 :room 0.5)))
(defmethod play-note ::oooh [{:keys [pitch duration]}]
(some-> pitch (groan (* 2 duration) :low 10 :vibrato 8/3 :position -1/6 :volume 0.1))
(some-> pitch (sing duration :pan 1/6 :volume 0.6)))
(comment
(->> dolorem-ipsum play)
(-> dolorem-ipsum var jam)
)
| null | https://raw.githubusercontent.com/ctford/whelmed/d396314654c95ddea599a1f55ecadea48989c2be/src/whelmed/songs/dolorem_ipsum.clj | clojure | Extra concepts
Melody
Arpeggios
Oooh
Pull it all together
The arrangement | (ns whelmed.songs.dolorem-ipsum
(:require
[leipzig.melody :refer :all]
[leipzig.live :refer :all]
[whelmed.melody :refer :all]
[leipzig.scale :refer :all]
[leipzig.chord :refer :all]
[leipzig.canon :refer :all]
[leipzig.temperament :as temperament]
[whelmed.instrument :refer :all]))
(defn arpeggiate [chord ks duration]
(map
(fn [k time] {:time time :pitch (chord k) :duration duration})
ks
(reductions + 0 (repeat duration))))
(def sixth (-> triad (assoc :vi 5)))
(def neque
(->>
(phrase
[1/2 1/2 1/2 1/4 1/4 1/2 1/2 1/2 1/4 1/4]
[4 4 5 4 5 6 8 5 4 5])
(times 2)
(but 3.5 4 (phrase [1/8 1/8 1/8 1/8] [4 5 4 5]))
(all :part ::melody)))
(def sit-amet
(->>
(phrase
[4 1 3]
[4 6 5])
(all :part ::melody)))
(def notice
(->>
(phrase
[1 5/2 1/4 1/4 2 2 4 1 2.5 1/4 1/4 4 4]
[5 4 2 3 4 7 6 6 5 4 3 4 2.5])
(all :part ::melody)))
(def finale
(let [alt-chords [(-> triad (inversion 2) (root 3) (update-in [:i] #(- % 1/2)))
(-> triad (inversion 1) (root 6))]]
(->>
(times 2 (mapthen #(->> (arpeggiate % [:i :v :i :iii] 1/4) (times 4)) alt-chords))
(then (times 2 (mapthen #(->> (arpeggiate % [:i :v :i :iii] 1/2) (times 2)) alt-chords)))
(all :part ::arpeggios)
(with (->> (phrase (repeat 8 4) (cycle [0 -1])) (all :part ::oooh))))))
(def theme
(let [up
#(-> % (augment :iii 1) (augment :v 1))
chords
[triad (up triad) (up (up triad)) (up triad)]]
(->> chords
(mapthen #(arpeggiate % [:v :i :iii :v] 1/4))
(times 2)
(all :part ::arpeggios))))
(def response
(->>
(arpeggiate (-> triad (root 4) (inversion 2))
[:i :v :i :iii] 1/4)
(times 4)
(then
(->> (arpeggiate (-> sixth (root 1))
[:v :iii :i :vi] 1/4)
(times 4)))
(all :part ::arpeggios)))
(def wander
(->>
(arpeggiate (-> triad (root 2))
[:iii :i :iii :v] 1/4)
(times 4)
(wherever (between? 15/4 16/4), :pitch inc)
(then
(->> (arpeggiate (-> sixth (root 2))
[:v :iii :i :vi] 1/4)
(times 4)))
(then
response)
(then
(->> (arpeggiate (-> triad (root 4) (inversion 2))
[:i :v :i :iii] 1/4)
(times 4)))
(then
(->> (arpeggiate
(-> triad (root 4) (inversion 2) (augment :i -3/2))
[:i :v :i :iii] 1/4)
(times 4)))
(all :part ::arpeggios)))
(def aaah
(->> (phrase [1 1] [6 5]) (times 4)
(all :part ::oooh)))
(def oooh-aaah
(->>
(phrase
[1 1 1 1]
[2 3 4 3])
(canon (interval -5))
(with (phrase [1 1 1 1] [0 0 0 0]))
(times 2)
(then
(->> aaah (with (phrase [2 2 2 2] [4 4 3 3]))
(with (phrase [1 1 1 1] [1 1 1 1]))))
(all :part ::oooh)
(with (->> (phrase (repeat 16 1/2) (repeat 7))
(then (phrase (repeat 8 1/2) (repeat 4)))
(then (phrase (repeat 8 1/2) (repeat 1)))
(all :part ::arpeggios)))))
(def la-la-la-la
(->>
(phrase [2 1 1/2 1/2 2 1 1/2 1/2 4]
[4 8 6 4 2 8 6 4 1])
(then (phrase [4] [3]))
(times 2)
(all :part ::oooh)))
(def wa-wa-wa-wa
(->>
(phrase [4 4 4 4 4 4] [4 7 8 10 11 8])
(all :part ::oooh)))
(def dolorem-ipsum
"Neque porro quisquam est
qui dolorem ipsum quia dolor sit amet,
consectetur,
adipisci velit.
I am the captain of my fate.
I don't choose pain for its own sake.
It's just a trick to hold my place.
I've lost my sense but not my shape."
(let [lorem (->> theme (then response))
intro (->> lorem (with (->> neque (then sit-amet))) (times 2))
development (->> wander (with notice))]
(->> lorem
(then intro)
(then development)
(then (->> theme (wherever (between? 4 8), :pitch raise)))
(then (->> theme (with neque)))
(then oooh-aaah)
(then (->> intro (with la-la-la-la)
(then (with development wa-wa-wa-wa))
(then finale)))
(tempo (comp (bpm 40) (accelerando 0 4 1/2)))
(where :pitch (comp temperament/equal F lydian)))))
(defmethod play-note ::melody [{:keys [pitch duration]}]
(some-> pitch (bell (* 7 duration) :position 1/8 :wet 0.5 :volume 0.5))
(some-> pitch (bell (* 8 duration) :position 1/9 :wet 0.9 :room 0.2 :volume 0.3)))
(defmethod play-note ::arpeggios [{:keys [pitch duration]}]
(some-> pitch (/ 2) (brassy duration 0.3 0.1 :noise 9 :pan -1/3 :p 3/3 :wet 0.4 :vol 0.2 :p 8/6))
(some-> pitch (/ 2) (corgan 0.2 :depth 0.3 :walk 0.5 :pan 1/3 :wet 0.4 :vol 0.4 :room 0.5)))
(defmethod play-note ::oooh [{:keys [pitch duration]}]
(some-> pitch (groan (* 2 duration) :low 10 :vibrato 8/3 :position -1/6 :volume 0.1))
(some-> pitch (sing duration :pan 1/6 :volume 0.6)))
(comment
(->> dolorem-ipsum play)
(-> dolorem-ipsum var jam)
)
|
467d2e21f6e6f0579a98a6afe91054335adfb39dcb2d1fd5ec5b44854b52309b | 8c6794b6/haskell-sc-scratch | CatList.hs | # LANGUAGE NoImplicitPrelude #
|
module : $ Header$
CopyRight : ( c ) 8c6794b6
License : :
Stability : unstable
Portability : non - portable
Scratch written while reading
/purely functional data structure/ , by .
Catenable list , showin in Figure 7.5 .
module : $Header$
CopyRight : (c) 8c6794b6
License : BSD3
Maintainer :
Stability : unstable
Portability : non-portable
Scratch written while reading
/purely functional data structure/, by Chris Okasaki.
Catenable list, showin in Figure 7.5.
-}
module Bootstrap.CatList where
import Prelude hiding (head, tail, (++))
import Queue.Initial (emptyQueueException)
import qualified Bootstrap.BSQueue as Q
data Cat a = Empty | Cat a (Q.Queue (Cat a)) deriving (Show)
empty :: Cat a
empty = Empty
isEmpty :: Cat a -> Bool
isEmpty c = case c of Empty -> True; _ -> False
link :: Cat a -> Cat a -> Cat a
link (Cat x q) s = Cat x (Q.snoc s q)
linkAll :: Q.Queue (Cat a) -> Cat a
linkAll Q.Empty = Empty
linkAll q = case (Q.head q, Q.tail q) of
(t, q') | Q.isEmpty q' -> t
| otherwise -> link t (linkAll q')
(++) :: Cat a -> Cat a -> Cat a
xs ++ ys = case (xs,ys) of
(_,Empty) -> xs
(Empty,_) -> ys
_ -> link xs ys
cons :: a -> Cat a -> Cat a
cons a xs = Cat a Q.empty ++ xs
snoc :: a -> Cat a -> Cat a
snoc a xs = xs ++ Cat a Q.empty
head :: Cat a -> a
head c = case c of
Empty -> emptyQueueException
Cat x _ -> x
tail :: Cat a -> Cat a
tail q = case q of
Empty -> emptyQueueException
Cat x q' | Q.isEmpty q' -> Empty
| otherwise -> linkAll q'
------------------------------------------------------------------------------
-- Test
toList :: Cat a -> [a]
toList c = case c of
Empty -> []
Cat a q -> a : concatMap toList (Q.toList q) | null | https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/Scratch/FP/PFDS/Bootstrap/CatList.hs | haskell | ----------------------------------------------------------------------------
Test | # LANGUAGE NoImplicitPrelude #
|
module : $ Header$
CopyRight : ( c ) 8c6794b6
License : :
Stability : unstable
Portability : non - portable
Scratch written while reading
/purely functional data structure/ , by .
Catenable list , showin in Figure 7.5 .
module : $Header$
CopyRight : (c) 8c6794b6
License : BSD3
Maintainer :
Stability : unstable
Portability : non-portable
Scratch written while reading
/purely functional data structure/, by Chris Okasaki.
Catenable list, showin in Figure 7.5.
-}
module Bootstrap.CatList where
import Prelude hiding (head, tail, (++))
import Queue.Initial (emptyQueueException)
import qualified Bootstrap.BSQueue as Q
data Cat a = Empty | Cat a (Q.Queue (Cat a)) deriving (Show)
empty :: Cat a
empty = Empty
isEmpty :: Cat a -> Bool
isEmpty c = case c of Empty -> True; _ -> False
link :: Cat a -> Cat a -> Cat a
link (Cat x q) s = Cat x (Q.snoc s q)
linkAll :: Q.Queue (Cat a) -> Cat a
linkAll Q.Empty = Empty
linkAll q = case (Q.head q, Q.tail q) of
(t, q') | Q.isEmpty q' -> t
| otherwise -> link t (linkAll q')
(++) :: Cat a -> Cat a -> Cat a
xs ++ ys = case (xs,ys) of
(_,Empty) -> xs
(Empty,_) -> ys
_ -> link xs ys
cons :: a -> Cat a -> Cat a
cons a xs = Cat a Q.empty ++ xs
snoc :: a -> Cat a -> Cat a
snoc a xs = xs ++ Cat a Q.empty
head :: Cat a -> a
head c = case c of
Empty -> emptyQueueException
Cat x _ -> x
tail :: Cat a -> Cat a
tail q = case q of
Empty -> emptyQueueException
Cat x q' | Q.isEmpty q' -> Empty
| otherwise -> linkAll q'
toList :: Cat a -> [a]
toList c = case c of
Empty -> []
Cat a q -> a : concatMap toList (Q.toList q) |
26a13b7cdd09901a5f53367395c1190fb7297edc0cd19fb2c87bb072eaa479f6 | BinaryAnalysisPlatform/bap | bap_primus_memory.mli | open Core_kernel[@@warning "-D"]
open Bap.Std
open Bap_primus_types
module Generator = Bap_primus_generator
val generated : (addr * value) Bap_primus_observation.t
type exn += Pagefault of addr
type memory
module Descriptor : sig
type t = memory [@@deriving compare, sexp_of]
val create : addr_size:int -> data_size:int -> string -> memory
val unknown : addr_size:int -> data_size:int -> memory
val name : memory -> string
val addr_size : memory -> int
val data_size : memory -> int
include Comparable.S with type t := memory
end
module Make(Machine : Machine) : sig
val switch : memory -> unit Machine.t
val memory : memory Machine.t
val load : addr -> word Machine.t
val store : addr -> word -> unit Machine.t
val store_never_fail : addr -> word -> unit Machine.t
val get : addr -> value Machine.t
val set : addr -> value -> unit Machine.t
val set_never_fail : addr -> value -> unit Machine.t
val del : addr -> unit Machine.t
val add_text : mem -> unit Machine.t
val add_data : mem -> unit Machine.t
val add_region :
?readonly:bool ->
?executable:bool ->
?init:(addr -> word Machine.t) ->
?generator:Generator.t ->
lower:addr -> upper:addr -> unit -> unit Machine.t
val allocate :
?readonly:bool ->
?executable:bool ->
?init:(addr -> word Machine.t) ->
?generator:Generator.t ->
addr -> int -> unit Machine.t
val map :
?readonly:bool ->
?executable:bool ->
mem -> unit Machine.t
val is_mapped : addr -> bool Machine.t
val is_writable : addr -> bool Machine.t
end
| null | https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/f995d28a4a34abb4cef8e0b3bd3c41cd710ccf1a/lib/bap_primus/bap_primus_memory.mli | ocaml | open Core_kernel[@@warning "-D"]
open Bap.Std
open Bap_primus_types
module Generator = Bap_primus_generator
val generated : (addr * value) Bap_primus_observation.t
type exn += Pagefault of addr
type memory
module Descriptor : sig
type t = memory [@@deriving compare, sexp_of]
val create : addr_size:int -> data_size:int -> string -> memory
val unknown : addr_size:int -> data_size:int -> memory
val name : memory -> string
val addr_size : memory -> int
val data_size : memory -> int
include Comparable.S with type t := memory
end
module Make(Machine : Machine) : sig
val switch : memory -> unit Machine.t
val memory : memory Machine.t
val load : addr -> word Machine.t
val store : addr -> word -> unit Machine.t
val store_never_fail : addr -> word -> unit Machine.t
val get : addr -> value Machine.t
val set : addr -> value -> unit Machine.t
val set_never_fail : addr -> value -> unit Machine.t
val del : addr -> unit Machine.t
val add_text : mem -> unit Machine.t
val add_data : mem -> unit Machine.t
val add_region :
?readonly:bool ->
?executable:bool ->
?init:(addr -> word Machine.t) ->
?generator:Generator.t ->
lower:addr -> upper:addr -> unit -> unit Machine.t
val allocate :
?readonly:bool ->
?executable:bool ->
?init:(addr -> word Machine.t) ->
?generator:Generator.t ->
addr -> int -> unit Machine.t
val map :
?readonly:bool ->
?executable:bool ->
mem -> unit Machine.t
val is_mapped : addr -> bool Machine.t
val is_writable : addr -> bool Machine.t
end
| |
da1c25b7c6648bec31c6b1e4549429e03d847c74fd82b2c71120086232fa518a | hstreamdb/hstream | HsGrpcHandler.hs | {-# LANGUAGE CPP #-}
# LANGUAGE DataKinds #
module HStream.Server.HsGrpcHandler (handlers) where
import HsGrpc.Server
import qualified HStream.Server.Handler.Admin as H
import qualified HStream.Server.Handler.Cluster as H
import qualified HStream.Server.Handler.Connector as H
import qualified HStream.Server.Handler.Query as H
import qualified HStream.Server.Handler.Stats as H
import qualified HStream.Server.Handler.Stream as H
import qualified HStream.Server.Handler.Subscription as H
import qualified HStream.Server.Handler.View as H
import qualified HStream.Server.HStreamApi as A
import HStream.Server.Types (ServerContext (..))
import qualified Proto.HStream.Server.HStreamApi as P
-------------------------------------------------------------------------------
handlers :: ServerContext -> [ServiceHandler]
handlers sc =
[ unary (GRPC :: GRPC P.HStreamApi "echo") handleEcho
-- Cluster
, unary (GRPC :: GRPC P.HStreamApi "describeCluster") (H.handleDescribeCluster sc)
, unary (GRPC :: GRPC P.HStreamApi "lookupResource") (H.handleLookupResource sc)
, unary (GRPC :: GRPC P.HStreamApi "lookupShard") (H.handleLookupShard sc)
, unary (GRPC :: GRPC P.HStreamApi "lookupSubscription") (H.handleLookupSubscription sc)
, unary (GRPC :: GRPC P.HStreamApi "lookupShardReader") (H.handleLookupShardReader sc)
, unary (GRPC :: GRPC P.HStreamApi "lookupConnector") (H.handleLookupConnector sc)
-- Stream
, unary (GRPC :: GRPC P.HStreamApi "createStream") (H.handleCreateStream sc)
, unary (GRPC :: GRPC P.HStreamApi "deleteStream") (H.handleDeleteStream sc)
, unary (GRPC :: GRPC P.HStreamApi "getStream") (H.handleGetStream sc)
, unary (GRPC :: GRPC P.HStreamApi "listStreams") (H.handleListStreams sc)
, unary (GRPC :: GRPC P.HStreamApi "listStreamsWithPrefix") (H.handleListStreamsWithPrefix sc)
, unary (GRPC :: GRPC P.HStreamApi "listShards") (H.handleListShard sc)
-- Reader
, unary (GRPC :: GRPC P.HStreamApi "listShardReaders") (H.handleListShardReaders sc)
, unary (GRPC :: GRPC P.HStreamApi "createShardReader") (H.handleCreateShardReader sc)
, unary (GRPC :: GRPC P.HStreamApi "deleteShardReader") (H.handleDeleteShardReader sc)
Subscription
, unary (GRPC :: GRPC P.HStreamApi "createSubscription") (H.handleCreateSubscription sc)
, unary (GRPC :: GRPC P.HStreamApi "getSubscription") (H.handleGetSubscription sc)
, handlerUseThreadPool $ unary (GRPC :: GRPC P.HStreamApi "deleteSubscription") (H.handleDeleteSubscription sc)
, unary (GRPC :: GRPC P.HStreamApi "listSubscriptions") (H.handleListSubscriptions sc)
, unary (GRPC :: GRPC P.HStreamApi "listSubscriptionsWithPrefix") (H.handleListSubscriptionsWithPrefix sc)
, unary (GRPC :: GRPC P.HStreamApi "listConsumers") (H.handleListConsumers sc)
, unary (GRPC :: GRPC P.HStreamApi "checkSubscriptionExist") (H.handleCheckSubscriptionExist sc)
-- Append
, unary (GRPC :: GRPC P.HStreamApi "append") (H.handleAppend sc)
-- Read
, unary (GRPC :: GRPC P.HStreamApi "readShard") (H.handleReadShard sc)
-- Subscribe
, bidiStream (GRPC :: GRPC P.HStreamApi "streamingFetch") (H.handleStreamingFetch sc)
-- Stats
, unary (GRPC :: GRPC P.HStreamApi "perStreamTimeSeriesStats") (H.handlePerStreamTimeSeriesStats $ scStatsHolder sc)
, unary (GRPC :: GRPC P.HStreamApi "perStreamTimeSeriesStatsAll") (H.handlePerStreamTimeSeriesStatsAll $ scStatsHolder sc)
, unary (GRPC :: GRPC P.HStreamApi "getStats") (H.handleGetStats $ scStatsHolder sc)
-- Admin
, unary (GRPC :: GRPC P.HStreamApi "sendAdminCommand") (H.handleAdminCommand sc)
Connector
, unary (GRPC :: GRPC P.HStreamApi "createConnector") (H.handleCreateConnector sc)
, unary (GRPC :: GRPC P.HStreamApi "listConnectors") (H.handleListConnectors sc)
, unary (GRPC :: GRPC P.HStreamApi "getConnector") (H.handleGetConnector sc)
, unary (GRPC :: GRPC P.HStreamApi "deleteConnector") (H.handleDeleteConnector sc)
, unary (GRPC :: GRPC P.HStreamApi "resumeConnector") (H.handleResumeConnector sc)
, unary (GRPC :: GRPC P.HStreamApi "pauseConnector") (H.handlePauseConnector sc)
-- View
, unary (GRPC :: GRPC P.HStreamApi "getView") (H.handleGetView sc)
, unary (GRPC :: GRPC P.HStreamApi "listViews") (H.handleListView sc)
, unary (GRPC :: GRPC P.HStreamApi "deleteView") (H.handleDeleteView sc)
-- Query
, unary (GRPC :: GRPC P.HStreamApi "terminateQueries") (H.handleTerminateQueries sc)
, unary (GRPC :: GRPC P.HStreamApi "executeQuery") (H.handleExecuteQuery sc)
, unary (GRPC :: GRPC P.HStreamApi "getQuery") (H.handleGetQuery sc)
, unary (GRPC :: GRPC P.HStreamApi "createQuery") (H.handleCreateQuery sc)
, unary (GRPC :: GRPC P.HStreamApi "listQueries") (H.handleListQueries sc)
, unary (GRPC :: GRPC P.HStreamApi "deleteQuery") (H.handleDeleteQuery sc)
, unary (GRPC :: GRPC P.HStreamApi "restartQuery") (H.handleRestartQuery sc)
]
handleEcho :: UnaryHandler A.EchoRequest A.EchoResponse
handleEcho _grpcCtx A.EchoRequest{..} = return $ A.EchoResponse echoRequestMsg
| null | https://raw.githubusercontent.com/hstreamdb/hstream/2d57ea42fdba2af19330e1ba06ef30235f5e6a6f/hstream/src/HStream/Server/HsGrpcHandler.hs | haskell | # LANGUAGE CPP #
-----------------------------------------------------------------------------
Cluster
Stream
Reader
Append
Read
Subscribe
Stats
Admin
View
Query | # LANGUAGE DataKinds #
module HStream.Server.HsGrpcHandler (handlers) where
import HsGrpc.Server
import qualified HStream.Server.Handler.Admin as H
import qualified HStream.Server.Handler.Cluster as H
import qualified HStream.Server.Handler.Connector as H
import qualified HStream.Server.Handler.Query as H
import qualified HStream.Server.Handler.Stats as H
import qualified HStream.Server.Handler.Stream as H
import qualified HStream.Server.Handler.Subscription as H
import qualified HStream.Server.Handler.View as H
import qualified HStream.Server.HStreamApi as A
import HStream.Server.Types (ServerContext (..))
import qualified Proto.HStream.Server.HStreamApi as P
handlers :: ServerContext -> [ServiceHandler]
handlers sc =
[ unary (GRPC :: GRPC P.HStreamApi "echo") handleEcho
, unary (GRPC :: GRPC P.HStreamApi "describeCluster") (H.handleDescribeCluster sc)
, unary (GRPC :: GRPC P.HStreamApi "lookupResource") (H.handleLookupResource sc)
, unary (GRPC :: GRPC P.HStreamApi "lookupShard") (H.handleLookupShard sc)
, unary (GRPC :: GRPC P.HStreamApi "lookupSubscription") (H.handleLookupSubscription sc)
, unary (GRPC :: GRPC P.HStreamApi "lookupShardReader") (H.handleLookupShardReader sc)
, unary (GRPC :: GRPC P.HStreamApi "lookupConnector") (H.handleLookupConnector sc)
, unary (GRPC :: GRPC P.HStreamApi "createStream") (H.handleCreateStream sc)
, unary (GRPC :: GRPC P.HStreamApi "deleteStream") (H.handleDeleteStream sc)
, unary (GRPC :: GRPC P.HStreamApi "getStream") (H.handleGetStream sc)
, unary (GRPC :: GRPC P.HStreamApi "listStreams") (H.handleListStreams sc)
, unary (GRPC :: GRPC P.HStreamApi "listStreamsWithPrefix") (H.handleListStreamsWithPrefix sc)
, unary (GRPC :: GRPC P.HStreamApi "listShards") (H.handleListShard sc)
, unary (GRPC :: GRPC P.HStreamApi "listShardReaders") (H.handleListShardReaders sc)
, unary (GRPC :: GRPC P.HStreamApi "createShardReader") (H.handleCreateShardReader sc)
, unary (GRPC :: GRPC P.HStreamApi "deleteShardReader") (H.handleDeleteShardReader sc)
Subscription
, unary (GRPC :: GRPC P.HStreamApi "createSubscription") (H.handleCreateSubscription sc)
, unary (GRPC :: GRPC P.HStreamApi "getSubscription") (H.handleGetSubscription sc)
, handlerUseThreadPool $ unary (GRPC :: GRPC P.HStreamApi "deleteSubscription") (H.handleDeleteSubscription sc)
, unary (GRPC :: GRPC P.HStreamApi "listSubscriptions") (H.handleListSubscriptions sc)
, unary (GRPC :: GRPC P.HStreamApi "listSubscriptionsWithPrefix") (H.handleListSubscriptionsWithPrefix sc)
, unary (GRPC :: GRPC P.HStreamApi "listConsumers") (H.handleListConsumers sc)
, unary (GRPC :: GRPC P.HStreamApi "checkSubscriptionExist") (H.handleCheckSubscriptionExist sc)
, unary (GRPC :: GRPC P.HStreamApi "append") (H.handleAppend sc)
, unary (GRPC :: GRPC P.HStreamApi "readShard") (H.handleReadShard sc)
, bidiStream (GRPC :: GRPC P.HStreamApi "streamingFetch") (H.handleStreamingFetch sc)
, unary (GRPC :: GRPC P.HStreamApi "perStreamTimeSeriesStats") (H.handlePerStreamTimeSeriesStats $ scStatsHolder sc)
, unary (GRPC :: GRPC P.HStreamApi "perStreamTimeSeriesStatsAll") (H.handlePerStreamTimeSeriesStatsAll $ scStatsHolder sc)
, unary (GRPC :: GRPC P.HStreamApi "getStats") (H.handleGetStats $ scStatsHolder sc)
, unary (GRPC :: GRPC P.HStreamApi "sendAdminCommand") (H.handleAdminCommand sc)
Connector
, unary (GRPC :: GRPC P.HStreamApi "createConnector") (H.handleCreateConnector sc)
, unary (GRPC :: GRPC P.HStreamApi "listConnectors") (H.handleListConnectors sc)
, unary (GRPC :: GRPC P.HStreamApi "getConnector") (H.handleGetConnector sc)
, unary (GRPC :: GRPC P.HStreamApi "deleteConnector") (H.handleDeleteConnector sc)
, unary (GRPC :: GRPC P.HStreamApi "resumeConnector") (H.handleResumeConnector sc)
, unary (GRPC :: GRPC P.HStreamApi "pauseConnector") (H.handlePauseConnector sc)
, unary (GRPC :: GRPC P.HStreamApi "getView") (H.handleGetView sc)
, unary (GRPC :: GRPC P.HStreamApi "listViews") (H.handleListView sc)
, unary (GRPC :: GRPC P.HStreamApi "deleteView") (H.handleDeleteView sc)
, unary (GRPC :: GRPC P.HStreamApi "terminateQueries") (H.handleTerminateQueries sc)
, unary (GRPC :: GRPC P.HStreamApi "executeQuery") (H.handleExecuteQuery sc)
, unary (GRPC :: GRPC P.HStreamApi "getQuery") (H.handleGetQuery sc)
, unary (GRPC :: GRPC P.HStreamApi "createQuery") (H.handleCreateQuery sc)
, unary (GRPC :: GRPC P.HStreamApi "listQueries") (H.handleListQueries sc)
, unary (GRPC :: GRPC P.HStreamApi "deleteQuery") (H.handleDeleteQuery sc)
, unary (GRPC :: GRPC P.HStreamApi "restartQuery") (H.handleRestartQuery sc)
]
handleEcho :: UnaryHandler A.EchoRequest A.EchoResponse
handleEcho _grpcCtx A.EchoRequest{..} = return $ A.EchoResponse echoRequestMsg
|
d6f87a5cc8166d5e5e8fcd18f787f80615ce64d4313b143d3cd30b3891f026fa | Elzair/nazghul | raise-merciful-death.scm | (define merciful-death-x 121)
(define merciful-death-y 87)
(define (raise-merciful-death)
(let ((loc (mk-loc p_shard
merciful-death-x
merciful-death-y)))
(kern-log-msg "From her watery grave...")
(kern-log-msg "...THE MERCIFUL DEATH ARISES!")
(shake-map 10)
(kern-place-set-subplace p_merciful_death loc)
(kern-map-set-dirty)
))
| null | https://raw.githubusercontent.com/Elzair/nazghul/8f3a45ed6289cd9f469c4ff618d39366f2fbc1d8/worlds/haxima-1.002/raise-merciful-death.scm | scheme | (define merciful-death-x 121)
(define merciful-death-y 87)
(define (raise-merciful-death)
(let ((loc (mk-loc p_shard
merciful-death-x
merciful-death-y)))
(kern-log-msg "From her watery grave...")
(kern-log-msg "...THE MERCIFUL DEATH ARISES!")
(shake-map 10)
(kern-place-set-subplace p_merciful_death loc)
(kern-map-set-dirty)
))
| |
a97903d044e761342e7b1a1ce241d925546fe9e7913b406426c647ef549b81fd | mtesseract/nakadi-client | Cursors.hs | |
Module : Network . . Subscriptions . Cursors
Description : Implementation of Nakadi Subscription Cursors API
Copyright : ( c ) 2017 , 2018
License : :
Stability : experimental
Portability : POSIX
This module implements the @\/subscriptions\/SUBSCRIPTIONS\/cursors@
API .
Module : Network.Nakadi.Subscriptions.Cursors
Description : Implementation of Nakadi Subscription Cursors API
Copyright : (c) Moritz Clasmeier 2017, 2018
License : BSD3
Maintainer :
Stability : experimental
Portability : POSIX
This module implements the @\/subscriptions\/SUBSCRIPTIONS\/cursors@
API.
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards #
module Network.Nakadi.Subscriptions.Cursors
( subscriptionCursorCommit'
, subscriptionCursorCommit
, subscriptionCursors
, subscriptionCursorsReset
)
where
import Network.Nakadi.Internal.Prelude
import Data.Aeson
import qualified Control.Exception.Safe as Safe
import Control.Lens
import qualified Data.HashMap.Lazy as HashMap
import Network.Nakadi.Internal.Conversions
import Network.Nakadi.Internal.Http
import Network.Nakadi.Internal.Lenses ( HasNakadiSubscriptionCursor )
import qualified Network.Nakadi.Internal.Lenses
as L
path :: SubscriptionId -> ByteString
path subscriptionId = "/subscriptions/" <> subscriptionIdToByteString subscriptionId <> "/cursors"
-- | @POST@ to @\/subscriptions\/SUBSCRIPTION-ID\/cursors@. Commits
-- cursors using low level interface.
subscriptionCursorCommit'
:: MonadNakadi b m
=> SubscriptionId -- ^ Subsciption ID
-> StreamId -- ^ Stream ID
^ Subscription Cursor to commit
-> m ()
subscriptionCursorCommit' subscriptionId streamId cursors = httpJsonNoBody
status204
[(ok200, errorCursorAlreadyCommitted)]
( setRequestMethod "POST"
. addRequestHeader "X-Nakadi-StreamId" (encodeUtf8 (unStreamId streamId))
. setRequestBodyJSON cursors
. setRequestPath (path subscriptionId)
)
| @POST@ to @\/subscriptions\/SUBSCRIPTION\/cursors@. Commits
-- cursors using high level interface.
subscriptionCursorCommit
:: (MonadNakadi b m, MonadCatch m, HasNakadiSubscriptionCursor a)
=> SubscriptionEventStream
-> [a] -- ^ Values containing Subscription Cursors to commit
-> m ()
subscriptionCursorCommit SubscriptionEventStream {..} as = Safe.catchJust
exceptionPredicate
(subscriptionCursorCommit' _subscriptionId _streamId cursorsCommit)
(const (return ()))
where
exceptionPredicate = \case
CursorAlreadyCommitted _ -> Just ()
_ -> Nothing
cursors = map (^. L.subscriptionCursor) as
cursorsCommit = SubscriptionCursorCommit cursors
-- | @GET@ to @\/subscriptions\/SUBSCRIPTION\/cursors@. Retrieves
-- subscriptions cursors.
subscriptionCursors
:: MonadNakadi b m
=> SubscriptionId -- ^ Subscription ID
^ Subscription Cursors for the specified Subscription
subscriptionCursors subscriptionId =
httpJsonBody ok200 [] (setRequestMethod "GET" . setRequestPath (path subscriptionId))
| @PATCH@ to @\/subscriptions\/SUBSCRIPTION\/cursors@. Resets
-- subscriptions cursors.
subscriptionCursorsReset
:: MonadNakadi b m
=> SubscriptionId -- ^ Subscription ID
-> [SubscriptionCursorWithoutToken] -- ^ Subscription Cursors to reset
-> m ()
subscriptionCursorsReset subscriptionId cursors = httpJsonNoBody
status204
[(status404, errorSubscriptionNotFound), (status409, errorCursorResetInProgress)]
(setRequestMethod "PATCH" . setRequestPath (path subscriptionId) . setRequestBodyJSON
(Object (HashMap.fromList [("items", toJSON cursors)]))
)
| null | https://raw.githubusercontent.com/mtesseract/nakadi-client/f8eef3ac215459081b01b0b48f0b430ae7701f52/src/Network/Nakadi/Subscriptions/Cursors.hs | haskell | # LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
| @POST@ to @\/subscriptions\/SUBSCRIPTION-ID\/cursors@. Commits
cursors using low level interface.
^ Subsciption ID
^ Stream ID
cursors using high level interface.
^ Values containing Subscription Cursors to commit
| @GET@ to @\/subscriptions\/SUBSCRIPTION\/cursors@. Retrieves
subscriptions cursors.
^ Subscription ID
subscriptions cursors.
^ Subscription ID
^ Subscription Cursors to reset | |
Module : Network . . Subscriptions . Cursors
Description : Implementation of Nakadi Subscription Cursors API
Copyright : ( c ) 2017 , 2018
License : :
Stability : experimental
Portability : POSIX
This module implements the @\/subscriptions\/SUBSCRIPTIONS\/cursors@
API .
Module : Network.Nakadi.Subscriptions.Cursors
Description : Implementation of Nakadi Subscription Cursors API
Copyright : (c) Moritz Clasmeier 2017, 2018
License : BSD3
Maintainer :
Stability : experimental
Portability : POSIX
This module implements the @\/subscriptions\/SUBSCRIPTIONS\/cursors@
API.
-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards #
module Network.Nakadi.Subscriptions.Cursors
( subscriptionCursorCommit'
, subscriptionCursorCommit
, subscriptionCursors
, subscriptionCursorsReset
)
where
import Network.Nakadi.Internal.Prelude
import Data.Aeson
import qualified Control.Exception.Safe as Safe
import Control.Lens
import qualified Data.HashMap.Lazy as HashMap
import Network.Nakadi.Internal.Conversions
import Network.Nakadi.Internal.Http
import Network.Nakadi.Internal.Lenses ( HasNakadiSubscriptionCursor )
import qualified Network.Nakadi.Internal.Lenses
as L
path :: SubscriptionId -> ByteString
path subscriptionId = "/subscriptions/" <> subscriptionIdToByteString subscriptionId <> "/cursors"
subscriptionCursorCommit'
:: MonadNakadi b m
^ Subscription Cursor to commit
-> m ()
subscriptionCursorCommit' subscriptionId streamId cursors = httpJsonNoBody
status204
[(ok200, errorCursorAlreadyCommitted)]
( setRequestMethod "POST"
. addRequestHeader "X-Nakadi-StreamId" (encodeUtf8 (unStreamId streamId))
. setRequestBodyJSON cursors
. setRequestPath (path subscriptionId)
)
| @POST@ to @\/subscriptions\/SUBSCRIPTION\/cursors@. Commits
subscriptionCursorCommit
:: (MonadNakadi b m, MonadCatch m, HasNakadiSubscriptionCursor a)
=> SubscriptionEventStream
-> m ()
subscriptionCursorCommit SubscriptionEventStream {..} as = Safe.catchJust
exceptionPredicate
(subscriptionCursorCommit' _subscriptionId _streamId cursorsCommit)
(const (return ()))
where
exceptionPredicate = \case
CursorAlreadyCommitted _ -> Just ()
_ -> Nothing
cursors = map (^. L.subscriptionCursor) as
cursorsCommit = SubscriptionCursorCommit cursors
subscriptionCursors
:: MonadNakadi b m
^ Subscription Cursors for the specified Subscription
subscriptionCursors subscriptionId =
httpJsonBody ok200 [] (setRequestMethod "GET" . setRequestPath (path subscriptionId))
| @PATCH@ to @\/subscriptions\/SUBSCRIPTION\/cursors@. Resets
subscriptionCursorsReset
:: MonadNakadi b m
-> m ()
subscriptionCursorsReset subscriptionId cursors = httpJsonNoBody
status204
[(status404, errorSubscriptionNotFound), (status409, errorCursorResetInProgress)]
(setRequestMethod "PATCH" . setRequestPath (path subscriptionId) . setRequestBodyJSON
(Object (HashMap.fromList [("items", toJSON cursors)]))
)
|
df355fdf335a106289bd66c1ac1e02b373214cd011a1ae780054ace98a79e911 | mwand/eopl3 | interp.scm | (module interp (lib "eopl.ss" "eopl")
cps interpreter for the LETREC language , using the data structure
representation of continuations ( Figure 5.3 ) .
;; exercise: rewrite this using the procedural representation of
continuations ( Figure 5.2 ) .
exercise : rewrite this using a trampoline ( page 159 ) .
(require "drscheme-init.scm")
(require "lang.scm")
(require "data-structures.scm")
(require "environments.scm")
(provide value-of-program value-of/k)
;;;;;;;;;;;;;;;; the interpreter ;;;;;;;;;;;;;;;;
;; value-of-program : Program -> FinalAnswer
Page : 143 and 154
(define value-of-program
(lambda (pgm)
(cases program pgm
(a-program (exp1)
(value-of/k exp1 (init-env) (end-cont))))))
;; value-of/k : Exp * Env * Cont -> FinalAnswer
Page : 143 - -146 , and 154
(define value-of/k
(lambda (exp env cont)
(cases expression exp
(const-exp (num) (apply-cont cont (num-val num)))
(var-exp (var) (apply-cont cont (apply-env env var)))
(proc-exp (var body)
(apply-cont cont
(proc-val (procedure var body env))))
(letrec-exp (p-name b-var p-body letrec-body)
(value-of/k letrec-body
(extend-env-rec p-name b-var p-body env)
cont))
(zero?-exp (exp1)
(value-of/k exp1 env
(zero1-cont cont)))
(let-exp (var exp1 body)
(value-of/k exp1 env
(let-exp-cont var body env cont)))
(if-exp (exp1 exp2 exp3)
(value-of/k exp1 env
(if-test-cont exp2 exp3 env cont)))
(diff-exp (exp1 exp2)
(value-of/k exp1 env
(diff1-cont exp2 env cont)))
(call-exp (rator rand)
(value-of/k rator env
(rator-cont rand env cont)))
)))
;; apply-cont : Cont * ExpVal -> FinalAnswer
Page : 148
(define apply-cont
(lambda (cont val)
(cases continuation cont
(end-cont ()
(begin
(eopl:printf
"End of computation.~%")
val))
;; or (logged-print val) ; if you use drscheme-init-cps.scm
(zero1-cont (saved-cont)
(apply-cont saved-cont
(bool-val
(zero? (expval->num val)))))
(let-exp-cont (var body saved-env saved-cont)
(value-of/k body
(extend-env var val saved-env) saved-cont))
(if-test-cont (exp2 exp3 saved-env saved-cont)
(if (expval->bool val)
(value-of/k exp2 saved-env saved-cont)
(value-of/k exp3 saved-env saved-cont)))
(diff1-cont (exp2 saved-env saved-cont)
(value-of/k exp2
saved-env (diff2-cont val saved-cont)))
(diff2-cont (val1 saved-cont)
(let ((num1 (expval->num val1))
(num2 (expval->num val)))
(apply-cont saved-cont
(num-val (- num1 num2)))))
(rator-cont (rand saved-env saved-cont)
(value-of/k rand saved-env
(rand-cont val saved-cont)))
(rand-cont (val1 saved-cont)
(let ((proc (expval->proc val1)))
(apply-procedure/k proc val saved-cont)))
)))
;; apply-procedure/k : Proc * ExpVal * Cont -> FinalAnswer
Page 152 and 155
(define apply-procedure/k
(lambda (proc1 arg cont)
(cases proc proc1
(procedure (var body saved-env)
(value-of/k body
(extend-env var arg saved-env)
cont)))))
)
| null | https://raw.githubusercontent.com/mwand/eopl3/b50e015be7f021d94c1af5f0e3a05d40dd2b0cbf/chapter5/letrec-lang/interp.scm | scheme | exercise: rewrite this using the procedural representation of
the interpreter ;;;;;;;;;;;;;;;;
value-of-program : Program -> FinalAnswer
value-of/k : Exp * Env * Cont -> FinalAnswer
apply-cont : Cont * ExpVal -> FinalAnswer
or (logged-print val) ; if you use drscheme-init-cps.scm
apply-procedure/k : Proc * ExpVal * Cont -> FinalAnswer | (module interp (lib "eopl.ss" "eopl")
cps interpreter for the LETREC language , using the data structure
representation of continuations ( Figure 5.3 ) .
continuations ( Figure 5.2 ) .
exercise : rewrite this using a trampoline ( page 159 ) .
(require "drscheme-init.scm")
(require "lang.scm")
(require "data-structures.scm")
(require "environments.scm")
(provide value-of-program value-of/k)
Page : 143 and 154
(define value-of-program
(lambda (pgm)
(cases program pgm
(a-program (exp1)
(value-of/k exp1 (init-env) (end-cont))))))
Page : 143 - -146 , and 154
(define value-of/k
(lambda (exp env cont)
(cases expression exp
(const-exp (num) (apply-cont cont (num-val num)))
(var-exp (var) (apply-cont cont (apply-env env var)))
(proc-exp (var body)
(apply-cont cont
(proc-val (procedure var body env))))
(letrec-exp (p-name b-var p-body letrec-body)
(value-of/k letrec-body
(extend-env-rec p-name b-var p-body env)
cont))
(zero?-exp (exp1)
(value-of/k exp1 env
(zero1-cont cont)))
(let-exp (var exp1 body)
(value-of/k exp1 env
(let-exp-cont var body env cont)))
(if-exp (exp1 exp2 exp3)
(value-of/k exp1 env
(if-test-cont exp2 exp3 env cont)))
(diff-exp (exp1 exp2)
(value-of/k exp1 env
(diff1-cont exp2 env cont)))
(call-exp (rator rand)
(value-of/k rator env
(rator-cont rand env cont)))
)))
Page : 148
(define apply-cont
(lambda (cont val)
(cases continuation cont
(end-cont ()
(begin
(eopl:printf
"End of computation.~%")
val))
(zero1-cont (saved-cont)
(apply-cont saved-cont
(bool-val
(zero? (expval->num val)))))
(let-exp-cont (var body saved-env saved-cont)
(value-of/k body
(extend-env var val saved-env) saved-cont))
(if-test-cont (exp2 exp3 saved-env saved-cont)
(if (expval->bool val)
(value-of/k exp2 saved-env saved-cont)
(value-of/k exp3 saved-env saved-cont)))
(diff1-cont (exp2 saved-env saved-cont)
(value-of/k exp2
saved-env (diff2-cont val saved-cont)))
(diff2-cont (val1 saved-cont)
(let ((num1 (expval->num val1))
(num2 (expval->num val)))
(apply-cont saved-cont
(num-val (- num1 num2)))))
(rator-cont (rand saved-env saved-cont)
(value-of/k rand saved-env
(rand-cont val saved-cont)))
(rand-cont (val1 saved-cont)
(let ((proc (expval->proc val1)))
(apply-procedure/k proc val saved-cont)))
)))
Page 152 and 155
(define apply-procedure/k
(lambda (proc1 arg cont)
(cases proc proc1
(procedure (var body saved-env)
(value-of/k body
(extend-env var arg saved-env)
cont)))))
)
|
621eb8bc79ae555b3fa2422b1d0b40f0f46633fa285a813ab324859ca2dc1479 | nuprl/website | typed.rkt | #lang typed/racket
(module+ test
(require typed/rackunit)
(define-syntax-rule (check-equal?* [i o] ...)
(begin
(check-equal? i o)
...)))
(define-type Words (Listof String))
(define-type Lines (Listof Words))
(: kwic-read : Path-String -> (Listof String))
(define (kwic-read filename)
(with-input-from-file filename
(λ ()
(for/list ([line (in-lines)])
: (Listof String)
line))))
(module+ test
(let ([tmpfile (make-temporary-file)])
(with-output-to-file tmpfile #:exists 'replace
(λ ()
(displayln "The Nellie,")
(displayln "a cruising yawl,")
(displayln "swung to her anchor without a flutter of sails,")
(displayln "and was at rest.")))
(define actual (kwic-read tmpfile))
(define expect (file->lines tmpfile))
(delete-file tmpfile)
(check-equal? actual expect)))
(: kwic-split : (Listof String) -> Lines)
(define (kwic-split lines)
(map #{string-split :: (String -> Words)} lines))
(module+ test
(check-equal?*
[(kwic-split '())
'()]
[(kwic-split '("hello world"))
'(("hello" "world"))]))
Move first element to last position
(: circular-shift : Words -> Words)
(define (circular-shift words)
(append (rest words) (list (first words))))
(module+ test
(check-equal?*
[(circular-shift '("A" "B" "C"))
'("B" "C" "A")]))
(: all-circular-shifts : Words -> (Listof Words))
(define (all-circular-shifts words)
(for/fold ([all-shifts (list words)])
([i (in-range 1 (length words))])
: (Listof Words)
(cons (circular-shift (first all-shifts))
all-shifts)))
(module+ test
(check-equal?*
[(all-circular-shifts '("A" "B" "C"))
'(("C" "A" "B") ("B" "C" "A") ("A" "B" "C"))]))
(: alphabetize : Lines -> Lines)
(define (alphabetize all-shifts)
(sort all-shifts shift<?))
(module+ test
(check-equal?*
[(alphabetize '(("A" "B" "C") ("B" "C") ("A")))
'(("A") ("A" "B" "C") ("B" "C"))]))
order on equal - length lists of words
(: shift<? : Words Words -> Boolean)
(define (shift<? shift1 shift2)
(match* (shift1 shift2) ; destruct multiple values
first list empty , do n't care about second
#t]
first list non - empty , second empty
#f]
[((cons s1 shift1-rest) (cons s2 shift2-rest))
(or (string<? s1 s2)
(and (string=? s1 s2)
(shift<? shift1-rest shift2-rest)))]))
(module+ test
(check-equal?*
[(shift<? '() '())
#t]
[(shift<? '("A" "B") '("A" "C"))
#t]))
(: kwic-display : Lines -> Void)
(define (kwic-display all-sorted-shifts)
(: display-words : Words -> Void)
(define (display-words words)
(display (first words))
(for ([word (in-list (cdr words))])
(display " ")
(display word))
(newline))
; for-each is like map, but always returns (void)
(for-each display-words all-sorted-shifts))
(module+ test
(parameterize ([current-output-port (open-output-string)])
(kwic-display '(("A") ("B" "C")))
(check-equal?
(get-output-string (current-output-port))
"A\nB C\n")))
(: all-circular-shifts* : Lines -> (Listof Lines))
(define (all-circular-shifts* lines)
(map all-circular-shifts lines))
(module+ test
(check-equal?
(all-circular-shifts* '(("A" "B" "C") ("D")))
'((("C" "A" "B") ("B" "C" "A") ("A" "B" "C")) (("D")))))
(: kwic-index : Path-String -> Void)
(define (kwic-index file-name)
(define all-lines (kwic-split (kwic-read file-name)))
(define all-shifts (append* (all-circular-shifts* all-lines)))
(kwic-display (alphabetize all-shifts)))
(module+ test
(parameterize ([current-output-port (open-output-string)])
(define tmpfile (make-temporary-file))
(with-output-to-file tmpfile #:exists 'replace
(λ ()
(displayln "imagine if this")
(displayln "took 2 weeks to write")))
(kwic-index tmpfile)
(delete-file tmpfile)
(check-equal?
(get-output-string (current-output-port))
(string-join '(
"2 weeks to write took"
"if this imagine"
"imagine if this"
"this imagine if"
"to write took 2 weeks"
"took 2 weeks to write"
"weeks to write took 2"
"write took 2 weeks to\n") "\n"))))
(module+ main
(require racket/cmdline)
(: *output-to* (Parameterof Any))
(define *output-to* (make-parameter #f))
(command-line
#:program "kwic index"
#:once-each
[("-o" "--output")
output-to
"Write output to file"
(*output-to* output-to)]
#:args (file-name)
(define output-to (*output-to*))
(define out-port
(if (string? output-to)
(open-output-file output-to #:exists 'replace)
(current-output-port)))
(parameterize ([current-output-port out-port])
(kwic-index (cast file-name Path-String)))
(when (string? output-to)
(close-output-port out-port))))
| null | https://raw.githubusercontent.com/nuprl/website/6952d0572094feae39e515e6b421de81af5a5be9/blog/_src/posts/kwic/typed.rkt | racket | destruct multiple values
for-each is like map, but always returns (void) | #lang typed/racket
(module+ test
(require typed/rackunit)
(define-syntax-rule (check-equal?* [i o] ...)
(begin
(check-equal? i o)
...)))
(define-type Words (Listof String))
(define-type Lines (Listof Words))
(: kwic-read : Path-String -> (Listof String))
(define (kwic-read filename)
(with-input-from-file filename
(λ ()
(for/list ([line (in-lines)])
: (Listof String)
line))))
(module+ test
(let ([tmpfile (make-temporary-file)])
(with-output-to-file tmpfile #:exists 'replace
(λ ()
(displayln "The Nellie,")
(displayln "a cruising yawl,")
(displayln "swung to her anchor without a flutter of sails,")
(displayln "and was at rest.")))
(define actual (kwic-read tmpfile))
(define expect (file->lines tmpfile))
(delete-file tmpfile)
(check-equal? actual expect)))
(: kwic-split : (Listof String) -> Lines)
(define (kwic-split lines)
(map #{string-split :: (String -> Words)} lines))
(module+ test
(check-equal?*
[(kwic-split '())
'()]
[(kwic-split '("hello world"))
'(("hello" "world"))]))
Move first element to last position
(: circular-shift : Words -> Words)
(define (circular-shift words)
(append (rest words) (list (first words))))
(module+ test
(check-equal?*
[(circular-shift '("A" "B" "C"))
'("B" "C" "A")]))
(: all-circular-shifts : Words -> (Listof Words))
(define (all-circular-shifts words)
(for/fold ([all-shifts (list words)])
([i (in-range 1 (length words))])
: (Listof Words)
(cons (circular-shift (first all-shifts))
all-shifts)))
(module+ test
(check-equal?*
[(all-circular-shifts '("A" "B" "C"))
'(("C" "A" "B") ("B" "C" "A") ("A" "B" "C"))]))
(: alphabetize : Lines -> Lines)
(define (alphabetize all-shifts)
(sort all-shifts shift<?))
(module+ test
(check-equal?*
[(alphabetize '(("A" "B" "C") ("B" "C") ("A")))
'(("A") ("A" "B" "C") ("B" "C"))]))
order on equal - length lists of words
(: shift<? : Words Words -> Boolean)
(define (shift<? shift1 shift2)
first list empty , do n't care about second
#t]
first list non - empty , second empty
#f]
[((cons s1 shift1-rest) (cons s2 shift2-rest))
(or (string<? s1 s2)
(and (string=? s1 s2)
(shift<? shift1-rest shift2-rest)))]))
(module+ test
(check-equal?*
[(shift<? '() '())
#t]
[(shift<? '("A" "B") '("A" "C"))
#t]))
(: kwic-display : Lines -> Void)
(define (kwic-display all-sorted-shifts)
(: display-words : Words -> Void)
(define (display-words words)
(display (first words))
(for ([word (in-list (cdr words))])
(display " ")
(display word))
(newline))
(for-each display-words all-sorted-shifts))
(module+ test
(parameterize ([current-output-port (open-output-string)])
(kwic-display '(("A") ("B" "C")))
(check-equal?
(get-output-string (current-output-port))
"A\nB C\n")))
(: all-circular-shifts* : Lines -> (Listof Lines))
(define (all-circular-shifts* lines)
(map all-circular-shifts lines))
(module+ test
(check-equal?
(all-circular-shifts* '(("A" "B" "C") ("D")))
'((("C" "A" "B") ("B" "C" "A") ("A" "B" "C")) (("D")))))
(: kwic-index : Path-String -> Void)
(define (kwic-index file-name)
(define all-lines (kwic-split (kwic-read file-name)))
(define all-shifts (append* (all-circular-shifts* all-lines)))
(kwic-display (alphabetize all-shifts)))
(module+ test
(parameterize ([current-output-port (open-output-string)])
(define tmpfile (make-temporary-file))
(with-output-to-file tmpfile #:exists 'replace
(λ ()
(displayln "imagine if this")
(displayln "took 2 weeks to write")))
(kwic-index tmpfile)
(delete-file tmpfile)
(check-equal?
(get-output-string (current-output-port))
(string-join '(
"2 weeks to write took"
"if this imagine"
"imagine if this"
"this imagine if"
"to write took 2 weeks"
"took 2 weeks to write"
"weeks to write took 2"
"write took 2 weeks to\n") "\n"))))
(module+ main
(require racket/cmdline)
(: *output-to* (Parameterof Any))
(define *output-to* (make-parameter #f))
(command-line
#:program "kwic index"
#:once-each
[("-o" "--output")
output-to
"Write output to file"
(*output-to* output-to)]
#:args (file-name)
(define output-to (*output-to*))
(define out-port
(if (string? output-to)
(open-output-file output-to #:exists 'replace)
(current-output-port)))
(parameterize ([current-output-port out-port])
(kwic-index (cast file-name Path-String)))
(when (string? output-to)
(close-output-port out-port))))
|
243e084ab69a6d9ac3a8fe3309c1b8edb673d489972a4b07d87bffe91e9960b9 | den1k/re-frame-utils | runner.cljs | (ns vimsical.re-frame.runner
(:require
[cljs.test :as test]
[doo.runner :refer-macros [doo-all-tests doo-tests]]
[vimsical.re-frame.cofx.inject-test]
[vimsical.re-frame.fx.track-test]))
(doo-all-tests #"vimsical.+\-test$")
| null | https://raw.githubusercontent.com/den1k/re-frame-utils/8d13297ea5f85d848b5f7b14a92b93e3ca933d28/test/vimsical/re_frame/runner.cljs | clojure | (ns vimsical.re-frame.runner
(:require
[cljs.test :as test]
[doo.runner :refer-macros [doo-all-tests doo-tests]]
[vimsical.re-frame.cofx.inject-test]
[vimsical.re-frame.fx.track-test]))
(doo-all-tests #"vimsical.+\-test$")
| |
fdfdb8b61bdb9316d33b69da682b45a121adfb3a614874a726abcfce3f10eee8 | haskell-repa/repa | Index.hs | # LANGUAGE TypeOperators , FlexibleInstances , ScopedTypeVariables #
-- | Index types.
module Data.Array.Repa.Vector.Index
(
-- * Index types
Z (..)
, (:.) (..)
-- * Common dimensions.
, DIM0, DIM1, DIM2, DIM3, DIM4, DIM5
, ix1, ix2, ix3, ix4, ix5)
where
import Data.Array.Repa.Vector.Shape
import GHC.Base (quotInt, remInt)
stage = "Data.Array.Repa.Index"
| An index of dimension zero
data Z = Z
deriving (Show, Read, Eq, Ord)
-- | Our index type, used for both shapes and indices.
infixl 3 :.
data tail :. head
= !tail :. !head
deriving (Show, Read, Eq, Ord)
-- Common dimensions
type DIM0 = Z
type DIM1 = DIM0 :. Int
type DIM2 = DIM1 :. Int
type DIM3 = DIM2 :. Int
type DIM4 = DIM3 :. Int
type DIM5 = DIM4 :. Int
-- | Helper for index construction.
--
-- Use this instead of explicit constructors like @(Z :. (x :: Int))@.
-- The this is sometimes needed to ensure that 'x' is constrained to
-- be in @Int@.
ix1 :: Int -> DIM1
ix1 x = Z :. x
# INLINE ix1 #
ix2 :: Int -> Int -> DIM2
ix2 y x = Z :. y :. x
# INLINE ix2 #
ix3 :: Int -> Int -> Int -> DIM3
ix3 z y x = Z :. z :. y :. x
# INLINE ix3 #
ix4 :: Int -> Int -> Int -> Int -> DIM4
ix4 a z y x = Z :. a :. z :. y :. x
# INLINE ix4 #
ix5 :: Int -> Int -> Int -> Int -> Int -> DIM5
ix5 b a z y x = Z :. b :. a :. z :. y :. x
# INLINE ix5 #
-- Shape ----------------------------------------------------------------------
instance Shape Z where
# INLINE [ 1 ] rank #
rank _ = 0
{-# INLINE [1] zeroDim #-}
zeroDim = Z
# INLINE [ 1 ] unitDim #
unitDim = Z
{-# INLINE [1] intersectDim #-}
intersectDim _ _ = Z
{-# INLINE [1] addDim #-}
addDim _ _ = Z
# INLINE [ 1 ] size #
size _ = 1
# INLINE [ 1 ] sizeIsValid #
sizeIsValid _ = True
# INLINE [ 1 ] toIndex #
toIndex _ _ = 0
# INLINE [ 1 ] fromIndex #
fromIndex _ _ = Z
{-# INLINE [1] inShapeRange #-}
inShapeRange Z Z Z = True
# NOINLINE listOfShape #
listOfShape _ = []
# NOINLINE shapeOfList #
shapeOfList [] = Z
shapeOfList _ = error $ stage ++ ".fromList: non-empty list when converting to Z."
# INLINE deepSeq #
deepSeq Z x = x
instance Shape sh => Shape (sh :. Int) where
# INLINE [ 1 ] rank #
rank (sh :. _)
= rank sh + 1
{-# INLINE [1] zeroDim #-}
zeroDim = zeroDim :. 0
# INLINE [ 1 ] unitDim #
unitDim = unitDim :. 1
{-# INLINE [1] intersectDim #-}
intersectDim (sh1 :. n1) (sh2 :. n2)
= (intersectDim sh1 sh2 :. (min n1 n2))
{-# INLINE [1] addDim #-}
addDim (sh1 :. n1) (sh2 :. n2)
= addDim sh1 sh2 :. (n1 + n2)
# INLINE [ 1 ] size #
size (sh1 :. n)
= size sh1 * n
# INLINE [ 1 ] sizeIsValid #
sizeIsValid (sh1 :. n)
| size sh1 > 0
= n <= maxBound `div` size sh1
| otherwise
= False
# INLINE [ 1 ] toIndex #
toIndex (sh1 :. sh2) (sh1' :. sh2')
= toIndex sh1 sh1' * sh2 + sh2'
# INLINE [ 1 ] fromIndex #
fromIndex (ds :. d) n
= fromIndex ds (n `quotInt` d) :. r
where
-- If we assume that the index is in range, there is no point
-- in computing the remainder for the highest dimension since
n < d must hold . This saves one remInt per element access which
-- is quite a big deal.
r | rank ds == 0 = n
| otherwise = n `remInt` d
{-# INLINE [1] inShapeRange #-}
inShapeRange (zs :. z) (sh1 :. n1) (sh2 :. n2)
= (n2 >= z) && (n2 < n1) && (inShapeRange zs sh1 sh2)
# NOINLINE listOfShape #
listOfShape (sh :. n)
= n : listOfShape sh
# NOINLINE shapeOfList #
shapeOfList xx
= case xx of
[] -> error $ stage ++ ".toList: empty list when converting to (_ :. Int)"
x:xs -> shapeOfList xs :. x
# INLINE deepSeq #
deepSeq (sh :. n) x = deepSeq sh (n `seq` x)
| null | https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/icebox/abandoned/repa-vector/Data/Array/Repa/Vector/Index.hs | haskell | | Index types.
* Index types
* Common dimensions.
| Our index type, used for both shapes and indices.
Common dimensions
| Helper for index construction.
Use this instead of explicit constructors like @(Z :. (x :: Int))@.
The this is sometimes needed to ensure that 'x' is constrained to
be in @Int@.
Shape ----------------------------------------------------------------------
# INLINE [1] zeroDim #
# INLINE [1] intersectDim #
# INLINE [1] addDim #
# INLINE [1] inShapeRange #
# INLINE [1] zeroDim #
# INLINE [1] intersectDim #
# INLINE [1] addDim #
If we assume that the index is in range, there is no point
in computing the remainder for the highest dimension since
is quite a big deal.
# INLINE [1] inShapeRange # | # LANGUAGE TypeOperators , FlexibleInstances , ScopedTypeVariables #
module Data.Array.Repa.Vector.Index
(
Z (..)
, (:.) (..)
, DIM0, DIM1, DIM2, DIM3, DIM4, DIM5
, ix1, ix2, ix3, ix4, ix5)
where
import Data.Array.Repa.Vector.Shape
import GHC.Base (quotInt, remInt)
stage = "Data.Array.Repa.Index"
| An index of dimension zero
data Z = Z
deriving (Show, Read, Eq, Ord)
infixl 3 :.
data tail :. head
= !tail :. !head
deriving (Show, Read, Eq, Ord)
type DIM0 = Z
type DIM1 = DIM0 :. Int
type DIM2 = DIM1 :. Int
type DIM3 = DIM2 :. Int
type DIM4 = DIM3 :. Int
type DIM5 = DIM4 :. Int
ix1 :: Int -> DIM1
ix1 x = Z :. x
# INLINE ix1 #
ix2 :: Int -> Int -> DIM2
ix2 y x = Z :. y :. x
# INLINE ix2 #
ix3 :: Int -> Int -> Int -> DIM3
ix3 z y x = Z :. z :. y :. x
# INLINE ix3 #
ix4 :: Int -> Int -> Int -> Int -> DIM4
ix4 a z y x = Z :. a :. z :. y :. x
# INLINE ix4 #
ix5 :: Int -> Int -> Int -> Int -> Int -> DIM5
ix5 b a z y x = Z :. b :. a :. z :. y :. x
# INLINE ix5 #
instance Shape Z where
# INLINE [ 1 ] rank #
rank _ = 0
zeroDim = Z
# INLINE [ 1 ] unitDim #
unitDim = Z
intersectDim _ _ = Z
addDim _ _ = Z
# INLINE [ 1 ] size #
size _ = 1
# INLINE [ 1 ] sizeIsValid #
sizeIsValid _ = True
# INLINE [ 1 ] toIndex #
toIndex _ _ = 0
# INLINE [ 1 ] fromIndex #
fromIndex _ _ = Z
inShapeRange Z Z Z = True
# NOINLINE listOfShape #
listOfShape _ = []
# NOINLINE shapeOfList #
shapeOfList [] = Z
shapeOfList _ = error $ stage ++ ".fromList: non-empty list when converting to Z."
# INLINE deepSeq #
deepSeq Z x = x
instance Shape sh => Shape (sh :. Int) where
# INLINE [ 1 ] rank #
rank (sh :. _)
= rank sh + 1
zeroDim = zeroDim :. 0
# INLINE [ 1 ] unitDim #
unitDim = unitDim :. 1
intersectDim (sh1 :. n1) (sh2 :. n2)
= (intersectDim sh1 sh2 :. (min n1 n2))
addDim (sh1 :. n1) (sh2 :. n2)
= addDim sh1 sh2 :. (n1 + n2)
# INLINE [ 1 ] size #
size (sh1 :. n)
= size sh1 * n
# INLINE [ 1 ] sizeIsValid #
sizeIsValid (sh1 :. n)
| size sh1 > 0
= n <= maxBound `div` size sh1
| otherwise
= False
# INLINE [ 1 ] toIndex #
toIndex (sh1 :. sh2) (sh1' :. sh2')
= toIndex sh1 sh1' * sh2 + sh2'
# INLINE [ 1 ] fromIndex #
fromIndex (ds :. d) n
= fromIndex ds (n `quotInt` d) :. r
where
n < d must hold . This saves one remInt per element access which
r | rank ds == 0 = n
| otherwise = n `remInt` d
inShapeRange (zs :. z) (sh1 :. n1) (sh2 :. n2)
= (n2 >= z) && (n2 < n1) && (inShapeRange zs sh1 sh2)
# NOINLINE listOfShape #
listOfShape (sh :. n)
= n : listOfShape sh
# NOINLINE shapeOfList #
shapeOfList xx
= case xx of
[] -> error $ stage ++ ".toList: empty list when converting to (_ :. Int)"
x:xs -> shapeOfList xs :. x
# INLINE deepSeq #
deepSeq (sh :. n) x = deepSeq sh (n `seq` x)
|
2b171aa6ac38b6999cf8d27416e485b6e2b7c98eca9ad93079470fd81556fb21 | exercism/clojure | annalyns_infiltration_test.clj | (ns annalyns-infiltration-test
(:require annalyns-infiltration
[clojure.test :refer [deftest is testing]]))
(deftest ^{:task 1} fast-attack-awake-test
(testing "Fast attack if knight is awake"
(is (= false (annalyns-infiltration/can-fast-attack? true)))))
(deftest ^{:task 1} fast-attack-asleep-test
(testing "Fast attack if knight is sleeping"
(is (= true (annalyns-infiltration/can-fast-attack? false)))))
(deftest ^{:task 2} spy-everyone-sleeping-test
(testing "Cannot spy if everyone is sleeping"
(is (= false (annalyns-infiltration/can-spy? false false false)))))
(deftest ^{:task 2} spy-but-knight-sleeping-test
(testing "Can spy if everyone but knight is sleeping"
(is (= true (annalyns-infiltration/can-spy? true false false)))))
(deftest ^{:task 2} spy-but-archer-sleeping-test
(testing "Can spy if everyone but archer is sleeping"
(is (= true (annalyns-infiltration/can-spy? false true false)))))
(deftest ^{:task 2} spy-but-prisoner-sleeping-test
(testing "Can spy if everyone but prisoner is sleeping"
(is (= true (annalyns-infiltration/can-spy? false false true)))))
(deftest ^{:task 2} spy-only-knight-sleeping-test
(testing "Can spy if only knight is sleeping"
(is (= true (annalyns-infiltration/can-spy? false true true)))))
(deftest ^{:task 2} spy-only-archer-sleeping-test
(testing "Can spy if only archer is sleeping"
(is (= true (annalyns-infiltration/can-spy? true false true)))))
(deftest ^{:task 2} spy-only-prisoner-sleeping-test
(testing "Can spy if only prisoner is sleeping"
(is (= true (annalyns-infiltration/can-spy? true true false)))))
(deftest ^{:task 2} spy-everyone-awake-test
(testing "Can spy if everyone is awake"
(is (= true (annalyns-infiltration/can-spy? true true true)))))
(deftest ^{:task 3} signal-prisoner-archer-sleeping-prisoner-awake-test
(testing "Can signal prisoner if archer is sleeping and prisoner is awake"
(is (= true (annalyns-infiltration/can-signal-prisoner? false true)))))
(deftest ^{:task 3} signal-prisoner-archer-awake-prisoner-sleeping-test
(testing "Cannot signal prisoner if archer is awake and prisoner is sleeping"
(is (= false (annalyns-infiltration/can-signal-prisoner? true false)))))
(deftest ^{:task 3} signal-prisoner-both-sleeping-test
(testing "Cannot signal prisoner if archer and prisoner are both sleeping"
(is (= false (annalyns-infiltration/can-signal-prisoner? false false)))))
(deftest ^{:task 3} signal-prisoner-both-awake-test
(testing "Cannot signal prisoner if archer and prisoner are both awake"
(is (= false (annalyns-infiltration/can-signal-prisoner? true true)))))
(deftest ^{:task 4} release-prisoner-everyone-awake-dog-present-test
(testing "Cannot release prisoner if everyone is awake and pet dog is present"
(is (= false (annalyns-infiltration/can-free-prisoner? true true true true)))))
(deftest ^{:task 4} release-prisoner-everyone-awake-dog-absent-test
(testing "Cannot release prisoner if everyone is awake and pet dog is absent"
(is (= false (annalyns-infiltration/can-free-prisoner? true true true false)))))
(deftest ^{:task 4} release-prisoner-everyone-asleep-dog-absent-test
(testing "Cannot release prisoner if everyone is asleep and pet dog is absent"
(is (= false (annalyns-infiltration/can-free-prisoner? false false false false)))))
(deftest ^{:task 4} release-prisoner-archer-awake-dog-present-test
(testing "Cannot release prisoner if only archer is awake and pet dog is present"
(is (= false (annalyns-infiltration/can-free-prisoner? false true false true)))))
(deftest ^{:task 4} release-prisoner-archer-awake-dog-absent-test
(testing "Cannot release prisoner if only archer is awake and pet dog is absent"
(is (= false (annalyns-infiltration/can-free-prisoner? false true false false)))))
(deftest ^{:task 4} release-prisoner-knight-awake-dog-absent-test
(testing "Cannot release prisoner if only knight is awake and pet dog is absent"
(is (= false (annalyns-infiltration/can-free-prisoner? true false false false)))))
(deftest ^{:task 4} release-prisoner-knight-awake-dog-present-test
(testing "Cannot release prisoner if only knight is asleep and pet dog is present"
(is (= false (annalyns-infiltration/can-free-prisoner? false true true true)))))
(deftest ^{:task 4} release-prisoner-knight-asleep-dog-absent-test
(testing "Cannot release prisoner if only knight is asleep and pet dog is absent"
(is (= false (annalyns-infiltration/can-free-prisoner? false true true false)))))
(deftest ^{:task 4} release-prisoner-archer-asleep-dog-absent-test
(testing "Cannot release prisoner if only archer is asleep and pet dog is absent"
(is (= false (annalyns-infiltration/can-free-prisoner? true false true false)))))
(deftest ^{:task 4} release-prisoner-prisoner-asleep-dog-present-test
(testing "Cannot release prisoner if only prisoner is asleep and pet dog is present"
(is (= false (annalyns-infiltration/can-free-prisoner? true true false true)))))
(deftest ^{:task 4} release-prisoner-prisoner-asleep-dog-absent-test
(testing "Cannot release prisoner if only prisoner is asleep and pet dog is absent"
(is (= false (annalyns-infiltration/can-free-prisoner? true true false false)))))
(deftest ^{:task 4} release-prisoner-everyone-asleep-dog-present-test
(testing "Can release prisoner if everyone is asleep and pet dog is present"
(is (= true (annalyns-infiltration/can-free-prisoner? false false false true)))))
(deftest ^{:task 4} release-prisoner-prisoner-awake-dog-present-test
(testing "Can release prisoner if only prisoner is awake and pet dog is present"
(is (= true (annalyns-infiltration/can-free-prisoner? false false true true)))))
(deftest ^{:task 4} release-prisoner-prisoner-awake-dog-absent-test
(testing "Can release prisoner if only prisoner is awake and pet dog is absent"
(is (= true (annalyns-infiltration/can-free-prisoner? false false true false)))))
(deftest ^{:task 4} release-prisoner-knight-awake-dog-present-test
(testing "Can release prisoner if only knight is awake and pet dog is present"
(is (= true (annalyns-infiltration/can-free-prisoner? true false false true)))))
(deftest ^{:task 4} release-prisoner-archer-asleep-dog-present-test
(testing "Can release prisoner if only archer is asleep and pet dog is present"
(is (= true (annalyns-infiltration/can-free-prisoner? true false true true)))))
| null | https://raw.githubusercontent.com/exercism/clojure/7f11e4bee92c3d94fa4d65b2eef7a2b6354fea50/exercises/concept/annalyns-infiltration/test/annalyns_infiltration_test.clj | clojure | (ns annalyns-infiltration-test
(:require annalyns-infiltration
[clojure.test :refer [deftest is testing]]))
(deftest ^{:task 1} fast-attack-awake-test
(testing "Fast attack if knight is awake"
(is (= false (annalyns-infiltration/can-fast-attack? true)))))
(deftest ^{:task 1} fast-attack-asleep-test
(testing "Fast attack if knight is sleeping"
(is (= true (annalyns-infiltration/can-fast-attack? false)))))
(deftest ^{:task 2} spy-everyone-sleeping-test
(testing "Cannot spy if everyone is sleeping"
(is (= false (annalyns-infiltration/can-spy? false false false)))))
(deftest ^{:task 2} spy-but-knight-sleeping-test
(testing "Can spy if everyone but knight is sleeping"
(is (= true (annalyns-infiltration/can-spy? true false false)))))
(deftest ^{:task 2} spy-but-archer-sleeping-test
(testing "Can spy if everyone but archer is sleeping"
(is (= true (annalyns-infiltration/can-spy? false true false)))))
(deftest ^{:task 2} spy-but-prisoner-sleeping-test
(testing "Can spy if everyone but prisoner is sleeping"
(is (= true (annalyns-infiltration/can-spy? false false true)))))
(deftest ^{:task 2} spy-only-knight-sleeping-test
(testing "Can spy if only knight is sleeping"
(is (= true (annalyns-infiltration/can-spy? false true true)))))
(deftest ^{:task 2} spy-only-archer-sleeping-test
(testing "Can spy if only archer is sleeping"
(is (= true (annalyns-infiltration/can-spy? true false true)))))
(deftest ^{:task 2} spy-only-prisoner-sleeping-test
(testing "Can spy if only prisoner is sleeping"
(is (= true (annalyns-infiltration/can-spy? true true false)))))
(deftest ^{:task 2} spy-everyone-awake-test
(testing "Can spy if everyone is awake"
(is (= true (annalyns-infiltration/can-spy? true true true)))))
(deftest ^{:task 3} signal-prisoner-archer-sleeping-prisoner-awake-test
(testing "Can signal prisoner if archer is sleeping and prisoner is awake"
(is (= true (annalyns-infiltration/can-signal-prisoner? false true)))))
(deftest ^{:task 3} signal-prisoner-archer-awake-prisoner-sleeping-test
(testing "Cannot signal prisoner if archer is awake and prisoner is sleeping"
(is (= false (annalyns-infiltration/can-signal-prisoner? true false)))))
(deftest ^{:task 3} signal-prisoner-both-sleeping-test
(testing "Cannot signal prisoner if archer and prisoner are both sleeping"
(is (= false (annalyns-infiltration/can-signal-prisoner? false false)))))
(deftest ^{:task 3} signal-prisoner-both-awake-test
(testing "Cannot signal prisoner if archer and prisoner are both awake"
(is (= false (annalyns-infiltration/can-signal-prisoner? true true)))))
(deftest ^{:task 4} release-prisoner-everyone-awake-dog-present-test
(testing "Cannot release prisoner if everyone is awake and pet dog is present"
(is (= false (annalyns-infiltration/can-free-prisoner? true true true true)))))
(deftest ^{:task 4} release-prisoner-everyone-awake-dog-absent-test
(testing "Cannot release prisoner if everyone is awake and pet dog is absent"
(is (= false (annalyns-infiltration/can-free-prisoner? true true true false)))))
(deftest ^{:task 4} release-prisoner-everyone-asleep-dog-absent-test
(testing "Cannot release prisoner if everyone is asleep and pet dog is absent"
(is (= false (annalyns-infiltration/can-free-prisoner? false false false false)))))
(deftest ^{:task 4} release-prisoner-archer-awake-dog-present-test
(testing "Cannot release prisoner if only archer is awake and pet dog is present"
(is (= false (annalyns-infiltration/can-free-prisoner? false true false true)))))
(deftest ^{:task 4} release-prisoner-archer-awake-dog-absent-test
(testing "Cannot release prisoner if only archer is awake and pet dog is absent"
(is (= false (annalyns-infiltration/can-free-prisoner? false true false false)))))
(deftest ^{:task 4} release-prisoner-knight-awake-dog-absent-test
(testing "Cannot release prisoner if only knight is awake and pet dog is absent"
(is (= false (annalyns-infiltration/can-free-prisoner? true false false false)))))
(deftest ^{:task 4} release-prisoner-knight-awake-dog-present-test
(testing "Cannot release prisoner if only knight is asleep and pet dog is present"
(is (= false (annalyns-infiltration/can-free-prisoner? false true true true)))))
(deftest ^{:task 4} release-prisoner-knight-asleep-dog-absent-test
(testing "Cannot release prisoner if only knight is asleep and pet dog is absent"
(is (= false (annalyns-infiltration/can-free-prisoner? false true true false)))))
(deftest ^{:task 4} release-prisoner-archer-asleep-dog-absent-test
(testing "Cannot release prisoner if only archer is asleep and pet dog is absent"
(is (= false (annalyns-infiltration/can-free-prisoner? true false true false)))))
(deftest ^{:task 4} release-prisoner-prisoner-asleep-dog-present-test
(testing "Cannot release prisoner if only prisoner is asleep and pet dog is present"
(is (= false (annalyns-infiltration/can-free-prisoner? true true false true)))))
(deftest ^{:task 4} release-prisoner-prisoner-asleep-dog-absent-test
(testing "Cannot release prisoner if only prisoner is asleep and pet dog is absent"
(is (= false (annalyns-infiltration/can-free-prisoner? true true false false)))))
(deftest ^{:task 4} release-prisoner-everyone-asleep-dog-present-test
(testing "Can release prisoner if everyone is asleep and pet dog is present"
(is (= true (annalyns-infiltration/can-free-prisoner? false false false true)))))
(deftest ^{:task 4} release-prisoner-prisoner-awake-dog-present-test
(testing "Can release prisoner if only prisoner is awake and pet dog is present"
(is (= true (annalyns-infiltration/can-free-prisoner? false false true true)))))
(deftest ^{:task 4} release-prisoner-prisoner-awake-dog-absent-test
(testing "Can release prisoner if only prisoner is awake and pet dog is absent"
(is (= true (annalyns-infiltration/can-free-prisoner? false false true false)))))
(deftest ^{:task 4} release-prisoner-knight-awake-dog-present-test
(testing "Can release prisoner if only knight is awake and pet dog is present"
(is (= true (annalyns-infiltration/can-free-prisoner? true false false true)))))
(deftest ^{:task 4} release-prisoner-archer-asleep-dog-present-test
(testing "Can release prisoner if only archer is asleep and pet dog is present"
(is (= true (annalyns-infiltration/can-free-prisoner? true false true true)))))
| |
3f185a6ee2aa7fa98da548ee98f1fec486a30a08479afcf1c0366306917ff533 | haskoin/haskoin-core | SignatureSpec.hs | {-# LANGUAGE OverloadedStrings #-}
module Haskoin.Crypto.SignatureSpec (spec) where
import Control.Monad
import Data.Bits (testBit)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Serialize as S
import Data.String.Conversions (cs)
import Data.Text (Text)
import Haskoin.Address
import Haskoin.Constants
import Haskoin.Crypto
import Haskoin.Keys
import Haskoin.Script
import Haskoin.Transaction
import Haskoin.Util
import Haskoin.Util.Arbitrary
import Haskoin.UtilSpec (readTestFile)
import Test.HUnit
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
spec :: Spec
spec = do
describe "Signature properties" $ do
prop "verify signature" $
forAll arbitrarySignature $ \(m, key', sig) ->
verifyHashSig m sig (derivePubKey key')
prop "s component less than half order" $
forAll arbitrarySignature $ isCanonicalHalfOrder . lst3
prop "encoded signature is canonical" $
forAll arbitrarySignature $ testIsCanonical . lst3
prop "decodeStrictSig . exportSig identity" $
forAll arbitrarySignature $
(\s -> decodeStrictSig (exportSig s) == Just s) . lst3
prop "importSig . exportSig identity" $
forAll arbitrarySignature $
(\s -> importSig (exportSig s) == Just s) . lst3
prop "getSig . putSig identity" $
forAll arbitrarySignature $
(\s -> runGet getSig (runPut $ putSig s) == Right s) . lst3
describe "Signature vectors" $
checkDistSig $ \file1 file2 -> do
vectors <- runIO (readTestFile file1 :: IO [(Text, Text, Text)])
vectorsDER <- runIO (readTestFile file2 :: IO [(Text, Text, Text)])
it "Passes the trezor rfc6979 test vectors" $
mapM_ (testRFC6979Vector . toVector) vectors
it "Passes the rfc6979 DER test vectors" $
mapM_ (testRFC6979DERVector . toVector) vectorsDER
describe "BIP143 signature vectors" $ do
it "agrees with BIP143 p2wpkh example" testBip143p2wpkh
it "agrees with BIP143 p2sh-p2wpkh example" testBip143p2shp2wpkh
it "builds a p2wsh multisig transaction" testP2WSHMulsig
it "agrees with BIP143 p2sh-p2wsh multisig example" testBip143p2shp2wpkhMulsig
-- github.com/bitcoin/bitcoin/blob/master/src/script.cpp
-- from function IsCanonicalSignature
testIsCanonical :: Sig -> Bool
testIsCanonical sig =
not $
-- Non-canonical signature: too short
(len < 8)
||
-- Non-canonical signature: too long
(len > 72)
||
-- Non-canonical signature: wrong type
(BS.index s 0 /= 0x30)
||
-- Non-canonical signature: wrong length marker
(BS.index s 1 /= len - 2)
||
-- Non-canonical signature: S length misplaced
(5 + rlen >= len)
||
-- Non-canonical signature: R+S length mismatch
(rlen + slen + 6 /= len)
||
-- Non-canonical signature: R value type mismatch
(BS.index s 2 /= 0x02)
||
Non - canonical signature : R length is zero
(rlen == 0)
||
-- Non-canonical signature: R value negative
testBit (BS.index s 4) 7
||
-- Non-canonical signature: R value excessively padded
( rlen > 1
&& BS.index s 4 == 0
&& not (testBit (BS.index s 5) 7)
)
||
-- Non-canonical signature: S value type mismatch
(BS.index s (fromIntegral rlen + 4) /= 0x02)
||
Non - canonical signature : S length is zero
(slen == 0)
||
-- Non-canonical signature: S value negative
testBit (BS.index s (fromIntegral rlen + 6)) 7
||
-- Non-canonical signature: S value excessively padded
( slen > 1
&& BS.index s (fromIntegral rlen + 6) == 0
&& not (testBit (BS.index s (fromIntegral rlen + 7)) 7)
)
where
s = exportSig sig
len = fromIntegral $ BS.length s
rlen = BS.index s 3
slen = BS.index s (fromIntegral rlen + 5)
RFC6979 note : Different libraries of libsecp256k1 use different constants
-- to produce a nonce. Thus, their deterministric signatures will be different.
-- We still want to test against fixed signatures so we need a way to switch
between implementations . We check the output of signMsg 1 0
data ValidImpl
= ImplCore
| ImplABC
implSig :: Text
implSig =
encodeHex $
exportSig $
signMsg
"0000000000000000000000000000000000000000000000000000000000000001"
"0000000000000000000000000000000000000000000000000000000000000000"
-- We have test vectors for these cases
validImplMap :: Map Text ValidImpl
validImplMap =
Map.fromList
[
( "3045022100a0b37f8fba683cc68f6574cd43b39f0343a50008bf6ccea9d13231\
\d9e7e2e1e4022011edc8d307254296264aebfc3dc76cd8b668373a072fd64665\
\b50000e9fcce52"
, ImplCore
)
,
( "304402200581361d23e645be9e3efe63a9a2ac2e8dd0c70ba3ac8554c9befe06\
\0ad0b36202207d8172f1e259395834793d81b17e986f1e6131e4734969d2f4ae\
\3a9c8bc42965"
, ImplABC
)
]
getImpl :: Maybe ValidImpl
getImpl = implSig `Map.lookup` validImplMap
rfc6979files :: ValidImpl -> (FilePath, FilePath)
rfc6979files ImplCore = ("rfc6979core.json", "rfc6979DERcore.json")
rfc6979files ImplABC = ("rfc6979abc.json", "rfc6979DERabc.json")
checkDistSig :: (FilePath -> FilePath -> Spec) -> Spec
checkDistSig go =
case rfc6979files <$> getImpl of
Just (file1, file2) -> go file1 file2
_ ->
it "Passes rfc6979 test vectors" $
void $ assertFailure "Invalid rfc6979 signature"
Trezor RFC 6979 Test Vectors
github.com/trezor/python-ecdsa/blob/master/ecdsa/test_pyecdsa.py
toVector :: (Text, Text, Text) -> (SecKey, ByteString, Text)
toVector (prv, m, res) = (fromJust $ (secKey <=< decodeHex) prv, cs m, res)
testRFC6979Vector :: (SecKey, ByteString, Text) -> Assertion
testRFC6979Vector (prv, m, res) = do
assertEqual "RFC 6979 Vector" res (encodeHex $ encode $ exportCompactSig s)
assertBool "Signature is valid" $ verifyHashSig h s (derivePubKey prv)
assertBool "Signature is canonical" $ testIsCanonical s
assertBool "Signature is normalized" $ isCanonicalHalfOrder s
where
h = sha256 m
s = signHash prv h
-- Test vectors from:
-- -for-data-to-test-deterministic-ecdsa-signature-algorithm-for-secp256k1
testRFC6979DERVector :: (SecKey, ByteString, Text) -> Assertion
testRFC6979DERVector (prv, m, res) = do
assertEqual "RFC 6979 DER Vector" res (encodeHex $ exportSig s)
assertBool "DER Signature is valid" $ verifyHashSig h s (derivePubKey prv)
assertBool "DER Signature is canonical" $ testIsCanonical s
assertBool "DER Signature is normalized" $ isCanonicalHalfOrder s
where
h = sha256 m
s = signHash prv h
Reproduce the P2WPKH example from BIP 143
testBip143p2wpkh :: Assertion
testBip143p2wpkh =
case getImpl of
Just ImplCore ->
assertEqual "BIP143 Core p2wpkh" (Right signedTxCore) generatedSignedTx
Just ImplABC ->
assertEqual "BIP143 ABC p2wpkh" (Right signedTxABC) generatedSignedTx
Nothing -> assertFailure "Invalid secp256k1 library"
where
signedTxCore =
"01000000000102fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433\
\541db4e4ad969f00000000494830450221008b9d1dc26ba6a9cb62127b02742f\
\a9d754cd3bebf337f7a55d114c8e5cdd30be022040529b194ba3f9281a99f2b1\
\c0a19c0489bc22ede944ccf4ecbab4cc618ef3ed01eeffffffef51e1b804cc89\
\d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffff\
\ffff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac\
\7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f0\
\167faa815988ac000247304402203609e17b84f6a7d30c80bfa610b5b4542f32\
\a8a0d5447a12fb1366d7f01cc44a0220573a954c4518331561406f90300e8f33\
\58f51928d43c212a8caed02de67eebee0121025476c2e83188368da1ff3e292e\
\7acafcdb3566bb0ad253f62fc70f07aeee635711000000"
signedTxABC =
"01000000000102fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433\
\541db4e4ad969f000000004847304402200fbc9dad97500334e47c2dca50096a\
\2117c01952c2870102e320823d21c36229022007cb36c2b141d11c08ef81d948\
\f148332fc09fe8f6d226aaaf8ba6ae0d8a66ba01eeffffffef51e1b804cc89d1\
\82d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffffff\
\ff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac7a\
\6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f016\
\7faa815988ac0002473044022011cb891cee521eb1fc7aef681655a881288553\
\fc024cff9cee5007bae5e6b8c602200b89d60ee2f98aa9a645dad59cd680b4b6\
\25f343efcd3e7fb70852100ef601890121025476c2e83188368da1ff3e292e7a\
\cafcdb3566bb0ad253f62fc70f07aeee635711000000"
unsignedTx =
"0100000002fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541d\
\b4e4ad969f0000000000eeffffffef51e1b804cc89d182d279655c3aa89e815b\
\1b309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb20600000000\
\1976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d0000\
\00001976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac11000000"
Just key0 =
secHexKey
"bbc27228ddcb9209d7fd6f36b02f7dfa6252af40bb2f1cbc7a557da8027ff866"
pubKey0 = toPubKey key0
Just key1 =
secHexKey
"619c335025c7f4012e556c2a58b2506e30b8511b53ade95ea316fd8c3286feb9"
[op0, op1] = prevOutput <$> txIn unsignedTx
sigIn0 = SigInput (PayPK pubKey0) 625000000 op0 sigHashAll Nothing
WitnessPubKeyAddress h = pubKeyWitnessAddr $ toPubKey key1
sigIn1 = SigInput (PayWitnessPKHash h) 600000000 op1 sigHashAll Nothing
generatedSignedTx = signTx btc unsignedTx [sigIn0, sigIn1] [key0, key1]
Reproduce the P2SH - P2WPKH example from BIP 143
testBip143p2shp2wpkh :: Assertion
testBip143p2shp2wpkh =
case getImpl of
Just ImplCore ->
assertEqual "BIP143 Core p2sh-p2wpkh" (Right signedTxCore) generatedSignedTx
Just ImplABC ->
assertEqual "BIP143 ABC p2sh-p2wpkh" (Right signedTxABC) generatedSignedTx
Nothing -> assertFailure "Invalid secp256k1 library"
where
signedTxCore =
"01000000000101db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092\
\ac4d3ceb1a5477010000001716001479091972186c449eb1ded22b78e40d009b\
\df0089feffffff02b8b4eb0b000000001976a914a457b684d7f0d539a46a45bb\
\c043f35b59d0d96388ac0008af2f000000001976a914fd270b1ee6abcaea97fe\
\a7ad0402e8bd8ad6d77c88ac02473044022047ac8e878352d3ebbde1c94ce3a1\
\0d057c24175747116f8288e5d794d12d482f0220217f36a485cae903c713331d\
\877c1f64677e3622ad4010726870540656fe9dcb012103ad1d8e89212f0b92c7\
\4d23bb710c00662ad1470198ac48c43f7d6f93a2a2687392040000"
signedTxABC =
"01000000000101db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092\
\ac4d3ceb1a5477010000001716001479091972186c449eb1ded22b78e40d009b\
\df0089feffffff02b8b4eb0b000000001976a914a457b684d7f0d539a46a45bb\
\c043f35b59d0d96388ac0008af2f000000001976a914fd270b1ee6abcaea97fe\
\a7ad0402e8bd8ad6d77c88ac024730440220091c78fd1e21535f6ddc45515e4c\
\afca15cdf344765d72c1529fb82d3ada2d1802204a980d5e37d0b04f5e1185a0\
\f97295c383764e9a4b08d8bd1161b33c6719139a012103ad1d8e89212f0b92c7\
\4d23bb710c00662ad1470198ac48c43f7d6f93a2a2687392040000"
unsignedTx =
"0100000001db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092ac4d\
\3ceb1a54770100000000feffffff02b8b4eb0b000000001976a914a457b684d7\
\f0d539a46a45bbc043f35b59d0d96388ac0008af2f000000001976a914fd270b\
\1ee6abcaea97fea7ad0402e8bd8ad6d77c88ac92040000"
Just key0 =
secHexKey
"eb696a065ef48a2192da5b28b694f87544b30fae8327c4510137a922f32c6dcf"
op0 = prevOutput . head $ txIn unsignedTx
WitnessPubKeyAddress h = pubKeyWitnessAddr $ toPubKey key0
sigIn0 = SigInput (PayWitnessPKHash h) 1000000000 op0 sigHashAll Nothing
generatedSignedTx = signNestedWitnessTx btc unsignedTx [sigIn0] [key0]
P2WSH multisig example ( tested against bitcoin - core 0.19.0.1 )
testP2WSHMulsig :: Assertion
testP2WSHMulsig =
case getImpl of
Just ImplCore ->
assertEqual "Core p2wsh multisig" (Right signedTxCore) generatedSignedTx
Just ImplABC ->
assertEqual "ABC p2wsh multisig" (Right signedTxABC) generatedSignedTx
Nothing -> assertFailure "Invalid secp256k1 library"
where
signedTxCore =
"01000000000101d2e34df5d7ee565208eddd231548916b9b0e99f4f5071f8961\
\34a448c5fb07bf0100000000ffffffff01f0b9f505000000001976a9143d5a35\
\2cab583b12fbcb26d1269b4a2c951a33ad88ac0400483045022100fad4fedd2b\
\b4c439c64637eb8e9150d9020a7212808b8dc0578d5ff5b4ad65fe0220714640\
\f261b37eb3106310bf853f4b706e51436fb6b64c2ab00768814eb55b98014730\
\44022100baff4e4ceea4022b9725a2e6f6d77997a554f858165b91ac8c16c983\
\3008bee9021f5f70ebc3f8580dc0a5e96451e3697bdf1f1f5883944f0f33ab0c\
\fb272354040169522102ba46d3bb8db74c77c6cf082db57fc0548058fcdea811\
\549e186526e3d10caf6721038ac8aef2dd9cea5e7d66e2f6e23f177a6c21f69e\
\a311fa0c85d81badb6b37ceb2103d96d2bfbbc040faaf93491d69e2bfe9695e2\
\d8e007a7f26db96c2ee42db15dc953ae00000000"
signedTxABC =
"01000000000101d2e34df5d7ee565208eddd231548916b9b0e99f4f5071f8961\
\34a448c5fb07bf0100000000ffffffff01f0b9f505000000001976a9143d5a35\
\2cab583b12fbcb26d1269b4a2c951a33ad88ac0400483045022100b79bf3714a\
\50f8f0e2f946034361ba4f6567b796d55910d89e98720d2e99f98c0220134879\
\518002df23e80a058475fa8b10bc4182bedfecd5f85e446a00f211ea53014830\
\45022100ce3c77480d664430a7544c1a962d1ae31151109a528a37e5bccc92ba\
\2e460ad10220317bc9a71d0c3471058d16d4c3b1ea99616208db6b9b9040fb81\
\0a7fa27f72b40169522102ba46d3bb8db74c77c6cf082db57fc0548058fcdea8\
\11549e186526e3d10caf6721038ac8aef2dd9cea5e7d66e2f6e23f177a6c21f6\
\9ea311fa0c85d81badb6b37ceb2103d96d2bfbbc040faaf93491d69e2bfe9695\
\e2d8e007a7f26db96c2ee42db15dc953ae00000000"
unsignedTx =
"0100000001d2e34df5d7ee565208eddd231548916b9b0e99f4f5071f896134a4\
\48c5fb07bf0100000000ffffffff01f0b9f505000000001976a9143d5a352cab\
\583b12fbcb26d1269b4a2c951a33ad88ac00000000"
op0 = head $ prevOutput <$> txIn unsignedTx
Just keys =
traverse
secHexKey
[ "3030303030303030303030303030303030303030303030303030303030303031"
, "3030303030303030303030303030303030303030303030303030303030303032"
, "3030303030303030303030303030303030303030303030303030303030303033"
]
rdm = PayMulSig (toPubKey <$> keys) 2
sigIn =
SigInput
(toP2WSH $ encodeOutput rdm)
100000000
op0
sigHashAll
(Just rdm)
generatedSignedTx = signTx btc unsignedTx [sigIn] (take 2 keys)
Reproduce the P2SH - P2WSH multisig example from BIP 143
testBip143p2shp2wpkhMulsig :: Assertion
testBip143p2shp2wpkhMulsig =
case getImpl of
Just ImplCore ->
assertEqual
"BIP143 Core p2sh-p2wsh multisig"
(Right signedTxCore)
generatedSignedTx
Just ImplABC ->
assertEqual
"BIP143 Core p2sh-p2wsh multisig"
(Right signedTxABC)
generatedSignedTx
Nothing -> assertFailure "Invalid secp256k1 library"
where
signedTxCore =
"0100000000010136641869ca081e70f394c6948e8af409e18b619df2ed74aa10\
\6c1ca29787b96e0100000023220020a16b5755f7f6f96dbd65f5f0d6ab9418b8\
\9af4b1f14a1bb8a09062c35f0dcb54ffffffff0200e9a435000000001976a914\
\389ffce9cd9ae88dcc0631e88a821ffdbe9bfe2688acc0832f05000000001976\
\a9147480a33f950689af511e6e84c138dbbd3c3ee41588ac080047304402206a\
\c44d672dac41f9b00e28f4df20c52eeb087207e8d758d76d92c6fab3b73e2b02\
\20367750dbbe19290069cba53d096f44530e4f98acaa594810388cf7409a1870\
\ce01473044022068c7946a43232757cbdf9176f009a928e1cd9a1a8c212f15c1\
\e11ac9f2925d9002205b75f937ff2f9f3c1246e547e54f62e027f64eefa26955\
\78cc6432cdabce271502473044022059ebf56d98010a932cf8ecfec54c48e613\
\9ed6adb0728c09cbe1e4fa0915302e022007cd986c8fa870ff5d2b3a89139c9f\
\e7e499259875357e20fcbb15571c76795403483045022100fbefd94bd0a488d5\
\0b79102b5dad4ab6ced30c4069f1eaa69a4b5a763414067e02203156c6a5c9cf\
\88f91265f5a942e96213afae16d83321c8b31bb342142a14d163814830450221\
\00a5263ea0553ba89221984bd7f0b13613db16e7a70c549a86de0cc0444141a4\
\07022005c360ef0ae5a5d4f9f2f87a56c1546cc8268cab08c73501d6b3be2e1e\
\1a8a08824730440220525406a1482936d5a21888260dc165497a90a15669636d\
\8edca6b9fe490d309c022032af0c646a34a44d1f4576bf6a4a74b67940f8faa8\
\4c7df9abe12a01a11e2b4783cf56210307b8ae49ac90a048e9b53357a2354b33\
\34e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28bfab54554ae8c658ac5c\
\3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b97\
\81957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a9a\
\21cfdf1ed1376e58c5d1f47de74683123987e967a8f42103a6d48b1131e94ba0\
\4d9737d61acdaa1322008af9602b3b14862c07a1789aac162102d8b661b0b330\
\2ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b56ae00000000"
signedTxABC =
"0100000000010136641869ca081e70f394c6948e8af409e18b619df2ed74aa10\
\6c1ca29787b96e0100000023220020a16b5755f7f6f96dbd65f5f0d6ab9418b8\
\9af4b1f14a1bb8a09062c35f0dcb54ffffffff0200e9a435000000001976a914\
\389ffce9cd9ae88dcc0631e88a821ffdbe9bfe2688acc0832f05000000001976\
\a9147480a33f950689af511e6e84c138dbbd3c3ee41588ac0800483045022100\
\b70b684ef0d17b51adf71c0dae932beca5d447dd5eec03394328436bdba836e7\
\0220208ebfd7408d21e41da11d8287655528385429d3fe300bee241f10944339\
\5b580147304402204b5f9bc06c8f0a252b9842ea44785853beb1638002cec5f2\
\489d73e5f6f5109302204f3b132b32638835d4b1a651e7d18dc93c10192db553\
\999932af6a8e3d8a153202483045022100e0ed8d3a245a138c751d74e1359aee\
\6a52476ddf33a3a9a5f0c2ad30147319650220581318187061ad0f48fc4f5c85\
\1822e554d59977005b8de4b78bf2ce2fe8399703483045022100a0a40abc581e\
\4b725775a3aa93bf0f0fd9a02ad3aa0f93483214784a47ba5387022069151c30\
\f85a7e20c8671107c5af884ee4c5a82bd06398327fa68a993f7cc64b81473044\
\022016d828460f6fab3cf89ae4b87c8f02c11c798cf739967f3b7406e7367c29\
\ae8b022079e82b822eb6c37a66efabc3f0b40a2b98c52f848d36463f6623cbdc\
\fe675812824730440220225a14ba7434858dbb5e6e0a0969ddf3b5455edaabf9\
\9f5773d1f59e7816b918022047ed1ab87840a74f7e9489f3af051e5fd26b790f\
\b308c79f4b0ed73c0422795d83cf56210307b8ae49ac90a048e9b53357a2354b\
\3334e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28bfab54554ae8c658ac\
\5c3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b\
\9781957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a\
\9a21cfdf1ed1376e58c5d1f47de74683123987e967a8f42103a6d48b1131e94b\
\a04d9737d61acdaa1322008af9602b3b14862c07a1789aac162102d8b661b0b3\
\302ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b56ae00000000"
unsignedTx =
"010000000136641869ca081e70f394c6948e8af409e18b619df2ed74aa106c1c\
\a29787b96e0100000000ffffffff0200e9a435000000001976a914389ffce9cd\
\9ae88dcc0631e88a821ffdbe9bfe2688acc0832f05000000001976a9147480a3\
\3f950689af511e6e84c138dbbd3c3ee41588ac00000000"
op0 = head $ prevOutput <$> txIn unsignedTx
rawKeys =
[ "730fff80e1413068a05b57d6a58261f07551163369787f349438ea38ca80fac6"
, "11fa3d25a17cbc22b29c44a484ba552b5a53149d106d3d853e22fdd05a2d8bb3"
, "77bf4141a87d55bdd7f3cd0bdccf6e9e642935fec45f2f30047be7b799120661"
, "14af36970f5025ea3e8b5542c0f8ebe7763e674838d08808896b63c3351ffe49"
, "fe9a95c19eef81dde2b95c1284ef39be497d128e2aa46916fb02d552485e0323"
, "428a7aee9f0c2af0cd19af3cf1c78149951ea528726989b2e83e4778d2c3f890"
]
Just keys = traverse secHexKey rawKeys
rdm = PayMulSig (toPubKey <$> keys) 6
sigIn sh = SigInput (toP2WSH $ encodeOutput rdm) 987654321 op0 sh (Just rdm)
sigHashesA = [sigHashAll, sigHashNone, sigHashSingle]
sigHashesB = setAnyoneCanPayFlag <$> sigHashesA
sigIns = sigIn <$> (sigHashesA <> sigHashesB)
generatedSignedTx = foldM addSig unsignedTx $ zip sigIns keys
addSig tx (sigIn', key') = signNestedWitnessTx btc tx [sigIn'] [key']
secHexKey :: Text -> Maybe SecKey
secHexKey = decodeHex >=> secKey
toPubKey :: SecKey -> PubKeyI
toPubKey = derivePubKeyI . wrapSecKey True
| null | https://raw.githubusercontent.com/haskoin/haskoin-core/d49455a27735dbe636453e870cf4e8720fb3a80a/test/Haskoin/Crypto/SignatureSpec.hs | haskell | # LANGUAGE OverloadedStrings #
github.com/bitcoin/bitcoin/blob/master/src/script.cpp
from function IsCanonicalSignature
Non-canonical signature: too short
Non-canonical signature: too long
Non-canonical signature: wrong type
Non-canonical signature: wrong length marker
Non-canonical signature: S length misplaced
Non-canonical signature: R+S length mismatch
Non-canonical signature: R value type mismatch
Non-canonical signature: R value negative
Non-canonical signature: R value excessively padded
Non-canonical signature: S value type mismatch
Non-canonical signature: S value negative
Non-canonical signature: S value excessively padded
to produce a nonce. Thus, their deterministric signatures will be different.
We still want to test against fixed signatures so we need a way to switch
We have test vectors for these cases
Test vectors from:
-for-data-to-test-deterministic-ecdsa-signature-algorithm-for-secp256k1 |
module Haskoin.Crypto.SignatureSpec (spec) where
import Control.Monad
import Data.Bits (testBit)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Serialize as S
import Data.String.Conversions (cs)
import Data.Text (Text)
import Haskoin.Address
import Haskoin.Constants
import Haskoin.Crypto
import Haskoin.Keys
import Haskoin.Script
import Haskoin.Transaction
import Haskoin.Util
import Haskoin.Util.Arbitrary
import Haskoin.UtilSpec (readTestFile)
import Test.HUnit
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
spec :: Spec
spec = do
describe "Signature properties" $ do
prop "verify signature" $
forAll arbitrarySignature $ \(m, key', sig) ->
verifyHashSig m sig (derivePubKey key')
prop "s component less than half order" $
forAll arbitrarySignature $ isCanonicalHalfOrder . lst3
prop "encoded signature is canonical" $
forAll arbitrarySignature $ testIsCanonical . lst3
prop "decodeStrictSig . exportSig identity" $
forAll arbitrarySignature $
(\s -> decodeStrictSig (exportSig s) == Just s) . lst3
prop "importSig . exportSig identity" $
forAll arbitrarySignature $
(\s -> importSig (exportSig s) == Just s) . lst3
prop "getSig . putSig identity" $
forAll arbitrarySignature $
(\s -> runGet getSig (runPut $ putSig s) == Right s) . lst3
describe "Signature vectors" $
checkDistSig $ \file1 file2 -> do
vectors <- runIO (readTestFile file1 :: IO [(Text, Text, Text)])
vectorsDER <- runIO (readTestFile file2 :: IO [(Text, Text, Text)])
it "Passes the trezor rfc6979 test vectors" $
mapM_ (testRFC6979Vector . toVector) vectors
it "Passes the rfc6979 DER test vectors" $
mapM_ (testRFC6979DERVector . toVector) vectorsDER
describe "BIP143 signature vectors" $ do
it "agrees with BIP143 p2wpkh example" testBip143p2wpkh
it "agrees with BIP143 p2sh-p2wpkh example" testBip143p2shp2wpkh
it "builds a p2wsh multisig transaction" testP2WSHMulsig
it "agrees with BIP143 p2sh-p2wsh multisig example" testBip143p2shp2wpkhMulsig
testIsCanonical :: Sig -> Bool
testIsCanonical sig =
not $
(len < 8)
||
(len > 72)
||
(BS.index s 0 /= 0x30)
||
(BS.index s 1 /= len - 2)
||
(5 + rlen >= len)
||
(rlen + slen + 6 /= len)
||
(BS.index s 2 /= 0x02)
||
Non - canonical signature : R length is zero
(rlen == 0)
||
testBit (BS.index s 4) 7
||
( rlen > 1
&& BS.index s 4 == 0
&& not (testBit (BS.index s 5) 7)
)
||
(BS.index s (fromIntegral rlen + 4) /= 0x02)
||
Non - canonical signature : S length is zero
(slen == 0)
||
testBit (BS.index s (fromIntegral rlen + 6)) 7
||
( slen > 1
&& BS.index s (fromIntegral rlen + 6) == 0
&& not (testBit (BS.index s (fromIntegral rlen + 7)) 7)
)
where
s = exportSig sig
len = fromIntegral $ BS.length s
rlen = BS.index s 3
slen = BS.index s (fromIntegral rlen + 5)
RFC6979 note : Different libraries of libsecp256k1 use different constants
between implementations . We check the output of signMsg 1 0
data ValidImpl
= ImplCore
| ImplABC
implSig :: Text
implSig =
encodeHex $
exportSig $
signMsg
"0000000000000000000000000000000000000000000000000000000000000001"
"0000000000000000000000000000000000000000000000000000000000000000"
validImplMap :: Map Text ValidImpl
validImplMap =
Map.fromList
[
( "3045022100a0b37f8fba683cc68f6574cd43b39f0343a50008bf6ccea9d13231\
\d9e7e2e1e4022011edc8d307254296264aebfc3dc76cd8b668373a072fd64665\
\b50000e9fcce52"
, ImplCore
)
,
( "304402200581361d23e645be9e3efe63a9a2ac2e8dd0c70ba3ac8554c9befe06\
\0ad0b36202207d8172f1e259395834793d81b17e986f1e6131e4734969d2f4ae\
\3a9c8bc42965"
, ImplABC
)
]
getImpl :: Maybe ValidImpl
getImpl = implSig `Map.lookup` validImplMap
rfc6979files :: ValidImpl -> (FilePath, FilePath)
rfc6979files ImplCore = ("rfc6979core.json", "rfc6979DERcore.json")
rfc6979files ImplABC = ("rfc6979abc.json", "rfc6979DERabc.json")
checkDistSig :: (FilePath -> FilePath -> Spec) -> Spec
checkDistSig go =
case rfc6979files <$> getImpl of
Just (file1, file2) -> go file1 file2
_ ->
it "Passes rfc6979 test vectors" $
void $ assertFailure "Invalid rfc6979 signature"
Trezor RFC 6979 Test Vectors
github.com/trezor/python-ecdsa/blob/master/ecdsa/test_pyecdsa.py
toVector :: (Text, Text, Text) -> (SecKey, ByteString, Text)
toVector (prv, m, res) = (fromJust $ (secKey <=< decodeHex) prv, cs m, res)
testRFC6979Vector :: (SecKey, ByteString, Text) -> Assertion
testRFC6979Vector (prv, m, res) = do
assertEqual "RFC 6979 Vector" res (encodeHex $ encode $ exportCompactSig s)
assertBool "Signature is valid" $ verifyHashSig h s (derivePubKey prv)
assertBool "Signature is canonical" $ testIsCanonical s
assertBool "Signature is normalized" $ isCanonicalHalfOrder s
where
h = sha256 m
s = signHash prv h
testRFC6979DERVector :: (SecKey, ByteString, Text) -> Assertion
testRFC6979DERVector (prv, m, res) = do
assertEqual "RFC 6979 DER Vector" res (encodeHex $ exportSig s)
assertBool "DER Signature is valid" $ verifyHashSig h s (derivePubKey prv)
assertBool "DER Signature is canonical" $ testIsCanonical s
assertBool "DER Signature is normalized" $ isCanonicalHalfOrder s
where
h = sha256 m
s = signHash prv h
Reproduce the P2WPKH example from BIP 143
testBip143p2wpkh :: Assertion
testBip143p2wpkh =
case getImpl of
Just ImplCore ->
assertEqual "BIP143 Core p2wpkh" (Right signedTxCore) generatedSignedTx
Just ImplABC ->
assertEqual "BIP143 ABC p2wpkh" (Right signedTxABC) generatedSignedTx
Nothing -> assertFailure "Invalid secp256k1 library"
where
signedTxCore =
"01000000000102fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433\
\541db4e4ad969f00000000494830450221008b9d1dc26ba6a9cb62127b02742f\
\a9d754cd3bebf337f7a55d114c8e5cdd30be022040529b194ba3f9281a99f2b1\
\c0a19c0489bc22ede944ccf4ecbab4cc618ef3ed01eeffffffef51e1b804cc89\
\d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffff\
\ffff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac\
\7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f0\
\167faa815988ac000247304402203609e17b84f6a7d30c80bfa610b5b4542f32\
\a8a0d5447a12fb1366d7f01cc44a0220573a954c4518331561406f90300e8f33\
\58f51928d43c212a8caed02de67eebee0121025476c2e83188368da1ff3e292e\
\7acafcdb3566bb0ad253f62fc70f07aeee635711000000"
signedTxABC =
"01000000000102fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433\
\541db4e4ad969f000000004847304402200fbc9dad97500334e47c2dca50096a\
\2117c01952c2870102e320823d21c36229022007cb36c2b141d11c08ef81d948\
\f148332fc09fe8f6d226aaaf8ba6ae0d8a66ba01eeffffffef51e1b804cc89d1\
\82d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffffff\
\ff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac7a\
\6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f016\
\7faa815988ac0002473044022011cb891cee521eb1fc7aef681655a881288553\
\fc024cff9cee5007bae5e6b8c602200b89d60ee2f98aa9a645dad59cd680b4b6\
\25f343efcd3e7fb70852100ef601890121025476c2e83188368da1ff3e292e7a\
\cafcdb3566bb0ad253f62fc70f07aeee635711000000"
unsignedTx =
"0100000002fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541d\
\b4e4ad969f0000000000eeffffffef51e1b804cc89d182d279655c3aa89e815b\
\1b309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb20600000000\
\1976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d0000\
\00001976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac11000000"
Just key0 =
secHexKey
"bbc27228ddcb9209d7fd6f36b02f7dfa6252af40bb2f1cbc7a557da8027ff866"
pubKey0 = toPubKey key0
Just key1 =
secHexKey
"619c335025c7f4012e556c2a58b2506e30b8511b53ade95ea316fd8c3286feb9"
[op0, op1] = prevOutput <$> txIn unsignedTx
sigIn0 = SigInput (PayPK pubKey0) 625000000 op0 sigHashAll Nothing
WitnessPubKeyAddress h = pubKeyWitnessAddr $ toPubKey key1
sigIn1 = SigInput (PayWitnessPKHash h) 600000000 op1 sigHashAll Nothing
generatedSignedTx = signTx btc unsignedTx [sigIn0, sigIn1] [key0, key1]
Reproduce the P2SH - P2WPKH example from BIP 143
testBip143p2shp2wpkh :: Assertion
testBip143p2shp2wpkh =
case getImpl of
Just ImplCore ->
assertEqual "BIP143 Core p2sh-p2wpkh" (Right signedTxCore) generatedSignedTx
Just ImplABC ->
assertEqual "BIP143 ABC p2sh-p2wpkh" (Right signedTxABC) generatedSignedTx
Nothing -> assertFailure "Invalid secp256k1 library"
where
signedTxCore =
"01000000000101db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092\
\ac4d3ceb1a5477010000001716001479091972186c449eb1ded22b78e40d009b\
\df0089feffffff02b8b4eb0b000000001976a914a457b684d7f0d539a46a45bb\
\c043f35b59d0d96388ac0008af2f000000001976a914fd270b1ee6abcaea97fe\
\a7ad0402e8bd8ad6d77c88ac02473044022047ac8e878352d3ebbde1c94ce3a1\
\0d057c24175747116f8288e5d794d12d482f0220217f36a485cae903c713331d\
\877c1f64677e3622ad4010726870540656fe9dcb012103ad1d8e89212f0b92c7\
\4d23bb710c00662ad1470198ac48c43f7d6f93a2a2687392040000"
signedTxABC =
"01000000000101db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092\
\ac4d3ceb1a5477010000001716001479091972186c449eb1ded22b78e40d009b\
\df0089feffffff02b8b4eb0b000000001976a914a457b684d7f0d539a46a45bb\
\c043f35b59d0d96388ac0008af2f000000001976a914fd270b1ee6abcaea97fe\
\a7ad0402e8bd8ad6d77c88ac024730440220091c78fd1e21535f6ddc45515e4c\
\afca15cdf344765d72c1529fb82d3ada2d1802204a980d5e37d0b04f5e1185a0\
\f97295c383764e9a4b08d8bd1161b33c6719139a012103ad1d8e89212f0b92c7\
\4d23bb710c00662ad1470198ac48c43f7d6f93a2a2687392040000"
unsignedTx =
"0100000001db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092ac4d\
\3ceb1a54770100000000feffffff02b8b4eb0b000000001976a914a457b684d7\
\f0d539a46a45bbc043f35b59d0d96388ac0008af2f000000001976a914fd270b\
\1ee6abcaea97fea7ad0402e8bd8ad6d77c88ac92040000"
Just key0 =
secHexKey
"eb696a065ef48a2192da5b28b694f87544b30fae8327c4510137a922f32c6dcf"
op0 = prevOutput . head $ txIn unsignedTx
WitnessPubKeyAddress h = pubKeyWitnessAddr $ toPubKey key0
sigIn0 = SigInput (PayWitnessPKHash h) 1000000000 op0 sigHashAll Nothing
generatedSignedTx = signNestedWitnessTx btc unsignedTx [sigIn0] [key0]
P2WSH multisig example ( tested against bitcoin - core 0.19.0.1 )
testP2WSHMulsig :: Assertion
testP2WSHMulsig =
case getImpl of
Just ImplCore ->
assertEqual "Core p2wsh multisig" (Right signedTxCore) generatedSignedTx
Just ImplABC ->
assertEqual "ABC p2wsh multisig" (Right signedTxABC) generatedSignedTx
Nothing -> assertFailure "Invalid secp256k1 library"
where
signedTxCore =
"01000000000101d2e34df5d7ee565208eddd231548916b9b0e99f4f5071f8961\
\34a448c5fb07bf0100000000ffffffff01f0b9f505000000001976a9143d5a35\
\2cab583b12fbcb26d1269b4a2c951a33ad88ac0400483045022100fad4fedd2b\
\b4c439c64637eb8e9150d9020a7212808b8dc0578d5ff5b4ad65fe0220714640\
\f261b37eb3106310bf853f4b706e51436fb6b64c2ab00768814eb55b98014730\
\44022100baff4e4ceea4022b9725a2e6f6d77997a554f858165b91ac8c16c983\
\3008bee9021f5f70ebc3f8580dc0a5e96451e3697bdf1f1f5883944f0f33ab0c\
\fb272354040169522102ba46d3bb8db74c77c6cf082db57fc0548058fcdea811\
\549e186526e3d10caf6721038ac8aef2dd9cea5e7d66e2f6e23f177a6c21f69e\
\a311fa0c85d81badb6b37ceb2103d96d2bfbbc040faaf93491d69e2bfe9695e2\
\d8e007a7f26db96c2ee42db15dc953ae00000000"
signedTxABC =
"01000000000101d2e34df5d7ee565208eddd231548916b9b0e99f4f5071f8961\
\34a448c5fb07bf0100000000ffffffff01f0b9f505000000001976a9143d5a35\
\2cab583b12fbcb26d1269b4a2c951a33ad88ac0400483045022100b79bf3714a\
\50f8f0e2f946034361ba4f6567b796d55910d89e98720d2e99f98c0220134879\
\518002df23e80a058475fa8b10bc4182bedfecd5f85e446a00f211ea53014830\
\45022100ce3c77480d664430a7544c1a962d1ae31151109a528a37e5bccc92ba\
\2e460ad10220317bc9a71d0c3471058d16d4c3b1ea99616208db6b9b9040fb81\
\0a7fa27f72b40169522102ba46d3bb8db74c77c6cf082db57fc0548058fcdea8\
\11549e186526e3d10caf6721038ac8aef2dd9cea5e7d66e2f6e23f177a6c21f6\
\9ea311fa0c85d81badb6b37ceb2103d96d2bfbbc040faaf93491d69e2bfe9695\
\e2d8e007a7f26db96c2ee42db15dc953ae00000000"
unsignedTx =
"0100000001d2e34df5d7ee565208eddd231548916b9b0e99f4f5071f896134a4\
\48c5fb07bf0100000000ffffffff01f0b9f505000000001976a9143d5a352cab\
\583b12fbcb26d1269b4a2c951a33ad88ac00000000"
op0 = head $ prevOutput <$> txIn unsignedTx
Just keys =
traverse
secHexKey
[ "3030303030303030303030303030303030303030303030303030303030303031"
, "3030303030303030303030303030303030303030303030303030303030303032"
, "3030303030303030303030303030303030303030303030303030303030303033"
]
rdm = PayMulSig (toPubKey <$> keys) 2
sigIn =
SigInput
(toP2WSH $ encodeOutput rdm)
100000000
op0
sigHashAll
(Just rdm)
generatedSignedTx = signTx btc unsignedTx [sigIn] (take 2 keys)
Reproduce the P2SH - P2WSH multisig example from BIP 143
testBip143p2shp2wpkhMulsig :: Assertion
testBip143p2shp2wpkhMulsig =
case getImpl of
Just ImplCore ->
assertEqual
"BIP143 Core p2sh-p2wsh multisig"
(Right signedTxCore)
generatedSignedTx
Just ImplABC ->
assertEqual
"BIP143 Core p2sh-p2wsh multisig"
(Right signedTxABC)
generatedSignedTx
Nothing -> assertFailure "Invalid secp256k1 library"
where
signedTxCore =
"0100000000010136641869ca081e70f394c6948e8af409e18b619df2ed74aa10\
\6c1ca29787b96e0100000023220020a16b5755f7f6f96dbd65f5f0d6ab9418b8\
\9af4b1f14a1bb8a09062c35f0dcb54ffffffff0200e9a435000000001976a914\
\389ffce9cd9ae88dcc0631e88a821ffdbe9bfe2688acc0832f05000000001976\
\a9147480a33f950689af511e6e84c138dbbd3c3ee41588ac080047304402206a\
\c44d672dac41f9b00e28f4df20c52eeb087207e8d758d76d92c6fab3b73e2b02\
\20367750dbbe19290069cba53d096f44530e4f98acaa594810388cf7409a1870\
\ce01473044022068c7946a43232757cbdf9176f009a928e1cd9a1a8c212f15c1\
\e11ac9f2925d9002205b75f937ff2f9f3c1246e547e54f62e027f64eefa26955\
\78cc6432cdabce271502473044022059ebf56d98010a932cf8ecfec54c48e613\
\9ed6adb0728c09cbe1e4fa0915302e022007cd986c8fa870ff5d2b3a89139c9f\
\e7e499259875357e20fcbb15571c76795403483045022100fbefd94bd0a488d5\
\0b79102b5dad4ab6ced30c4069f1eaa69a4b5a763414067e02203156c6a5c9cf\
\88f91265f5a942e96213afae16d83321c8b31bb342142a14d163814830450221\
\00a5263ea0553ba89221984bd7f0b13613db16e7a70c549a86de0cc0444141a4\
\07022005c360ef0ae5a5d4f9f2f87a56c1546cc8268cab08c73501d6b3be2e1e\
\1a8a08824730440220525406a1482936d5a21888260dc165497a90a15669636d\
\8edca6b9fe490d309c022032af0c646a34a44d1f4576bf6a4a74b67940f8faa8\
\4c7df9abe12a01a11e2b4783cf56210307b8ae49ac90a048e9b53357a2354b33\
\34e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28bfab54554ae8c658ac5c\
\3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b97\
\81957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a9a\
\21cfdf1ed1376e58c5d1f47de74683123987e967a8f42103a6d48b1131e94ba0\
\4d9737d61acdaa1322008af9602b3b14862c07a1789aac162102d8b661b0b330\
\2ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b56ae00000000"
signedTxABC =
"0100000000010136641869ca081e70f394c6948e8af409e18b619df2ed74aa10\
\6c1ca29787b96e0100000023220020a16b5755f7f6f96dbd65f5f0d6ab9418b8\
\9af4b1f14a1bb8a09062c35f0dcb54ffffffff0200e9a435000000001976a914\
\389ffce9cd9ae88dcc0631e88a821ffdbe9bfe2688acc0832f05000000001976\
\a9147480a33f950689af511e6e84c138dbbd3c3ee41588ac0800483045022100\
\b70b684ef0d17b51adf71c0dae932beca5d447dd5eec03394328436bdba836e7\
\0220208ebfd7408d21e41da11d8287655528385429d3fe300bee241f10944339\
\5b580147304402204b5f9bc06c8f0a252b9842ea44785853beb1638002cec5f2\
\489d73e5f6f5109302204f3b132b32638835d4b1a651e7d18dc93c10192db553\
\999932af6a8e3d8a153202483045022100e0ed8d3a245a138c751d74e1359aee\
\6a52476ddf33a3a9a5f0c2ad30147319650220581318187061ad0f48fc4f5c85\
\1822e554d59977005b8de4b78bf2ce2fe8399703483045022100a0a40abc581e\
\4b725775a3aa93bf0f0fd9a02ad3aa0f93483214784a47ba5387022069151c30\
\f85a7e20c8671107c5af884ee4c5a82bd06398327fa68a993f7cc64b81473044\
\022016d828460f6fab3cf89ae4b87c8f02c11c798cf739967f3b7406e7367c29\
\ae8b022079e82b822eb6c37a66efabc3f0b40a2b98c52f848d36463f6623cbdc\
\fe675812824730440220225a14ba7434858dbb5e6e0a0969ddf3b5455edaabf9\
\9f5773d1f59e7816b918022047ed1ab87840a74f7e9489f3af051e5fd26b790f\
\b308c79f4b0ed73c0422795d83cf56210307b8ae49ac90a048e9b53357a2354b\
\3334e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28bfab54554ae8c658ac\
\5c3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b\
\9781957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a\
\9a21cfdf1ed1376e58c5d1f47de74683123987e967a8f42103a6d48b1131e94b\
\a04d9737d61acdaa1322008af9602b3b14862c07a1789aac162102d8b661b0b3\
\302ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b56ae00000000"
unsignedTx =
"010000000136641869ca081e70f394c6948e8af409e18b619df2ed74aa106c1c\
\a29787b96e0100000000ffffffff0200e9a435000000001976a914389ffce9cd\
\9ae88dcc0631e88a821ffdbe9bfe2688acc0832f05000000001976a9147480a3\
\3f950689af511e6e84c138dbbd3c3ee41588ac00000000"
op0 = head $ prevOutput <$> txIn unsignedTx
rawKeys =
[ "730fff80e1413068a05b57d6a58261f07551163369787f349438ea38ca80fac6"
, "11fa3d25a17cbc22b29c44a484ba552b5a53149d106d3d853e22fdd05a2d8bb3"
, "77bf4141a87d55bdd7f3cd0bdccf6e9e642935fec45f2f30047be7b799120661"
, "14af36970f5025ea3e8b5542c0f8ebe7763e674838d08808896b63c3351ffe49"
, "fe9a95c19eef81dde2b95c1284ef39be497d128e2aa46916fb02d552485e0323"
, "428a7aee9f0c2af0cd19af3cf1c78149951ea528726989b2e83e4778d2c3f890"
]
Just keys = traverse secHexKey rawKeys
rdm = PayMulSig (toPubKey <$> keys) 6
sigIn sh = SigInput (toP2WSH $ encodeOutput rdm) 987654321 op0 sh (Just rdm)
sigHashesA = [sigHashAll, sigHashNone, sigHashSingle]
sigHashesB = setAnyoneCanPayFlag <$> sigHashesA
sigIns = sigIn <$> (sigHashesA <> sigHashesB)
generatedSignedTx = foldM addSig unsignedTx $ zip sigIns keys
addSig tx (sigIn', key') = signNestedWitnessTx btc tx [sigIn'] [key']
secHexKey :: Text -> Maybe SecKey
secHexKey = decodeHex >=> secKey
toPubKey :: SecKey -> PubKeyI
toPubKey = derivePubKeyI . wrapSecKey True
|
b7f69c24e93212e0fae348bf2b6a0c46eff789d11042506c29084a6c2449713b | tek/polysemy-hasql | Database.hs | module Polysemy.Hasql.Test.Database where
import Control.Lens (view)
import qualified Data.UUID as UUID
import Exon (exon)
import Hasql.Connection (Connection)
import Hasql.Session (QueryError)
import qualified Polysemy.Db.Data.DbConfig as DbConfig
import Polysemy.Db.Data.DbConfig (DbConfig (DbConfig))
import Polysemy.Db.Data.DbConnectionError (DbConnectionError)
import qualified Polysemy.Db.Data.DbError as DbError
import Polysemy.Db.Data.DbError (DbError)
import Polysemy.Db.Data.DbName (DbName (DbName))
import Polysemy.Db.Data.Rep (Auto, PrimQuery, PrimaryKey, UidRep)
import Polysemy.Db.Data.Uid (Uid)
import Polysemy.Db.Random (Random, random, runRandomIO)
import Polysemy.Time (GhcTime)
import Polysemy.Hasql.Data.Database (Database)
import qualified Polysemy.Hasql.Data.DbConnection as DbConnection
import Polysemy.Hasql.Data.DbConnection (DbConnection)
import Polysemy.Hasql.Data.DbType (Column (Column), Name (Name), Selector (Selector))
import qualified Polysemy.Hasql.Data.QueryTable as QueryTable
import Polysemy.Hasql.Data.QueryTable (QueryTable, UidQueryTable)
import qualified Polysemy.Hasql.Data.Table as Table
import Polysemy.Hasql.Data.Table (Table)
import Polysemy.Hasql.Database (HasqlConnection, interpretDatabase)
import Polysemy.Hasql.DbConnection (interpretDbConnection)
import Polysemy.Hasql.Session (convertQueryError)
import qualified Polysemy.Hasql.Statement as Statement
import Polysemy.Hasql.Store (StoreStack, interpretStoreDbFull)
import Polysemy.Hasql.Table (createTable, dropTable, runStatement)
import Polysemy.Hasql.Table.BasicSchema (BasicSchema, basicSchema)
import Polysemy.Hasql.Table.Query.Text (sqlQuote)
import Polysemy.Hasql.Table.Schema (Schema, UidQuerySchema, UidSchema, schema)
suffixedTable ::
Lens' t (Table d) ->
Text ->
t ->
t
suffixedTable lens suffix =
lens . Table.structure %~ applySuffix
where
applySuffix (Column (Name name) _ tpe opt dbTpe) =
Column (Name suffixed) (Selector (sqlQuote suffixed)) tpe opt dbTpe
where
suffixed =
[exon|#{name}-#{suffix}|]
bracketTestTable ::
Members [Resource, Embed IO, DbConnection Connection !! DbConnectionError, Random, Stop QueryError, Stop DbError] r =>
Lens' t (Table d) ->
t ->
(t -> Sem r a) ->
Connection ->
Sem r a
bracketTestTable lens t use connection =
bracket acquire release (const (use t))
where
acquire =
createTable connection (view Table.structure table)
release _ =
dropTable connection (view Table.name table)
table =
view lens t
withTestTable ::
Members [Resource, Embed IO, DbConnection Connection !! DbConnectionError, Random, Stop QueryError, Stop DbError] r =>
Lens' t (Table d) ->
t ->
(t -> Sem r a) ->
Sem r a
withTestTable lens table use = do
suffix <- UUID.toText <$> random
resumeHoist DbError.Connection $ DbConnection.use \ _ ->
bracketTestTable lens (suffixedTable lens suffix table) (raise . use)
withTestPlainTable ::
Members [Resource, Embed IO, DbConnection Connection !! DbConnectionError, Random, Stop QueryError, Stop DbError] r =>
Table d ->
(Table d -> Sem r a) ->
Sem r a
withTestPlainTable =
withTestTable id
withTestTableGen ::
∀ rep d a r .
Members [Resource, Embed IO, DbConnection Connection !! DbConnectionError, Random, Stop QueryError, Stop DbError] r =>
BasicSchema rep d =>
(Table d -> Sem r a) ->
Sem r a
withTestTableGen =
withTestPlainTable (basicSchema @rep)
withTestQueryTable ::
Members [Resource, Embed IO, DbConnection Connection !! DbConnectionError, Random, Stop QueryError, Stop DbError] r =>
QueryTable q d ->
(QueryTable q d -> Sem r a) ->
Sem r a
withTestQueryTable =
withTestTable QueryTable.table
withTestQueryTableGen ::
∀ qrep rep q d a r .
Members [Resource, Embed IO, DbConnection Connection !! DbConnectionError, Random, Stop QueryError, Stop DbError] r =>
Schema qrep rep q d =>
(QueryTable q d -> Sem r a) ->
Sem r a
withTestQueryTableGen =
withTestQueryTable (schema @qrep @rep)
createTestDb ::
Members [Random, DbConnection Connection !! DbConnectionError, Stop DbError, Embed IO] r =>
DbConfig ->
Connection ->
Sem r DbConfig
createTestDb dbConfig@(DbConfig _ _ (DbName name) _ _) connection = do
suffix <- UUID.toText <$> random
let
suffixedName = DbName [exon|#{name}-#{suffix}|]
suffixed = dbConfig & DbConfig.name .~ suffixedName
mapStop convertQueryError (runStatement connection () (Statement.createDb suffixedName))
pure suffixed
TODO this should use ` Error `
withTestDb ::
Members [Stop DbError, Resource, Embed IO, Final IO] r =>
DbConfig ->
(DbConfig -> Sem r a) ->
Sem r a
withTestDb baseConfig f =
interpretDbConnection "test" baseConfig do
resumeHoist DbError.Connection $ DbConnection.use \ _ connection ->
bracket (acquire baseConfig connection) (release connection) (raise . raise . f)
where
acquire config connection =
runRandomIO $ createTestDb config connection
release connection (DbConfig _ _ name _ _) =
mapStop convertQueryError (runStatement connection () (Statement.dropDb name))
withTestConnection ::
Members [Stop DbError, Time t dt, Resource, Embed IO, Final IO] r =>
DbConfig ->
Sem (Database !! DbError : HasqlConnection : r) a ->
Sem r a
withTestConnection baseConfig ma =
withTestDb baseConfig \ dbConfig ->
interpretDbConnection "test" dbConfig (interpretDatabase ma)
type TestStoreDeps =
[
Resource,
Embed IO,
HasqlConnection,
Database !! DbError,
Error DbError,
Random,
Log,
Stop QueryError,
Stop DbError,
GhcTime
]
withTestStoreUsing ::
∀ d i r a .
Members TestStoreDeps r =>
UidQueryTable i d ->
Sem (StoreStack i d ++ r) a ->
Sem r a
withTestStoreUsing table prog =
withTestQueryTable table \ t ->
interpretStoreDbFull t prog
withTestStoreTable ::
∀ qrep rep d i r a .
Members TestStoreDeps r =>
Schema qrep rep i (Uid i d) =>
(UidQueryTable i d -> Sem (StoreStack i d ++ r) a) ->
Sem r a
withTestStoreTable prog =
withTestQueryTableGen @qrep @rep \ table ->
interpretStoreDbFull table (prog table)
withTestStoreTableGenAs ::
∀ qrep rep irep d i r a .
Members TestStoreDeps r =>
UidQuerySchema qrep irep rep i i d =>
(UidQueryTable i d -> Sem (StoreStack i d ++ r) a) ->
Sem r a
withTestStoreTableGenAs prog =
withTestQueryTableGen @qrep @(UidRep irep rep) \ table ->
interpretStoreDbFull table (prog table)
withTestStoreTableGen ::
∀ rep i d r a .
Members TestStoreDeps r =>
UidSchema rep i d =>
(UidQueryTable i d -> Sem (StoreStack i d ++ r) a) ->
Sem r a
withTestStoreTableGen prog =
withTestQueryTableGen @(PrimQuery "id") @(UidRep PrimaryKey rep) \ table ->
interpretStoreDbFull table (prog table)
withTestStore ::
∀ qrep rep i d r .
Members TestStoreDeps r =>
Schema qrep rep i (Uid i d) =>
InterpretersFor (StoreStack i d) r
withTestStore prog =
withTestStoreTable @qrep @rep (const prog)
withTestStoreGenAs ::
∀ qrep irep rep i d r .
Members TestStoreDeps r =>
UidQuerySchema qrep irep rep i i d =>
InterpretersFor (StoreStack i d) r
withTestStoreGenAs prog =
withTestStoreTableGenAs @qrep @rep @irep (const prog)
withTestStoreGen ::
∀ rep i d r .
Members TestStoreDeps r =>
UidSchema rep i d =>
InterpretersFor (StoreStack i d) r
withTestStoreGen =
withTestStoreGenAs @(PrimQuery "id") @PrimaryKey @rep
withTestStoreAuto ::
∀ i d r a.
Members TestStoreDeps r =>
UidSchema Auto i d =>
Sem (StoreStack i d ++ r) a ->
Sem r a
withTestStoreAuto =
withTestStoreGen @Auto
withTestStoreUidAs ::
∀ qrep irep i d r a.
Members TestStoreDeps r =>
Schema qrep (UidRep irep Auto) i (Uid i d) =>
Sem (StoreStack i d ++ r) a ->
Sem r a
withTestStoreUidAs prog =
withTestQueryTableGen @qrep @(UidRep irep Auto) \ table ->
interpretStoreDbFull table prog
withTestStoreUid ::
∀ i d r a.
Members TestStoreDeps r =>
Schema (PrimQuery "id") (UidRep PrimaryKey Auto) i (Uid i d) =>
Sem (StoreStack i d ++ r) a ->
Sem r a
withTestStoreUid prog =
withTestQueryTableGen @(PrimQuery "id") @(UidRep PrimaryKey Auto) \ table ->
interpretStoreDbFull table prog
| null | https://raw.githubusercontent.com/tek/polysemy-hasql/831dfdb47f9246286db2c46e30194300a199ef38/packages/hasql/lib/Polysemy/Hasql/Test/Database.hs | haskell | module Polysemy.Hasql.Test.Database where
import Control.Lens (view)
import qualified Data.UUID as UUID
import Exon (exon)
import Hasql.Connection (Connection)
import Hasql.Session (QueryError)
import qualified Polysemy.Db.Data.DbConfig as DbConfig
import Polysemy.Db.Data.DbConfig (DbConfig (DbConfig))
import Polysemy.Db.Data.DbConnectionError (DbConnectionError)
import qualified Polysemy.Db.Data.DbError as DbError
import Polysemy.Db.Data.DbError (DbError)
import Polysemy.Db.Data.DbName (DbName (DbName))
import Polysemy.Db.Data.Rep (Auto, PrimQuery, PrimaryKey, UidRep)
import Polysemy.Db.Data.Uid (Uid)
import Polysemy.Db.Random (Random, random, runRandomIO)
import Polysemy.Time (GhcTime)
import Polysemy.Hasql.Data.Database (Database)
import qualified Polysemy.Hasql.Data.DbConnection as DbConnection
import Polysemy.Hasql.Data.DbConnection (DbConnection)
import Polysemy.Hasql.Data.DbType (Column (Column), Name (Name), Selector (Selector))
import qualified Polysemy.Hasql.Data.QueryTable as QueryTable
import Polysemy.Hasql.Data.QueryTable (QueryTable, UidQueryTable)
import qualified Polysemy.Hasql.Data.Table as Table
import Polysemy.Hasql.Data.Table (Table)
import Polysemy.Hasql.Database (HasqlConnection, interpretDatabase)
import Polysemy.Hasql.DbConnection (interpretDbConnection)
import Polysemy.Hasql.Session (convertQueryError)
import qualified Polysemy.Hasql.Statement as Statement
import Polysemy.Hasql.Store (StoreStack, interpretStoreDbFull)
import Polysemy.Hasql.Table (createTable, dropTable, runStatement)
import Polysemy.Hasql.Table.BasicSchema (BasicSchema, basicSchema)
import Polysemy.Hasql.Table.Query.Text (sqlQuote)
import Polysemy.Hasql.Table.Schema (Schema, UidQuerySchema, UidSchema, schema)
suffixedTable ::
Lens' t (Table d) ->
Text ->
t ->
t
suffixedTable lens suffix =
lens . Table.structure %~ applySuffix
where
applySuffix (Column (Name name) _ tpe opt dbTpe) =
Column (Name suffixed) (Selector (sqlQuote suffixed)) tpe opt dbTpe
where
suffixed =
[exon|#{name}-#{suffix}|]
bracketTestTable ::
Members [Resource, Embed IO, DbConnection Connection !! DbConnectionError, Random, Stop QueryError, Stop DbError] r =>
Lens' t (Table d) ->
t ->
(t -> Sem r a) ->
Connection ->
Sem r a
bracketTestTable lens t use connection =
bracket acquire release (const (use t))
where
acquire =
createTable connection (view Table.structure table)
release _ =
dropTable connection (view Table.name table)
table =
view lens t
withTestTable ::
Members [Resource, Embed IO, DbConnection Connection !! DbConnectionError, Random, Stop QueryError, Stop DbError] r =>
Lens' t (Table d) ->
t ->
(t -> Sem r a) ->
Sem r a
withTestTable lens table use = do
suffix <- UUID.toText <$> random
resumeHoist DbError.Connection $ DbConnection.use \ _ ->
bracketTestTable lens (suffixedTable lens suffix table) (raise . use)
withTestPlainTable ::
Members [Resource, Embed IO, DbConnection Connection !! DbConnectionError, Random, Stop QueryError, Stop DbError] r =>
Table d ->
(Table d -> Sem r a) ->
Sem r a
withTestPlainTable =
withTestTable id
withTestTableGen ::
∀ rep d a r .
Members [Resource, Embed IO, DbConnection Connection !! DbConnectionError, Random, Stop QueryError, Stop DbError] r =>
BasicSchema rep d =>
(Table d -> Sem r a) ->
Sem r a
withTestTableGen =
withTestPlainTable (basicSchema @rep)
withTestQueryTable ::
Members [Resource, Embed IO, DbConnection Connection !! DbConnectionError, Random, Stop QueryError, Stop DbError] r =>
QueryTable q d ->
(QueryTable q d -> Sem r a) ->
Sem r a
withTestQueryTable =
withTestTable QueryTable.table
withTestQueryTableGen ::
∀ qrep rep q d a r .
Members [Resource, Embed IO, DbConnection Connection !! DbConnectionError, Random, Stop QueryError, Stop DbError] r =>
Schema qrep rep q d =>
(QueryTable q d -> Sem r a) ->
Sem r a
withTestQueryTableGen =
withTestQueryTable (schema @qrep @rep)
createTestDb ::
Members [Random, DbConnection Connection !! DbConnectionError, Stop DbError, Embed IO] r =>
DbConfig ->
Connection ->
Sem r DbConfig
createTestDb dbConfig@(DbConfig _ _ (DbName name) _ _) connection = do
suffix <- UUID.toText <$> random
let
suffixedName = DbName [exon|#{name}-#{suffix}|]
suffixed = dbConfig & DbConfig.name .~ suffixedName
mapStop convertQueryError (runStatement connection () (Statement.createDb suffixedName))
pure suffixed
TODO this should use ` Error `
withTestDb ::
Members [Stop DbError, Resource, Embed IO, Final IO] r =>
DbConfig ->
(DbConfig -> Sem r a) ->
Sem r a
withTestDb baseConfig f =
interpretDbConnection "test" baseConfig do
resumeHoist DbError.Connection $ DbConnection.use \ _ connection ->
bracket (acquire baseConfig connection) (release connection) (raise . raise . f)
where
acquire config connection =
runRandomIO $ createTestDb config connection
release connection (DbConfig _ _ name _ _) =
mapStop convertQueryError (runStatement connection () (Statement.dropDb name))
withTestConnection ::
Members [Stop DbError, Time t dt, Resource, Embed IO, Final IO] r =>
DbConfig ->
Sem (Database !! DbError : HasqlConnection : r) a ->
Sem r a
withTestConnection baseConfig ma =
withTestDb baseConfig \ dbConfig ->
interpretDbConnection "test" dbConfig (interpretDatabase ma)
type TestStoreDeps =
[
Resource,
Embed IO,
HasqlConnection,
Database !! DbError,
Error DbError,
Random,
Log,
Stop QueryError,
Stop DbError,
GhcTime
]
withTestStoreUsing ::
∀ d i r a .
Members TestStoreDeps r =>
UidQueryTable i d ->
Sem (StoreStack i d ++ r) a ->
Sem r a
withTestStoreUsing table prog =
withTestQueryTable table \ t ->
interpretStoreDbFull t prog
withTestStoreTable ::
∀ qrep rep d i r a .
Members TestStoreDeps r =>
Schema qrep rep i (Uid i d) =>
(UidQueryTable i d -> Sem (StoreStack i d ++ r) a) ->
Sem r a
withTestStoreTable prog =
withTestQueryTableGen @qrep @rep \ table ->
interpretStoreDbFull table (prog table)
withTestStoreTableGenAs ::
∀ qrep rep irep d i r a .
Members TestStoreDeps r =>
UidQuerySchema qrep irep rep i i d =>
(UidQueryTable i d -> Sem (StoreStack i d ++ r) a) ->
Sem r a
withTestStoreTableGenAs prog =
withTestQueryTableGen @qrep @(UidRep irep rep) \ table ->
interpretStoreDbFull table (prog table)
withTestStoreTableGen ::
∀ rep i d r a .
Members TestStoreDeps r =>
UidSchema rep i d =>
(UidQueryTable i d -> Sem (StoreStack i d ++ r) a) ->
Sem r a
withTestStoreTableGen prog =
withTestQueryTableGen @(PrimQuery "id") @(UidRep PrimaryKey rep) \ table ->
interpretStoreDbFull table (prog table)
withTestStore ::
∀ qrep rep i d r .
Members TestStoreDeps r =>
Schema qrep rep i (Uid i d) =>
InterpretersFor (StoreStack i d) r
withTestStore prog =
withTestStoreTable @qrep @rep (const prog)
withTestStoreGenAs ::
∀ qrep irep rep i d r .
Members TestStoreDeps r =>
UidQuerySchema qrep irep rep i i d =>
InterpretersFor (StoreStack i d) r
withTestStoreGenAs prog =
withTestStoreTableGenAs @qrep @rep @irep (const prog)
withTestStoreGen ::
∀ rep i d r .
Members TestStoreDeps r =>
UidSchema rep i d =>
InterpretersFor (StoreStack i d) r
withTestStoreGen =
withTestStoreGenAs @(PrimQuery "id") @PrimaryKey @rep
withTestStoreAuto ::
∀ i d r a.
Members TestStoreDeps r =>
UidSchema Auto i d =>
Sem (StoreStack i d ++ r) a ->
Sem r a
withTestStoreAuto =
withTestStoreGen @Auto
withTestStoreUidAs ::
∀ qrep irep i d r a.
Members TestStoreDeps r =>
Schema qrep (UidRep irep Auto) i (Uid i d) =>
Sem (StoreStack i d ++ r) a ->
Sem r a
withTestStoreUidAs prog =
withTestQueryTableGen @qrep @(UidRep irep Auto) \ table ->
interpretStoreDbFull table prog
withTestStoreUid ::
∀ i d r a.
Members TestStoreDeps r =>
Schema (PrimQuery "id") (UidRep PrimaryKey Auto) i (Uid i d) =>
Sem (StoreStack i d ++ r) a ->
Sem r a
withTestStoreUid prog =
withTestQueryTableGen @(PrimQuery "id") @(UidRep PrimaryKey Auto) \ table ->
interpretStoreDbFull table prog
| |
f36eb727aaf7000f76c0202f18e048f562f109f86471720497f44763c80c7a3e | namenu/bootcamp-maze | sidewinder.cljc | (ns maze.seq.sidewinder
(:require [maze.core :refer [full-grid size link-toward advance]])
(:require-macros [maze.seq.macros :refer [defmaze]]))
(defn close-out?
"옆으로 진행하기를 멈추고 아래를 확장할 것인지?"
[[rows cols] [r c]]
(or (= c (dec cols))
(and (< r (dec rows))
(rand-nth [true false]))))
(defmaze Sidewinder [output coords run]
(if-let [pos (first coords)]
(let [run (conj run pos)
[pos dir new-run] (if (close-out? (:size output) pos)
[(rand-nth run) :north []]
[pos :east run])]
(Sidewinder. (-> output
(update :grid link-toward pos dir)
(assoc :frontier [(advance pos dir)]))
(rest coords)
new-run))))
(defn sidewinder [rows cols]
(Sidewinder. {:size [rows cols]
:grid (full-grid rows cols)
:frontier nil}
(->> (for [i (range rows) j (range cols)]
[i j])
(butlast))
[]))
| null | https://raw.githubusercontent.com/namenu/bootcamp-maze/0558ba6b624bc0b6a5312415972398401396c4cf/src/maze/seq/sidewinder.cljc | clojure | (ns maze.seq.sidewinder
(:require [maze.core :refer [full-grid size link-toward advance]])
(:require-macros [maze.seq.macros :refer [defmaze]]))
(defn close-out?
"옆으로 진행하기를 멈추고 아래를 확장할 것인지?"
[[rows cols] [r c]]
(or (= c (dec cols))
(and (< r (dec rows))
(rand-nth [true false]))))
(defmaze Sidewinder [output coords run]
(if-let [pos (first coords)]
(let [run (conj run pos)
[pos dir new-run] (if (close-out? (:size output) pos)
[(rand-nth run) :north []]
[pos :east run])]
(Sidewinder. (-> output
(update :grid link-toward pos dir)
(assoc :frontier [(advance pos dir)]))
(rest coords)
new-run))))
(defn sidewinder [rows cols]
(Sidewinder. {:size [rows cols]
:grid (full-grid rows cols)
:frontier nil}
(->> (for [i (range rows) j (range cols)]
[i j])
(butlast))
[]))
| |
49c0710bf29e1025112a1d581f94b313f739f6ae31012e17496b160b037458a7 | herbelin/coq-hh | proof_global.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(** This module defines the global proof environment
Especially it keeps tracks of whether or not there is a proof which is currently being edited. *)
(** Type of proof modes :
- A name
- A function [set] to set it *from standard mode*
- A function [reset] to reset the *standard mode* from it
*)
type proof_mode = {
name : string ;
set : unit -> unit ;
reset : unit -> unit
}
* Registers a new proof mode which can then be adressed by name
in [ set_default_proof_mode ] .
One mode is already registered - the standard mode - named " No " ,
It corresponds to Coq default setting are they are set when coqtop starts .
in [set_default_proof_mode].
One mode is already registered - the standard mode - named "No",
It corresponds to Coq default setting are they are set when coqtop starts. *)
val register_proof_mode : proof_mode -> unit
val there_is_a_proof : unit -> bool
val there_are_pending_proofs : unit -> bool
val check_no_pending_proof : unit -> unit
val get_current_proof_name : unit -> Names.identifier
val get_all_proof_names : unit -> Names.identifier list
val discard : Names.identifier Util.located -> unit
val discard_current : unit -> unit
val discard_all : unit -> unit
(** [set_proof_mode] sets the proof mode to be used after it's called. It is
typically called by the Proof Mode command. *)
val set_proof_mode : string -> unit
exception NoCurrentProof
val give_me_the_proof : unit -> Proof.proof
* [ start_proof s str goals ~init_tac ~compute_guard hook ] starts
a proof of name [ s ] and
conclusion [ t ] ; [ hook ] is optionally a function to be applied at
proof end ( e.g. to declare the built constructions as a coercion
or a setoid morphism ) .
a proof of name [s] and
conclusion [t]; [hook] is optionally a function to be applied at
proof end (e.g. to declare the built constructions as a coercion
or a setoid morphism). *)
type lemma_possible_guards = int list list
val start_proof : Names.identifier ->
Decl_kinds.goal_kind ->
(Environ.env * Term.types) list ->
?compute_guard:lemma_possible_guards ->
Tacexpr.declaration_hook ->
unit
val close_proof : unit ->
Names.identifier *
(Entries.definition_entry list *
lemma_possible_guards *
Decl_kinds.goal_kind *
Tacexpr.declaration_hook)
exception NoSuchProof
val suspend : unit -> unit
val resume_last : unit -> unit
val resume : Names.identifier -> unit
* @raise NoSuchProof if it does n't find
(* Runs a tactic on the current proof. Raises [NoCurrentProof] is there is
no current proof. *)
val run_tactic : unit Proofview.tactic -> unit
(* Sets the tactic to be used when a tactic line is closed with [...] *)
val set_endline_tactic : unit Proofview.tactic -> unit
(* Appends the endline tactic of the current proof to a tactic. *)
val with_end_tac : unit Proofview.tactic -> unit Proofview.tactic
module V82 : sig
val get_current_initial_conclusions : unit -> Names.identifier *(Term.types list * Decl_kinds.goal_kind * Tacexpr.declaration_hook)
end
| null | https://raw.githubusercontent.com/herbelin/coq-hh/296d03d5049fea661e8bdbaf305ed4bf6d2001d2/proofs/proof_global.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* This module defines the global proof environment
Especially it keeps tracks of whether or not there is a proof which is currently being edited.
* Type of proof modes :
- A name
- A function [set] to set it *from standard mode*
- A function [reset] to reset the *standard mode* from it
* [set_proof_mode] sets the proof mode to be used after it's called. It is
typically called by the Proof Mode command.
Runs a tactic on the current proof. Raises [NoCurrentProof] is there is
no current proof.
Sets the tactic to be used when a tactic line is closed with [...]
Appends the endline tactic of the current proof to a tactic. | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
type proof_mode = {
name : string ;
set : unit -> unit ;
reset : unit -> unit
}
* Registers a new proof mode which can then be adressed by name
in [ set_default_proof_mode ] .
One mode is already registered - the standard mode - named " No " ,
It corresponds to Coq default setting are they are set when coqtop starts .
in [set_default_proof_mode].
One mode is already registered - the standard mode - named "No",
It corresponds to Coq default setting are they are set when coqtop starts. *)
val register_proof_mode : proof_mode -> unit
val there_is_a_proof : unit -> bool
val there_are_pending_proofs : unit -> bool
val check_no_pending_proof : unit -> unit
val get_current_proof_name : unit -> Names.identifier
val get_all_proof_names : unit -> Names.identifier list
val discard : Names.identifier Util.located -> unit
val discard_current : unit -> unit
val discard_all : unit -> unit
val set_proof_mode : string -> unit
exception NoCurrentProof
val give_me_the_proof : unit -> Proof.proof
* [ start_proof s str goals ~init_tac ~compute_guard hook ] starts
a proof of name [ s ] and
conclusion [ t ] ; [ hook ] is optionally a function to be applied at
proof end ( e.g. to declare the built constructions as a coercion
or a setoid morphism ) .
a proof of name [s] and
conclusion [t]; [hook] is optionally a function to be applied at
proof end (e.g. to declare the built constructions as a coercion
or a setoid morphism). *)
type lemma_possible_guards = int list list
val start_proof : Names.identifier ->
Decl_kinds.goal_kind ->
(Environ.env * Term.types) list ->
?compute_guard:lemma_possible_guards ->
Tacexpr.declaration_hook ->
unit
val close_proof : unit ->
Names.identifier *
(Entries.definition_entry list *
lemma_possible_guards *
Decl_kinds.goal_kind *
Tacexpr.declaration_hook)
exception NoSuchProof
val suspend : unit -> unit
val resume_last : unit -> unit
val resume : Names.identifier -> unit
* @raise NoSuchProof if it does n't find
val run_tactic : unit Proofview.tactic -> unit
val set_endline_tactic : unit Proofview.tactic -> unit
val with_end_tac : unit Proofview.tactic -> unit Proofview.tactic
module V82 : sig
val get_current_initial_conclusions : unit -> Names.identifier *(Term.types list * Decl_kinds.goal_kind * Tacexpr.declaration_hook)
end
|
f0706a22dd231c62a8b56c36852312ec31f64f1e02d989c5c10bb8740fb63f13 | robert-strandh/CLIMatis | camfer.lisp | ;;; FIXME: the bends in the `f', the `t', and the `j' should look the
;;; same, but currently the code is duplicated. Improve by making
;;; the width and the start of the bend font-wide parameters.
(in-package #:camfer)
(defgeneric ascent (font))
(defgeneric descent (font))
(defgeneric width (font))
(defclass font ()
((%ascent :initarg :ascent :reader ascent)
(%lower-case-ascent :initarg :lower-case-ascent :reader lower-case-ascent)
(%stroke-width :initarg :stroke-width :reader stroke-width)
(%stroke-height :initarg :stroke-height :reader stroke-height)
(%upper-case-h-width :initarg :upper-case-h-width :reader upper-case-h-width)
(%upper-case-o-width :initarg :upper-case-o-width :reader upper-case-o-width)
(%digit-width :initarg :digit-width :reader digit-width)
(%upper-case-h-bar-position :initarg :upper-case-h-bar-position
:reader upper-case-h-bar-position)
(%width :initarg :width :reader width)
(%descent :initarg :descent :reader descent)
(%j-width :initarg :j-width :reader j-width)
;; The horizontal distance from the right edge of the `j'
;; to the min-point of the hook
(%j-hook-extreme :initarg :j-hook-extreme :reader j-hook-extreme)
;; The vertical distance beteween the bottom of the j and
;; the point where the hook starts.
(%j-hook-start :initarg :j-hook-start :reader j-hook-start)
(%slash-width :initarg :slash-width :reader slash-width)
(%bracket-descent :initarg :bracket-descent :reader bracket-descent)
(%bracket-width :initarg :bracket-width :reader bracket-width)
(%bracket-ascent :initarg :bracket-ascent :reader bracket-ascent)
(%kerning-info :initform (make-hash-table :test #'equal) :reader kerning-info)
(%glyphs :initform (make-hash-table) :reader glyphs)))
(defclass glyph ()
((%x-offset :initarg :x-offset :reader x-offset)
(%y-offset :initarg :y-offset :reader y-offset)
(%left-shape :initarg :left-shape :reader left-shape)
(%right-shape :initarg :right-shape :reader right-shape)
(%mask :initarg :mask :reader mask)))
(defun make-glyph (paths left-shape right-shape)
(let ((x-min most-positive-fixnum)
(y-min most-positive-fixnum)
(x-max most-negative-fixnum)
(y-max most-negative-fixnum))
(flet ((convert-path-to-knots (path)
(let* ((dpath (paths:make-discrete-path path))
(iterator (paths:path-iterator dpath)))
(paths:path-iterator-reset iterator)
(loop with end = nil
collect (multiple-value-bind (interpolation knot end-p)
(paths:path-iterator-next iterator)
(declare (ignore interpolation))
(setf end end-p)
knot)
until end)))
(determine-min-max (x y alpha)
(declare (ignore alpha))
(setf x-min (min x-min x)
y-min (min y-min y)
x-max (max x-max x)
y-max (max y-max y))))
(let ((state (aa:make-state))
(knot-paths (mapcar #'convert-path-to-knots paths)))
(loop for path in knot-paths
do (loop for (p1 p2) on path
until (null p2)
do (aa:line-f state
(paths:point-x p1) (paths:point-y p1)
(paths:point-x p2) (paths:point-y p2))))
(aa:cells-sweep state #'determine-min-max)
(let* ((height (1+ (- y-max y-min)))
(width (1+ (- x-max x-min)))
(mask (make-array (list height width)
:element-type 'double-float
:initial-element 0d0)))
(aa:cells-sweep state (lambda (x y alpha)
(setf alpha (min 256 (max 0 alpha)))
(setf (aref mask (- y-max y) (- x x-min))
(/ alpha 256d0))))
(make-instance 'glyph
:x-offset x-min :y-offset (- y-max)
:left-shape left-shape :right-shape right-shape
:mask mask))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Basic character elements
1
;;; |
;;; **
0 -****- 2
;;; **
;;; |
3
;;; If the stroke width is odd, then the x coordinate of the
;;; center point will be in the middle of a pixel, and if is
;;; even, then the x coordinate will be an integer. A similar
;;; thing holds for the stroke height and the y coordinate.
(defun make-dot (font center)
(with-accessors ((stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((x (realpart center))
(y (imagpart center))
(sw/2 (/ stroke-width 2))
(sh/2 (/ stroke-height 2))
(p0 (c (- x sw/2) y))
(p1 (c x (+ y sh/2)))
(p2 (c (+ x sw/2) y))
(p3 (c x (- y sh/2))))
(mf p0 up ++ p1 right ++ p2 down ++ p3 left ++ cycle)))))
;;;
;;;
2
;;; |
;;; *******
;;; *************
;;; **** | ****
;;; **** 6 ****
;;; **** ****
;;; **** ****
1- * * * * -5 7-****-3
;;; **** ****
;;; **** ****
;;; **** 4 ****
;;; **** | ****
;;; *************
;;; *******
;;; |
;;; 0
;;;
(defun make-o-paths (font)
(with-accessors ((width width)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(let* ((p0 (complex (/ width 2) 0))
(p1 (complex 0 (/ lower-case-ascent 2)))
(p2 (complex (/ width 2) lower-case-ascent))
(p3 (complex width (/ lower-case-ascent 2)))
(p4 (+ p0 (complex 0 stroke-height)))
(p5 (+ p1 stroke-width))
(p6 (- p2 (complex 0 stroke-height)))
(p7 (- p3 stroke-width)))
(list (mf p0 left ++ p1 up ++ p2 right ++ p3 down ++ cycle)
(mf p4 right ++ p7 up ++ p6 left ++ p5 down ++ cycle)))))
;;;
;;;
;;; | |
;;; | |
;;; | |
;;; | |
;;; | |
;;; | |
;;; | | 3
;;; | | /
;;; | |******
| * * | * * * * * * * * * 2
;;; | ***|* | ***** /
4-|****| 6 7- * * * * \
| |\5 * * * * |
;;; | | **** |
;;; | | **** |
;;; | | **** | bend-start
;;; | | **** |
;;; | | **** |
;;; |____| **** /
;;; / \
;;; 0 1
;;;
;;; \_______________/
;;; |
;;; width
;;;
(defun make-h-m-n-hook (font p0 width)
(with-accessors ((lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((bend-start (- lower-case-ascent (* stroke-height 3.0)))
(p1 (+ p0 stroke-width))
(p2 (+ p1 (c 0 bend-start)))
(p4 (- p2 width))
(p5 (+ p4 (* 0.5 stroke-width)))
(p3 (c (realpart (* 1/2 (+ p2 p4))) lower-case-ascent))
(p6 (- p3 (c 0 stroke-height)))
(p7 (- p2 stroke-width)))
(mf p0 --
p7 up ++
p6 left ++
down p5 --
p4 up ++
p3 right ++
down p2 --
p1 -- cycle)))))
;;;
;;; 1 2
;;; \ /
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; ++++
;;; / \
;;; 0 3
;;;
(defun make-vertical-stroke (font p0 height)
(with-accessors ((stroke-width stroke-width))
font
(let* ((p1 (+ p0 (complex 0 height)))
(p2 (+ p1 stroke-width))
(p3 (+ p0 stroke-width)))
(mf p0 -- p1 -- p2 -- p3 -- cycle))))
;;;
;;;
;;; 1 2
;;; *****************************************
;;; *****************************************
;;; 0 3
;;;
;;;
(defun make-horizontal-stroke (font p0 width)
(with-accessors ((stroke-height stroke-height))
font
(let* ((p1 (+ p0 (complex 0 stroke-height)))
(p2 (+ p1 width))
(p3 (+ p0 width)))
(mf p0 -- p1 -- p2 -- p3 -- cycle))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The characters
;;;
;;;
;;;
;;;
;;;
;;;
;;;
;;;
13
;;; |
;;; *********
;;; *************
12- * * * 10 * * * * -
;;; 11 1 9-****- 14 - |
;;; \ **** | |
;;; ************* - | |
;;; *************** | | | h4
;;; **** 5 **** | | h3 |
0 -****- 4 6-****- 2 - | h2 | |
;;; **** 7 **** | | | |
;;; *************** | h1 | | |
;;; ******** **** _ _| _| _|
;;; | | \
3 8 15
(defun make-glyph-lower-case-a (font)
(with-accessors ((width width)
(lower-case-ascent lower-case-ascent )
(stroke-width stroke-width )
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (* lower-case-ascent 0.3))
(h2 (round (* lower-case-ascent 0.65)))
(h3 (* lower-case-ascent 0.7))
(h4 (round (* lower-case-ascent 0.75)))
(p0 (c 0 h1))
(p3 (c (* width 0.5) 0))
(p1 (+ p3 (c 0 h2)))
(p2 (+ p0 width))
(p4 (+ p0 stroke-width))
(p5 (- p1 (c 0 stroke-height)))
(p6 (- p2 stroke-width))
(p7 (+ p3 (c 0 stroke-height)))
(p8 (c (- width stroke-width) 0))
(p9 (c (- width stroke-width) h3))
(p10 (c (* width 0.6) (- lower-case-ascent stroke-height)))
(p12 (c (round (* width 0.1)) h4))
(p11 (+ p12 stroke-width))
(p13 (+ p10 (c 0 stroke-height)))
(p14 (+ p9 (c stroke-width 0)))
(p15 (c width 0)))
(make-glyph
(list (mf p0 up ++ p1 right ++ p2 down ++ p3 left ++ cycle)
(mf p4 down ++ p7 right ++ p6 up ++ p5 left ++ cycle)
(mf p8 -- p9 up ++ p10 left ++ down p11 --
p12 up ++ p13 right ++ down p14 -- p15 -- cycle))
#\a #\i)))))
(defun make-glyph-lower-case-b (font)
(with-accessors ((ascent ascent))
font
(make-glyph (cons (make-vertical-stroke font #c(0 0) ascent)
(make-o-paths font))
#\l #\o)))
;;;
;;; *******
;;; *************
;;; **** ****
;;; **** */ -2
;;; **** /
;;; **** /
;;; **** 0-*
;;; **** \
;;; **** \
;;; **** *\ -1 \
;;; **** **** |
;;; ************* | h
;;; ******* /
;;;
(defun make-glyph-lower-case-c (font)
(with-accessors ((width width)
(lower-case-ascent lower-case-ascent)
(stroke-height stroke-height))
font
(let* ((h (* stroke-height (if (< width 5) 1 1.7)))
(p0 (complex (/ width 2) (/ lower-case-ascent 2)))
(p1 (complex width h))
(p2 (complex width (- lower-case-ascent h))))
(make-glyph (cons (mf p0 -- p1 -- p2 -- cycle)
(make-o-paths font))
#\o #\c))))
(defun make-glyph-lower-case-d (font)
(with-accessors ((ascent ascent)
(width width)
(stroke-width stroke-width))
font
(make-glyph (cons (make-vertical-stroke font (- width stroke-width) ascent)
(make-o-paths font))
#\o #\l)))
;;;
;;; *******
;;; *************
;;; **** ****
* * * * 4 5 * * * *
;;; ****/ \****
;;; *****************
;;; *****************
;;; *****************- 2 -
;;; ****\ | / |
* * * * 3 0 6 * \ - 1 |
;;; **** **** \ | m
;;; ************* | h |
;;; ******* / _|
;;;
(defun make-glyph-lower-case-e (font)
(with-accessors ((width width)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(let* ((h (* stroke-height 1.7))
(m (ceiling (- lower-case-ascent stroke-height) 2))
(p0 (complex (/ width 2) m))
(p1 (complex width h))
(p2 (complex width m))
(p3 (complex stroke-width m))
(p4 (complex stroke-width (+ m stroke-height)))
(p5 (complex (- width stroke-width) (+ m stroke-height)))
(p6 (complex (- width stroke-width) m)))
(make-glyph (list* (mf p0 -- p1 -- p2 -- cycle)
(mf p4 -- p5 -- p6 -- p3 -- cycle)
(make-o-paths font))
#\o #\o))))
;;; w2
;;; ________
;;; | |
;;;
;;; w3
;;; _____
;;; | |
6 7
;;; | /
;;; ****
;;; *******\
;;; **** \ 8
5 -****10 9 -
;;; **** |
;;; **** |
;;; **** |
;;; **** |
4 * * * * 11 |
;;; \****/ |
3 -********- 12 |
2 -********- 13 |
;;; /****\14 | h
1 * * * * |
;;; ****|_| |
;;; **** w1 |
;;; **** |
;;; **** |
;;; **** |
;;; **** |
;;; **** |
;;; **** |
;;; **** |
;;; **** |
;;; **** _|
;;; / \
0 15
;;;
(defun make-glyph-lower-case-f (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(j-width j-width)
(j-hook-start j-hook-start)
(lower-case-ascent lower-case-ascent))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (max 1 (round (* ascent 0.1))))
(w2 j-width)
(w3 (* ascent 0.2))
(h (- ascent j-hook-start))
(p0 (c w1 0))
(p1 (+ p0 (c 0 (- lower-case-ascent stroke-height))))
(p2 (- p1 (c w1 0)))
(p3 (+ p2 (c 0 stroke-height)))
(p4 (+ p1 (c 0 stroke-height)))
(p5 (+ p0 (c 0 h)))
(p6 (c (+ w1 w3) ascent))
(p7 (c (+ w1 w2) ascent))
(p8 (- p7 (c 0 stroke-height)))
(p9 (- p6 (c 0 stroke-height)))
(p10 (+ p5 stroke-width))
(p11 (+ p4 stroke-width))
(p12 (+ p3 stroke-width (* 2 w1)))
(p13 (+ p2 stroke-width (* 2 w1)))
(p14 (+ p1 stroke-width))
(p15 (+ p0 stroke-width)))
(make-glyph
(list (mf p0 -- p1 -- p2 -- p3 -- p4 -- p5 up ++
right p6 -- p7 -- p8 -- p9 left ++
down p10 -- p11 -- p12 -- p13 -- p14 -- p15 -- cycle))
#\f #\f)))))
;;;
;;;
;;; 0 1
;;; | /
;;; ******* ****
;;; ***************
;;; **** *****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** *****
;;; ***************
;;; ------ *******-****---- - -
;;; **** | h1 |
6 7 -****- 2 _ | |
;;; 5 \ | *** | h2
;;; ************ |
4 - * * * * * * * * * * _ |
;;; |
3
;;;
;;; |_|
;;; w2
;;;
;;; |______|
;;; w1
(defun make-glyph-lower-case-g (font)
(with-accessors ((ascent ascent)
(width width)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(descent descent))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (* ascent 0.07))
(h2 descent)
(w1 (* width 0.5))
(w2 (round (* 0.2 width)))
(p0 (c (- width stroke-width) lower-case-ascent))
(p1 (+ p0 stroke-width))
(p2 (c width (- h1)))
(p3 (c w1 (- h2)))
(p4 (c w2 (- h2)))
(p5 (+ p4 (c 0 stroke-height)))
(p6 (+ p3 (c 0 stroke-height)))
(p7 (- p2 stroke-width)))
(make-glyph
(cons (mf p0 -- p1 -- p2 down ++ left p3 -- p4 --
p5 -- p6 right ++ up p7 -- cycle)
(make-o-paths font))
#\o #\q)))))
(defun make-glyph-lower-case-h (font)
(with-accessors ((ascent ascent)
(width width)
(stroke-width stroke-width))
font
(let ((w (round (* 0.9 width))))
(make-glyph (list (make-vertical-stroke font #c(0 0) ascent)
(make-h-m-n-hook font (- w stroke-width) w))
#\l #\i))))
(defun make-glyph-lower-case-i (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(make-glyph (list (make-vertical-stroke font #c(0 0) lower-case-ascent)
(make-dot font
(complex (/ stroke-height 2)
(+ lower-case-ascent (* 3/2 stroke-height)))))
#\i #\i)))
;;;
;;; **
;;; ****
1 * * 2
;;; \ /
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; w1 ****
;;; _____ ****
;;; | |****
;;; ****
;;; ****
;;; 0-**** -
;;; **** |
;;; **** |
;;; **** | h
6 7 8-****-3 _ |
;;; \ \ ****
;;; *******
;;; ****
;;; / |
5 4
;;; |__|
;;; w2
;;;
(defun make-glyph-lower-case-j (font)
(with-accessors ((ascent ascent)
(descent descent)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(j-width j-width)
(j-hook-extreme j-hook-extreme)
(j-hook-start j-hook-start)
(width width))
font
(flet ((c (x y) (complex x y)))
(let* ((h (- descent j-hook-start))
( h ( * 0.1 descent ) )
FIXME , make these the same as for the ` f '
(w1 (- j-width stroke-width))
(w2 (- j-width j-hook-extreme))
( w2 ( * 1.0 stroke - width ) )
(p0 (c w1 0))
(p1 (+ p0 (c 0 lower-case-ascent)))
(p2 (+ p1 stroke-width))
(p3 (- p2 (c 0 (+ lower-case-ascent h))))
(p4 (c w2 (- descent)))
(p5 (c 0 (- descent)))
(p6 (+ p5 (c 0 stroke-height)))
(p7 (+ p4 (c 0 stroke-height)))
(p8 (- p3 stroke-width)))
(make-glyph (list (make-dot font
(c (+ w1 (/ stroke-width 2))
(+ lower-case-ascent (* 3/2 stroke-height))))
(mf p0 -- p1 -- p2 -- p3 down ++
left p4 -- p5 -- p6 -- p7 right ++
up p8 -- cycle))
#\j #\q)))))
;;;
;;;
;;; 1 2
;;; \ /
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; **** 4 5
;;; **** \ /
;;; **** ****
;;; **** ****
;;; **** ****
* * * * 3 * * * *
;;; **********- 6 -
* * * * * * 9 * * * * |
- * * * * 10 * * * * |
;;; | **** **** | h2
;;; h1 | **** **** |
;;; | **** **** |
;;; |_ **** **** _|
;;; / \ / \
;;; 0 11 8 7
;;;
;;; |_______________|
;;; w
(defun make-glyph-lower-case-k (font)
(with-accessors ((ascent ascent)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(width width))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (* 0.4 lower-case-ascent))
(h2 (* 0.6 lower-case-ascent))
(w (round (* (if (< width 5) 1.1 0.9) width)))
(p0 (c 0 0))
(p1 (c 0 ascent))
(p2 (+ p1 stroke-width))
(p10 (c stroke-width h1))
;; average stroke for angled lines
(stroke (* 0.5 (+ stroke-width stroke-height)))
assume angles are around 45 degrees
(p3 (+ p10 (c 0 (* stroke 1.2))))
(p5 (c w lower-case-ascent))
(p4 (- p5 (* stroke 1.4)))
(dx10-5 (- w stroke-width))
(dy10-5 (- lower-case-ascent h1))
(dy10-6 (- h2 h1))
(dx10-6 (* dy10-6 (/ dx10-5 dy10-5)))
(p6 (c (+ stroke-width dx10-6) h2))
(p7 (c w 0))
(p8 (- p7 (* 1.4 stroke)))
(dy10-9 (- dy10-6 (* 0.7 stroke)))
(dx10-9 (* dy10-9 (/ dx10-5 dy10-5)))
(p9 (+ p10 (c dx10-9 dy10-9)))
(p11 (c stroke-width 0)))
(make-glyph
(list (mf p0 -- p1 -- p2 -- p3 -- p4 -- p5 -- p6 --
p7 -- p8 -- p9 -- p10 -- p11 -- cycle))
#\l #\x)))))
(defun make-glyph-lower-case-l (font)
(make-glyph (list (make-vertical-stroke font 0 (ascent font)))
#\l #\l))
(defun make-glyph-lower-case-m (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(width width))
font
(let ((d (round (* 0.5 width)))
(sw stroke-width))
(make-glyph
(list (make-vertical-stroke font #c(0 0) lower-case-ascent)
(make-h-m-n-hook font (+ sw d) (+ sw sw d))
(make-h-m-n-hook font (+ sw d sw d) (+ sw sw d)))
#\i #\i))))
(defun make-glyph-lower-case-n (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(width width)
(stroke-width stroke-width))
font
(let ((w (round (* 0.9 width))))
(make-glyph (list (make-vertical-stroke font #c(0 0) lower-case-ascent)
(make-h-m-n-hook font (- w stroke-width) w))
#\i #\i))))
(defun make-glyph-lower-case-o (font)
(make-glyph (make-o-paths font) #\o #\o))
(defun make-glyph-lower-case-p (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(descent descent))
font
(make-glyph (cons (make-vertical-stroke font
(complex 0 (- descent))
(+ lower-case-ascent descent))
(make-o-paths font))
#\p #\o)))
(defun make-glyph-lower-case-q (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(width width)
(stroke-width stroke-width)
(descent descent))
font
(make-glyph (cons (make-vertical-stroke font
(complex (- width stroke-width)
(- descent))
(+ lower-case-ascent descent))
(make-o-paths font))
#\o #\q)))
;;;
;;;
1
;;; ---- /
;;; | | *****
;;; | |**********
;;; | ***** \
| * * * | 2
;;; 0 -|*** |
;;; | / |
;;; |3 |
;;; | |
;;; | |
;;; | |
;;; | |
;;; | |
;;; | |
;;; | |
;;; | |
;;; | |
;;; | |
;;; ----
;;;
;;;
(defun make-glyph-lower-case-r (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(width width))
font
(flet ((c (x y) (complex x y)))
(let* ((bend-start (- lower-case-ascent (* stroke-height 3.0)))
(w (* 0.5 width))
(p0 (c 0 bend-start))
(p1 (c w lower-case-ascent))
(p2 (- p1 (c 0 stroke-height)))
(p3 (+ p0 (* 0.5 stroke-width))))
(make-glyph
(list (make-vertical-stroke font (c 0 0) lower-case-ascent)
(mf p0 up ++ right p1 -- p2 left ++ down p3 -- cycle))
#\i #\r)))))
;;;
;;;
;;;
6
;;; |
;;; *******
;;; ************
* * * * * * * * * * * * * * * * * - 7
;;; **** | ****
* * * * 9 * - 8
;;; 5 -****- 10
* * * * 11
;;; ****** |
;;; ***************
;;; ****************
;;; | ******
4 * * * *
;;; 3 -****- 12 -
;;; 1 -* 2 **** |
;;; **** | **** |
;;; - 0 -****************** | h2
;;; h1 | ************** |
;;; |_ ******* _|
;;; |
13
;;;
;;;
;;;
;;;
(defun make-glyph-lower-case-s (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(width width))
font
(flet ((c (x y) (complex x y)))
(let* ((upper-shrink (round (* width 0.1)))
(h1 (* lower-case-ascent 0.15))
(h2 (* lower-case-ascent 0.3))
(delta (if (or (and (oddp lower-case-ascent)
(evenp stroke-height))
(and (evenp lower-case-ascent)
(oddp stroke-height)))
1/2
0))
(p0 (c 0 h1))
assume angle about 45 degrees
(p1 (+ p0 (* stroke-width (c 0.7 0.7))))
(p13 (c (* 0.5 width) 0))
(p2 (+ p13 (c 0 stroke-height)))
(p12 (c width h2))
(p3 (- p12 stroke-width))
(p4 (c (* 0.5 width) (+ (* 1/2 (- lower-case-ascent stroke-height)) delta)))
(p11 (+ p4 (c 0 stroke-height)))
(p5 (c upper-shrink (- lower-case-ascent h2)))
(p10 (+ p5 stroke-width))
(p6 (c (* 0.5 width) lower-case-ascent))
(p9 (- p6 (c 0 stroke-height)))
(p7 (c (- width upper-shrink) (- lower-case-ascent h1)))
(p8 (+ p7 (- p0 p1))))
(make-glyph
(list (mf p0 -- p1 ++ right p2 ++ up p3 ++ left p4 ++
up p5 ++ right p6 ++ p7 -- p8 ++ left p9 ++
down p10 ++ right p11 ++ down p12 ++ left p13 ++ cycle))
#\o #\o)))))
;;; 5 6
;;; \ /
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
4 * * * * 7
;;; \****/
3 - * * * * * * * * * * - 8
2 - * * * * * * * * * * - 9
;;; /****\
1 * * * * 10
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
0 -****- 11
* * * * 12 13
;;; **** | /
;;; *******
;;; ****
;;; | \
15 14
(defun make-glyph-lower-case-t (font)
(with-accessors ((ascent ascent)
(descent descent)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(j-width j-width)
(j-hook-extreme j-hook-extreme)
(j-hook-start j-hook-start)
(width width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (max 1 (round (* ascent 0.1))))
(p0 (c w1 j-hook-start))
(p1 (c w1 (- lower-case-ascent stroke-height)))
(p2 (- p1 w1))
(p3 (+ p2 (c 0 stroke-height)))
(p4 (+ p3 w1))
(p5 (c w1 (round (* 0.8 ascent))))
(p6 (+ p5 stroke-width))
(p7 (+ p4 stroke-width))
(p8 (+ p7 w1))
(p9 (- p8 (c 0 stroke-height)))
(p10 (+ p1 stroke-width))
(p11 (+ p0 stroke-width))
(p12 (c (+ w1 j-hook-extreme) stroke-height))
(p13 (c (+ w1 j-width) stroke-height))
(p14 (+ w1 j-width))
(p15 (+ w1 j-hook-extreme)))
(make-glyph
(list (mf p0 -- p1 -- p2 -- p3 -- p4 -- p5 -- p6 -- p7 -- p8 --
p9 -- p10 -- p11 down ++ right p12 -- p13 --
p14 -- p15 left ++ up cycle))
#\l #\t)))))
(defun make-glyph-lower-case-u (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(width width)
(stroke-width stroke-width))
font
(let ((w (round (* 0.9 width))))
(make-glyph (list (make-vertical-stroke font (- width stroke-width) lower-case-ascent)
(paths:path-rotate
(make-h-m-n-hook font (- w stroke-width) w)
pi
(paths:make-point (* 0.5 width) (* 0.5 lower-case-ascent))))
#\u #\i))))
;;; w1
;;; _____________
;;; | |
;;;
;;; w3
;;; __
;;; | |
;;;
1 * * * * 2 4 * * * * 5
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
* * * * 3 * * * *
;;; *******
;;; *******
;;; *****
0 * * * * * 6
;;;
|___|
;;; w2
(defun make-glyph-lower-case-v (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(width width)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (max 4 (round (* 0.9 width))))
(w2 (* 1.1 stroke-width))
(w3 (* 1.0 stroke-width))
(p0 (* 0.5 (- w1 w2)))
(p1 (c 0 lower-case-ascent))
(p2 (+ p1 w3))
(p3 (c (* 0.5 w1) (* 1.1 stroke-width))) ; guess and adjust y coordinate
(p4 (+ p1 (- w1 w3)))
(p5 (+ p1 w1))
(p6 (+ p0 w2)))
(make-glyph (list (mf p0 -- p1 -- p2 -- p3 -- p4 -- p5 -- p6 -- cycle))
#\v #\v)))))
;;; w1
;;; ______________________
;;; | |
;;;
;;; w3
;;; __
;;; | |
;;;
b****c
;;; **** ****
;;; **** ****
;;; **** e f ****
;;; **** **** ****
;;; **** **** ****
;;; **** ****** ****
;;; ****d***l***g****
;;; ******* *******
;;; ******* *******
;;; ***** *****
;;; a *****m k*****j
;;;
|_____|___|
;;; w4 w2
(defun make-glyph-lower-case-w (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(width width)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (max 5 (round (* 1.2 width))))
(w2 (* 1.0 stroke-width))
(w3 (* 1.0 stroke-width))
(w4 (* 0.2 w1))
(pa (c w4 0))
(pb (c 0 lower-case-ascent))
(pc (+ pb w3))
(pd (c (+ w4 (* 0.5 w2)) (* 1.0 stroke-height)))
(pe (c (* 0.5 (- w1 w2)) (* 0.7 lower-case-ascent)))
(pf (+ pe w2))
(pg (c (- w1 (+ w4 (* 0.5 w2))) (* 1.0 stroke-height)))
(ph (c (- w1 w3) lower-case-ascent))
(ppi (c w1 lower-case-ascent))
(pj (c (- w1 w4) 0))
(pk (- pj w2))
(pl (c (* 0.5 w1) (- (imagpart pe) (* 1.0 stroke-height))))
(pm (+ pa w2)))
(make-glyph (list (mf pa -- pb -- pc -- pd -- pe -- pf -- pg --
ph -- ppi -- pj -- pk -- pl -- pm -- cycle))
#\v #\v)))))
;;;
;;; w1
;;; ______________
;;; | |
;;;
;;;
;;; c****d f****g
;;; **** ****
;;; **** ****
;;; **** e**** _
;;; ******** |
;;; ****** | h1
|
;;; ******** _|
;;; **** k****
;;; **** ****
;;; **** ****
a****l
;;;
|____| |___|
;;; w2 w3
;;;
;;;
(defun make-glyph-lower-case-x (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(width width)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (max 4 (round (* 0.9 width))))
(w2 (* 0.5 (- w1 (* 0.8 stroke-width))))
(w3 (* 1.3 stroke-width))
(h1 (* 1.0 stroke-width))
(pa (c 0 0))
(pb (c w2 (* 0.5 lower-case-ascent)))
(pc (c 0 lower-case-ascent))
(pd (+ pc w3))
(pe (c (* 0.5 w1) (+ (imagpart pb) (* 0.5 h1))))
(pf (c (- w1 w3) lower-case-ascent))
(pg (c w1 lower-case-ascent))
(ph (+ pb (- w1 (* 2 w2))))
(ppi (c w1 0))
(pj (c (- w1 w3) 0))
(pk (- pe (c 0 h1)))
(pl (c w3 0)))
(make-glyph
(list (mf pa -- pb -- pc -- pd -- pe -- pf --
pg -- ph -- ppi -- pj -- pk -- pl -- cycle))
#\x #\x)))))
;;;
;;; w1
;;; __________________
;;; | |
;;;
;;; w2
;;; __
;;; | |
;;;
e****f
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; ****g ****
;;; ********
;;; ******
;;; d****
;;; ****
;;; ****
;;; c ****j
;;; b******
;;; a****
;;; k
;;; |_|
;;; w3
;;;
;;; |______|
;;; w4
(defun make-glyph-lower-case-y (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(width width)
(stroke-height stroke-height)
(stroke-width stroke-width)
(descent descent))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (max 4 (round (* 0.9 width))))
(w2 (* 1.0 stroke-width))
(w3 (* 0.1 w1))
(w4 (* 0.5 (- w1 (* 0.9 stroke-width))))
(pa (c w3 (- descent)))
(pb (+ pa (c 0 stroke-height)))
(pc (+ pb (* 0.03 w4)))
(pd (c w4 0))
(pe (c 0 lower-case-ascent))
(pf (+ pe w2))
(pg (c (* 0.5 w1) (* 0.9 stroke-height)))
(ph (c (- w1 w2) lower-case-ascent))
(ppi (c w1 lower-case-ascent))
(pj (+ ppi (* 1.2 (- pd ph))))
(pk (- pc (c 0 stroke-height))))
(make-glyph
(list (mf pa -- pb -- pc right ++ pd -- pe -- pf -- pg -- ph --
ppi -- pj (direction (- pd ph)) ++ left pk -- cycle))
#\v #\v)))))
;;;
;;; w1
;;; _______________
;;; | |
;;;
e****************f
;;; d**********c*****g
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****h
;;; b***************i
a***************j
;;;
;;; |____|
;;; w2
;;;
;;;
(defun make-glyph-lower-case-z (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(width width)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (max 4 (round (* 0.9 width))))
(w2 (* 1.1 stroke-width))
(pa (c 0 0))
(pb (c 0 stroke-height))
(pc (c (- w1 w2) (- lower-case-ascent stroke-height)))
(pd (c 0 (- lower-case-ascent stroke-height)))
(pe (c 0 lower-case-ascent))
(pf (c w1 lower-case-ascent))
(pg (c w1 (- lower-case-ascent stroke-height)))
(ph (c w2 stroke-height))
(ppi (c w1 stroke-height))
(pj (c w1 0)))
(make-glyph
(list (mf pa -- pb -- pc -- pd -- pe -- pf -- pg --
ph -- ppi -- pj -- cycle))
#\z #\z)))))
;;; w2
;;; ___
;;; | |
;;; be cf
;;; *****
;;; *******
;;; *******
;;; *********
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** **** _
;;; **j***************k** |
;;; *i*****************l* |
;;; **** **** |
;;; **** **** |
;;; **** **** | h1
;;; **** **** |
;;; **** **** |
;;; **** **** |
;;; **** **** |
;;; **** **** -
;;; a d h g
;;; |____________________________|
;;; w1
;;;
;;;
;;; |__|
;;; w3
(defun make-glyph-upper-case-a (font)
(with-accessors ((ascent ascent)
(lower-case-ascent lower-case-ascent)
(upper-case-h-width upper-case-h-width)
(j-hook-start j-hook-start)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w2 (round (* 1.2 stroke-width)))
(w1 (let ((w (round (* 1.2 upper-case-h-width))))
(if (= (mod w2 2) (mod w 2)) w (1- w))))
(w3 (* 1.05 stroke-width))
(h1 (round (* 0.4 ascent)))
(xb (* 1/2 (- w1 w2)))
(xj (* (/ xb ascent) h1))
(xi (* (/ xb ascent) (- h1 stroke-height)))
(pa (c 0 0))
(pb (c xb ascent))
(pc (+ pb w3))
(pd (+ pa w3))
(pf (c (* 1/2 (+ w1 w2)) ascent))
(pe (- pf w3))
(pg (c w1 0))
(ph (- pg w3))
(ppi (c xi (- h1 stroke-height)))
(pj (c xj h1))
(pk (c (- w1 xj) h1))
(pl (c (- w1 xi) (- h1 stroke-height))))
(make-glyph
(list (mf pa -- pb -- pc -- pd -- cycle)
(mf pe -- pf -- pg -- ph -- cycle)
(mf ppi -- pj -- pk -- pl -- cycle))
#\l #\l)))))
;;;
;;;
;;; g h _
;;; *************** |
;;; ****************** |
;;; f e**** |
;;; **** |
;;; **** |
;;; d****j | h
;;; **** |
;;; **** |
;;; b c**** |
;;; ****************** |
;;; *************** -
;;; a k
;;; |_____________|
;;; w1
;;; |____________________|
;;; w2
;;;
;;;
(defun make-loop (font pa w1 w2 h)
(with-accessors ((stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((pb (+ pa (c 0 stroke-height)))
(pc (+ pb w1))
(pd (+ pa (c (- w2 stroke-width) (/ h 2))))
(pf (+ pa (c 0 (- h stroke-height))))
(pe (+ pf w1))
(pg (+ pa (c 0 h)))
(ph (+ pg w1))
(pj (+ pd stroke-width))
(pk (+ pa w1)))
(mf pa -- pb -- pc right ++ up pd ++ left pe -- pf --
pg -- ph right ++ down pj ++ left pk -- cycle)))))
;;; w2
;;; ______________
;;; | |
;;;
;;; **********
;;; ************
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** **** _
;;; ************* |
;;; *************** |
;;; **** **** |
;;; **** **** |
;;; **** **** |
;;; **** **** | h
;;; **** **** |
;;; **** **** |
;;; **** **** |
;;; *************** |
;;; ************* -
;;;
;;;
;;; |________________|
;;; w1
;;;
(defun make-glyph-upper-case-b (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.88 upper-case-h-width)))
(w2 (round (* 0.8 upper-case-h-width)))
(h upper-case-h-bar-position))
(make-glyph
(list (make-vertical-stroke font 0 ascent)
(make-loop font
(c stroke-width 0)
(* 0.5 w1)
w1
h)
(make-loop font
(c stroke-width (- h stroke-height))
(* 0.5 w2)
w2
(+ (- ascent h) stroke-height)))
#\l #\B)))))
;;;
;;; f
;;; *******
;;; ************
;;; **** e ****
;;; **** ***g
;;; **** ***
;;; **** **
;;; **** *
;;; **** h
;;; ****
;;; ****
;;; ****
;;; **** c _
;;; **** * |
;;; **** ** | h2
;;; **** *** -
;;; **** ***d |
;;; **** b **** | h1
;;; ************ |
;;; ******* -
;;; a
;;; |__________|
;;; w1
;;;
(defun make-glyph-upper-case-c (font)
(with-accessors ((ascent ascent)
(upper-case-o-width upper-case-o-width)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (if (oddp upper-case-o-width)
(+ 1/2 (floor (* 1/3 upper-case-o-width)))
(round (* 1/3 upper-case-o-width))))
(h1 (* 0.12 ascent))
(h2 (* 1.1 stroke-height))
(pa (c (* 1/2 upper-case-o-width) 0))
(pb (+ pa (c 0 stroke-height)))
(pc (c (+ (* 1/2 upper-case-o-width) w1) (+ h1 h2)))
(pd (- pc (c 0 h2)))
(pf (+ pa (c 0 ascent)))
(pe (- pf (c 0 stroke-height)))
(ph (c (realpart pc) (- ascent (imagpart pc))))
(pg (c (realpart pd) (- ascent (imagpart pd))))
(center (paths:make-point (* 1/2 upper-case-o-width)
(* 1/2 ascent))))
(make-glyph
(list (paths:path-rotate
(make-loop font pa 0 (* 1/2 upper-case-o-width) ascent)
pi
center)
(mf pa -- pb right ++ pc -- pd ++ left cycle)
(mf pe -- pf right ++ pg -- ph ++ left cycle))
#\l #\C)))))
;;;
;;;
;;;
;;; *************
;;; ***************
;;; **** *****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** *****
;;; ***************
;;; *************
;;; |________________|
;;; w1
;;;
(defun make-glyph-upper-case-d (font)
(with-accessors ((ascent ascent)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.71 ascent))))
(make-glyph
(list (make-vertical-stroke font 0 ascent)
(make-loop font (c stroke-height 0) (* 0.3 w1) w1 ascent))
#\l #\l)))))
;;; w1
;;; ____________________
;;; | |
;;;
;;; **********************
;;; **********************
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ***************
;;; ***************
;;; ****
;;; ****|_________|
;;; **** w2
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; *********************
;;; *********************
;;;
(defun make-glyph-upper-case-e (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.75 upper-case-h-width)))
(w2 (round (* 0.88 w1))))
(make-glyph
(list (make-vertical-stroke font 0 ascent)
(make-horizontal-stroke font 0 w1)
(make-horizontal-stroke
font (c 0 (- ascent stroke-height)) w1)
(make-horizontal-stroke
font (c 0 (- upper-case-h-bar-position stroke-height)) w2))
#\l #\E)))))
;;; w1
;;; ____________________
;;; | |
;;;
;;; **********************
;;; **********************
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ***************
;;; ***************
;;; ****
;;; ****|_________|
;;; **** w2
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
(defun make-glyph-upper-case-f (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.75 upper-case-h-width)))
(w2 (round (* 0.88 w1))))
(make-glyph
(list (make-vertical-stroke font 0 ascent)
(make-horizontal-stroke
font (c 0 (- ascent stroke-height)) w1)
(make-horizontal-stroke
font (c 0 (- upper-case-h-bar-position stroke-height)) w2))
#\l #\E)))))
;;;
;;; w2
;;; ________
;;; | |
;;;
;;;
;;; f
;;; *******
;;; ************
;;; **** e ****
;;; **** ***g
;;; **** ***
;;; **** **
;;; **** *
;;; **** h
;;; **** m n _
;;; **** ************* |
;;; **** ************* |
;;; **** l k**** _ |
;;; **** ***c | |
;;; **** **** | h2 | h3
;;; **** **** - |
* * * * | |
;;; **** b **** | h1 |
;;; ************ | |
;;; ******* - -
;;; a
;;; |__________|
;;; w1
;;;
(defun make-glyph-upper-case-g (font)
(with-accessors ((ascent ascent)
(upper-case-o-width upper-case-o-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (if (oddp upper-case-o-width)
(+ 1/2 (floor (* 0.37 upper-case-o-width)))
(round (* 0.37 upper-case-o-width))))
(w2 (* 0.43 upper-case-o-width))
(h1 (* 0.06 ascent))
(h2 (* 1.1 stroke-height))
(h3 upper-case-h-bar-position)
(pa (c (* 1/2 upper-case-o-width) 0))
(pb (+ pa (c 0 stroke-height)))
(pc (c (+ (* 1/2 upper-case-o-width) w1) (+ h1 h2)))
(pd (- pc (c 0 h2)))
(pf (+ pa (c 0 ascent)))
(pe (- pf (c 0 stroke-height)))
(ph (c (realpart pc) (- ascent (imagpart pc))))
(pg (c (realpart pd) (- ascent (imagpart pd))))
(pj (- pd stroke-width))
(pk (c (- (+ (* 1/2 upper-case-o-width) w1) stroke-width)
(- h3 stroke-height)))
(pl (c w2 (- h3 stroke-height)))
(pm (c w2 h3))
(pn (c (+ (* 1/2 upper-case-o-width) w1) h3))
(center (paths:make-point (* 1/2 upper-case-o-width)
(* 1/2 ascent))))
(make-glyph
(list (paths:path-rotate
(make-loop font pa 0 (* 1/2 upper-case-o-width) ascent)
pi
center)
(mf pa -- pb right ++ pc -- pd ++ left cycle)
(mf pe -- pf right ++ pg -- ph ++ left cycle)
(mf pj -- pk -- pl -- pm -- pn -- pd -- cycle))
#\l #\C)))))
;;;
;;;
;;;
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **********************
;;; **********************
;;; ****a ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;;
(defun make-glyph-upper-case-h (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w upper-case-h-width)
(pa (c stroke-width (- upper-case-h-bar-position stroke-height))))
(make-glyph
(list (make-vertical-stroke font (c 0 0) ascent)
(make-vertical-stroke font (c (- w stroke-width) 0) ascent)
(make-horizontal-stroke font pa (- w (* 2 stroke-width))))
#\l #\l)))))
(defun make-glyph-upper-case-i (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w (max 1 (round (* ascent 0.1))))
(h (- ascent (* 2 stroke-height))))
(make-glyph
(list (make-horizontal-stroke font (c 0 0) (+ (* 2 w) stroke-width))
(make-horizontal-stroke font (c 0 (- ascent stroke-height))
(+ (* 2 w) stroke-width))
(make-vertical-stroke font (c w stroke-height) h))
#\I #\I)))))
;;;
;;;
;;; w2
;;; __
;;; | |g h
;;; ************
;;; ************
;;; f e****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; d****i -
;;; **** |
;;; b c***** | h1
;;; *********** |
;;; ********* _|
;;; a j
;;; |______________|
;;; w1
;;;
(defun make-glyph-upper-case-j (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(j-hook-start j-hook-start)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (max 3 (round (* 0.60 upper-case-h-width))))
(w2 (max 1 (round (* 0.250 upper-case-h-width))))
(h1 j-hook-start)
(pa (c 0 0))
(pb (+ pa (c 0 stroke-height)))
(pc (c (* 0.3 w1) stroke-height))
(pd (c (- w1 stroke-width) h1))
(pe (c (- w1 stroke-width) (- ascent stroke-height)))
(pf (c w2 (- ascent stroke-height)))
(pg (c w2 ascent))
(ph (c w1 ascent))
(ppi (+ pd stroke-width))
(pj (- pc (c 0 stroke-height))))
(make-glyph
(list (mf pa -- pb right ++ pc right ++ up pd -- pe -- pf --
pg -- ph -- ppi down ++ left pj -- cycle))
#\J #\l)))))
;;; w2
;;; ___
;;; | |
;;; c d
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; ****b**f* _
;;; ********* |
;;; ********** |
;;; ***** **** |
;;; ****a **** |
;;; **** **** |
;;; **** **** | h1
;;; **** **** |
;;; **** **** |
;;; **** **** |
;;; **** **** |
;;; **** **** _|
;;; e g
;;;
;;; |__________________|
;;; w1
;;;
(defun make-glyph-upper-case-k (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.9 upper-case-h-width)))
(w2 (* 1.1 stroke-width))
(h1 (round (* 1.0 lower-case-ascent)))
(pb (c stroke-width h1))
(pa (- pb (c 0 (* 1.3 stroke-height))))
(pd (c w1 ascent))
(pc (- pd w2))
(pf (+ pb w2))
(pg (c w1 0))
(pe (- pg w2)))
(make-glyph
(list (make-vertical-stroke font (c 0 0) ascent)
(mf pa -- pb -- pc -- pd -- cycle)
(mf pb -- pf -- pg -- pe -- cycle))
#\l #\K)))))
(defun make-glyph-upper-case-l (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w (round (* 0.71 upper-case-h-width))))
(make-glyph
(list (make-vertical-stroke font (c 0 0) ascent)
(make-horizontal-stroke font (c 0 0) w))
#\l #\L)))))
;;;
;;; w1
;;; ____________________
;;; | |
;;; a b e f
;;; **** ****
;;; ***** *****
;;; ****** ******
;;; ******* *******
;;; ******** ********
;;; **** **** **** ****
;;; **** **** **** ****
;;; **** ******** ****
;;; **** ****** ****
;;; **** **** ****
;;; **** c d ****
;;; **** |__| ****
;;; **** w2 ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;;
;;;
(defun make-glyph-upper-case-m (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 1.2 upper-case-h-width)))
(w2 (* 1.0 stroke-width))
(pa (c 0 ascent))
(pb (+ pa w2))
(pc (c (* 0.5 (- w1 w2)) (- lower-case-ascent (* 1.3 stroke-height))))
(pd (+ pc w2))
(pe (c (- w1 w2) ascent))
(pf (+ pe w2)))
(make-glyph
(list (make-vertical-stroke font (c 0 0) ascent)
(make-vertical-stroke font (c (- w1 stroke-width) 0) ascent)
(mf pa -- pb -- pd -- pc -- cycle)
(mf pc -- pe -- pf -- pd -- cycle))
#\l #\l)))))
;;;
;;; w1
;;; ____________________
;;; | |
;;; a b
;;; **** ****
;;; ***** ****
;;; ****** ****
;;; ******* ****
;;; ******** ****
;;; **** **** ****
;;; **** **** ****
;;; **** **** ****
;;; **** **** ****
;;; **** **** ****
;;; **** **** ****
;;; **** **** ****
;;; **** **** ****
;;; **** **** ****
;;; **** ********
;;; **** *******
;;; **** ******
;;; **** *****
;;; **** ****
;;; d c
;;; |__|
;;; w2
;;;
(defun make-glyph-upper-case-n (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 1.0 upper-case-h-width)))
(w2 (* 1.0 stroke-width))
(pa (c 0 ascent))
(pb (+ pa w2))
(pc (c w1 0))
(pd (- pc w2)))
(make-glyph
(list (make-vertical-stroke font (c 0 0) ascent)
(make-vertical-stroke font (c (- w1 stroke-width) 0) ascent)
(mf pa -- pb -- pc -- pd -- cycle))
#\l #\l)))))
;;;
;;;
;;;
;;; *******
;;; ************
;;; ***** *****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; ***** *****
;;; ************
;;; *******
;;; a
;;;
(defun make-glyph-upper-case-o (font)
(with-accessors ((ascent ascent)
(upper-case-o-width upper-case-o-width))
font
(flet ((c (x y) (complex x y)))
(let* ((pa (c (* 1/2 upper-case-o-width) 0))
(center (paths:make-point (* 1/2 upper-case-o-width)
(* 1/2 ascent))))
(make-glyph
(list (paths:path-rotate
(make-loop font pa 0 (* 1/2 upper-case-o-width) ascent)
pi
center)
(make-loop font pa 0 (* 1/2 upper-case-o-width) ascent))
#\l #\l)))))
;;; w1
;;; ______________
;;; | |
;;;
;;; **********
;;; ************
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** **** _
;;; ************* |
;;; *********** |
;;; **** |
;;; **** |
;;; **** |
;;; **** | h
;;; **** |
;;; **** |
;;; **** _|
;;;
;;;
;;;
(defun make-glyph-upper-case-p (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.83 upper-case-h-width)))
(h (* 0.84 upper-case-h-bar-position)))
(make-glyph
(list (make-vertical-stroke font 0 ascent)
(make-loop font
(c 0 (- h stroke-height))
(* 0.55 w1)
w1
(+ (- ascent h) stroke-height)))
#\l #\P)))))
;;;
;;;
;;;
;;; *******
;;; ************
;;; ***** *****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** b ****
;;; **** * **** -
;;; **** ****** |
;;; ***** ***** | h1
;;; **************** |
;;; ******* **** -
;;; a **** | h2
;;; |__________| **** -
;;; w2 d c
;;;
;;; |________________|____|
;;; w1 w3
(defun make-glyph-upper-case-q (font)
(with-accessors ((ascent ascent)
(upper-case-o-width upper-case-o-width)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (* 0.9 upper-case-o-width))
(w2 (* 0.5 upper-case-o-width))
(w3 (* 0.15 ascent))
(h1 (* 0.2 ascent))
(h2 (* 0.1 ascent))
(pa (c (* 1/2 upper-case-o-width) 0))
(pb (c w2 h1))
(pd (c w1 (- h2)))
(pc (+ pd w3))
(center (paths:make-point (* 1/2 upper-case-o-width)
(* 1/2 ascent))))
(make-glyph
(list (paths:path-rotate
(make-loop font pa 0 (* 1/2 upper-case-o-width) ascent)
pi
center)
(make-loop font pa 0 (* 1/2 upper-case-o-width) ascent)
(mf pb -- pc -- pd -- cycle))
#\l #\Q)))))
;;; w1
;;; ______________
;;; | |
;;;
;;; **********
;;; ************
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** **** _
;;; ************* |
;;; *****b**c** |
;;; **** **** |
;;; **** **** |
;;; **** **** |
;;; **** **** | h
;;; **** **** |
;;; **** **** |
;;; **** **** _|
;;; a d
;;;
;;; |____| |__|
;;; w3 w2
;;;
;;; |______________|
;;; w4
;;;
(defun make-glyph-upper-case-r (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.83 upper-case-h-width)))
(w2 (* 1.2 stroke-width))
(w3 (* 0.6 w1))
(w4 (* 0.90 upper-case-h-width))
(h upper-case-h-bar-position)
(pa (c (- w4 w2) 0))
(pb (c w3 (- h (* 0.5 stroke-height))))
(pc (+ pb w2))
(pd (+ pa w2)))
(make-glyph
(list (make-vertical-stroke font 0 ascent)
(make-loop font
(c 0 (- h stroke-height))
(* 0.6 w1)
w1
(+ (- ascent h) stroke-height))
(mf pa -- pb -- pc -- pd -- cycle))
#\l #\R)))))
;;;
;;; w2
;;; _______________
;;; | |
;;; g _
;;; ********* | h1
;;; ************* |
;;; **** k **h -|
;;; **** ** | h2
;;; f****l * -
;;; **** j
;;; **** m
;;; ***********
;;; **********
;;; b e ****
;;; * ****
* * d****n
;;; a** c ****
;;; ****************
;;; **********
;;; o
;;; |_________________|
;;; w1
;;;
(defun make-glyph-upper-case-s (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.87 upper-case-h-width)))
(w2 (+ (* 2 (round (* 0.37 upper-case-h-width)))
(if (oddp w1) 1 0)))
(h1 (* 0.06 ascent))
(h2 (* 1.1 stroke-height))
(pa (c 0 h1))
(pb (+ pa (c 0 h2)))
(xo (* 1/2 w1))
(po (c xo 0))
(pc (+ po (c 0 stroke-height)))
(pm (c w1 (* 0.25 ascent)))
(pd (- pm stroke-width))
(ym (+ (* 1/2 (+ ascent stroke-height))
(if (= (mod ascent 2) (mod stroke-height 2)) 0 1/2)))
(pm (c xo ym))
(pe (- pm (c 0 stroke-height)))
(pf (c (* 1/2 (- w1 w2)) (* 0.75 ascent)))
(pg (c xo ascent))
(ph (c (* 1/2 (+ w1 w2)) (- ascent h1)))
(pj (- ph (c 0 h2)))
(pk (- pg (c 0 stroke-height)))
(pl (+ pf stroke-width))
(pn (+ pd stroke-width)))
(make-glyph
(list (mf pa -- pb ++ right pc ++ up pd ++ left pe ++
up pf ++ right pg ++ ph -- pj ++ left pk ++
down pl ++ right pm ++ down pn ++ left po ++ cycle))
#\S #\S)))))
;;;
;;; w
;;; ____________________
;;; | |
;;;
;;; **********************
;;; **********************
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;;
;;;
;;;
(defun make-glyph-upper-case-t (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w (- (* 2 (round (* 0.5 upper-case-h-width)))
(if (oddp stroke-width) 1 0))))
(make-glyph (list (make-vertical-stroke
font (c (* 1/2 (- w stroke-width)) 0) ascent)
(make-horizontal-stroke
font (c 0 (- ascent stroke-height)) w))
#\T #\T)))))
;;;
;;;
;;;
;;;
;;;
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
b****c e****f -
;;; **** d **** |
;;; ************ | h
;;; ******* -
;;; a
;;;
;;; |________________|
;;; w
;;;
;;;
(defun make-glyph-upper-case-u (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w (round (* 1.0 upper-case-h-width)))
(h (* 0.29 ascent))
(pa (c (* 1/2 w) 0))
(pb (c 0 h))
(pc (+ pb stroke-width))
(pd (+ pa (c 0 stroke-height)))
(pf (c w h))
(pe (- pf stroke-width)))
(make-glyph (list (make-vertical-stroke font pb (- ascent h))
(make-vertical-stroke font pe (- ascent h))
(mf pa left ++ pb -- pc down ++ right
pd ++ up pe -- pf down ++ left cycle))
#\l #\l)))))
;;; w1
;;; _____________________________
;;; | |
;;; w3
;;; ___
;;; | |
;;; a d h g
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; *********
;;; *******
;;; *******
;;; *****
;;; be cf
;;;
|___|
;;; w2
;;;
;;;
;;;
(defun make-glyph-upper-case-v (font)
(with-accessors ((ascent ascent)
(lower-case-ascent lower-case-ascent)
(upper-case-h-width upper-case-h-width)
(j-hook-start j-hook-start)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w2 (round (* 1.2 stroke-width)))
(w1 (let ((w (round (* 1.2 upper-case-h-width))))
(if (= (mod w2 2) (mod w 2)) w (1- w))))
(w3 (* 1.05 stroke-width))
(xb (* 1/2 (- w1 w2)))
(pa (c 0 ascent))
(pb (c xb 0))
(pc (+ pb w3))
(pd (+ pa w3))
(pf (c (* 1/2 (+ w1 w2)) 0))
(pe (- pf w3))
(pg (c w1 ascent))
(ph (- pg w3)))
(make-glyph (list (mf pa -- pd -- pc -- pb -- cycle)
(mf ph -- pg -- pf -- pe -- cycle))
#\V #\V)))))
;;; w1
;;; _______________________________________________
;;; | |
;;; w3
;;; ___
;;; | |
;;; a b o p
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** fj gk ****
;;; **** ***** **** -
;;; **** ******* **** |
;;; **** ******* **** |
;;; **** ********* **** |
;;; **** **** **** **** |
;;; **** **** **** **** |
;;; **** **** **** **** |
;;; **** **** **** **** |
;;; **** **** **** **** | h
;;; **** **** **** **** |
;;; **** **** **** **** |
;;; **** **** **** **** |
;;; ********* ********* |
;;; ******* ******* |
;;; ******* ******* |
;;; ***** ***** -
;;; de ch mn lq
;;;
|___|
;;; w2
;;;
;;;
;;; We try to maintain the same slope of all the strokes.
;;;
(defun make-glyph-upper-case-w (font)
(with-accessors ((ascent ascent)
(lower-case-ascent lower-case-ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 1.5 upper-case-h-width)))
(w2 (round (* 1.2 stroke-width)))
(h (round (* 1.5 upper-case-h-bar-position)))
(w3 (* 1.05 stroke-width))
(xd (/ (- w1 w2) 2 (+ 1 (/ h ascent))))
(pa (c 0 ascent))
(pb (+ pa w3))
(pd (c xd 0))
(pc (+ pd w3))
(ph (+ pd w2))
(pe (- ph w3))
(pf (c (* 1/2 (- w1 w2)) h))
(pg (+ pf w3))
(pk (+ pf w2))
(pj (- pk w3))
(pq (c (- w1 xd) 0))
(pn (- pq w3))
(pm (- pq w2))
(pl (+ pm w3))
(pp (c w1 ascent))
(po (- pp w3)))
(make-glyph (list (mf pa -- pb -- pc -- pd -- cycle)
(mf pe -- pf -- pg -- ph -- cycle)
(mf pj -- pk -- pl -- pm -- cycle)
(mf pn -- po -- pp -- pq -- cycle))
#\V #\V)))))
;;;
;;; w1
;;; ______________
;;; | |
;;;
;;;
;;; c****d f****g
;;; **** ****
;;; **** ****
;;; **** e**** _
;;; ******** |
;;; ****** | h1
|
;;; ******** _|
;;; **** k****
;;; **** ****
;;; **** ****
a****l
;;;
|____| |___|
;;; w2 w3
;;;
;;;
(defun make-glyph-upper-case-x (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 1.1 upper-case-h-width)))
(w2 (* 0.5 (- w1 (* 0.8 stroke-width))))
(w3 (* 1.1 stroke-width))
(h1 (* 1.0 stroke-width))
(pa (c 0 0))
(pb (c w2 (* 0.5 ascent)))
(pc (c 0 ascent))
(pd (+ pc w3))
(pe (c (* 0.5 w1) (+ (imagpart pb) (* 0.5 h1))))
(pf (c (- w1 w3) ascent))
(pg (c w1 ascent))
(ph (+ pb (- w1 (* 2 w2))))
(ppi (c w1 0))
(pj (c (- w1 w3) 0))
(pk (- pe (c 0 h1)))
(pl (c w3 0)))
(make-glyph
(list (mf pa -- pb -- pc -- pd -- pe -- pf --
pg -- ph -- ppi -- pj -- pk -- pl -- cycle))
#\x #\x)))))
;;;
;;;
;;; w1
;;; __________________
;;; | |
;;;
;;; w2
;;; __
;;; | |
;;; b c e f
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; ********
;;; ******
;;; a****d -
;;; **** |
;;; **** |
;;; **** |
;;; **** | h
;;; **** |
;;; **** |
;;; **** |
;;; **** -
;;;
(defun make-glyph-upper-case-y (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (+ (* 2 (round (* 0.5 upper-case-h-width)))
(if (oddp stroke-width) 1 0)))
(w2 (* 1.1 stroke-width))
(h (round (* 0.6 upper-case-h-bar-position)))
(xa (* 1/2 (- w1 stroke-width)))
(pa (c xa h))
(pb (c 0 ascent))
(pc (+ pb w2))
(pd (+ pa stroke-width))
(pe (c (- w1 w2) ascent))
(pf (+ pe w2)))
(make-glyph (list (make-vertical-stroke
font (c (* 1/2 (- w1 w2)) 0) h)
(mf pa -- pb -- pc -- pd -- cycle)
(mf pa -- pe -- pf -- pd -- cycle))
#\Y #\Y)))))
;;;
;;;
;;;
;;; w1
;;; ___________________
;;; | |
;;;
;;; *********************
* * * * * * * * * * * * * * * *
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; a****d****************
;;; *********************
;;;
;;;
|___|
;;; w2
;;;
;;;
(defun make-glyph-upper-case-z (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.9 upper-case-h-width)))
(w2 (* 1.1 stroke-width))
(pa (c 0 stroke-height))
(pc (c w1 (- ascent stroke-height)))
(pb (- pc w2))
(pd (+ pa w2)))
(make-glyph (list (make-horizontal-stroke
font (c 0 0) w1)
(make-horizontal-stroke
font (c 0 (- ascent stroke-height)) w1)
(mf pa -- pb -- pc -- pd -- cycle))
#\Z #\Z)))))
;;;
;;;
;;; c
;;; ****
;;; b********d
;;; **********
a**********e
;;; h********f
;;; ****
;;; g
(defun make-disk (center radius)
(flet ((c (x y) (complex x y)))
(let* ((pa (- center radius))
(pe (+ center radius))
(pc (+ center (c 0 radius)))
(pg (- center (c 0 radius)))
(pb (+ center (/ (c (- radius) radius) (sqrt 2))))
(pd (+ center (/ (c radius radius) (sqrt 2))))
(pf (+ center (/ (c radius (- radius)) (sqrt 2))))
(ph (+ center (/ (c (- radius) (- radius)) (sqrt 2)))))
(mf pa up ++ pb ++ pc right ++ pd ++ pe down ++
pf ++ pg left ++ ph ++ cycle))))
(defun make-glyph-period (font)
(with-accessors ((stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(make-glyph (list (make-disk
(* 1 (c stroke-width stroke-width)) (* 1 stroke-width)))
#\. #\.))))
;;; w1
;;; _____
;;; | |
;;;
;;; a b
;;; ********
;;; ******** _
;;; ******** |
;;; ******* |
;;; ****** |
;;; ***** | h1
;;; **** |
;;; **** |
;;; c**** _|
;;;
(defun make-comma-hook (font)
(with-accessors ((stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (* 1.5 stroke-width))
(h1 (* 2.0 stroke-height))
(cw1 (ceiling w1))
(pa (c (+ cw1 (* 0.7 stroke-width)) stroke-width))
(pb (c (+ cw1 (* 2 stroke-width)) stroke-width))
(pc (c (- cw1 w1) (- h1))))
(mf pa -- pb down ++ left pc & pc ++ up cycle)))))
(defun make-glyph-comma (font)
(with-accessors ((stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (* 2.0 stroke-width))
(cw1 (ceiling w1)))
(make-glyph (list (make-disk
(c (+ stroke-width cw1) stroke-width)
stroke-width)
(make-comma-hook font))
#\, #\.)))))
(defun make-glyph-colon (font)
(with-accessors ((stroke-width stroke-width)
(lower-case-ascent lower-case-ascent))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 stroke-width)
(h1 (max 5 lower-case-ascent)))
(make-glyph (list (make-disk (c w1 w1) w1)
(make-disk (c w1 (- h1 w1)) w1))
#\: #\:)))))
(defun make-glyph-semicolon (font)
(with-accessors ((stroke-width stroke-width)
(lower-case-ascent lower-case-ascent))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (* 2.0 stroke-width))
(cw1 (ceiling w1))
(h1 (max 5 lower-case-ascent)))
(make-glyph (list (make-disk
(c (+ stroke-width cw1) stroke-width)
stroke-width)
(make-disk
(c (+ stroke-width cw1)
(- h1 stroke-width))
stroke-width)
(make-comma-hook font))
#\, #\.)))))
;;;
;;;
;;;
;;;
;;; **** -
;;; ******** |
;;; ********** |
;;; c*****a****d |
;;; ********** |
;;; ********** |
;;; ********** |
;;; ********** |
;;; ******** |
;;; ******** |
;;; ******** |
;;; ******** |
;;; ******** |
;;; ******** |
;;; ****** |
;;; ****** |
;;; ****** |
;;; ****** |
;;; ****** |
;;; ****** |
;;; **** |
;;; **** | h
;;; **** |
;;; **** |
;;; **** |
;;; **** |
;;; ** |
;;; ** |
;;; ** |
;;; ** |
;;; ** |
;;; *b |
;;; |
;;; **** |
;;; ******** |
;;; ********** |
;;; ********** |
;;; ******** |
;;; **** -
;;;
(defun make-glyph-exclamation-mark (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h (round (* 1.0 ascent)))
(pa (c (* 1/2 stroke-width) (- h stroke-width)))
(pb (c (* 1/2 stroke-width) (* 2 stroke-width)))
(pc (- pa (* 1/2 stroke-width)))
(pd (+ pa (* 1/2 stroke-width))))
(make-glyph (list (make-disk
(* 1/2 (c stroke-width stroke-width))
(* 1/2 stroke-width))
(make-disk pa (* 1/2 stroke-width))
(mf pc -- pd down ++ pb & pb ++ up cycle))
#\. #\.)))))
;;; Make this similar to the exclamation mark.
(defun make-quote (font xpos)
(with-accessors ((ascent ascent)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (round (* 1.0 ascent)))
(h2 (* 0.3 ascent))
(pa (c (+ xpos (* 1/2 stroke-width)) (- h1 stroke-width)))
(pb (c (+ xpos (* 1/2 stroke-width)) (- ascent h2)))
(pc (- pa (* 1/2 stroke-width)))
(pd (+ pa (* 1/2 stroke-width))))
(list (make-disk pa (* 1/2 stroke-width))
(mf pc -- pd down ++ pb & pb ++ up cycle))))))
(defun make-glyph-double-quote (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width))
font
(let ((w (max (* 2 stroke-width) (round (* 0.2 ascent)))))
(make-glyph (append (make-quote font 0)
(make-quote font w))
#\" #\"))))
;;; Make a "slash", i.e., a slanted line the height of the ascent
;;; of the font.
;;;
;;; x1
;;; ___
;;; | |
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; |__|
;;; w
;;;
;;; |____________|
;;;
;;; x2
(defun make-slash (font x1 x2)
(with-accessors ((ascent ascent)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((angle (atan (- x2 x1 stroke-width) ascent))
(w (/ stroke-width (cos angle)))
(pa (c x1 ascent))
(pb (+ pa w))
(pc (c x2 0))
(pd (- pc w)))
(mf pa -- pb -- pc -- pd -- cycle)))))
;;;
;;;
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **************************
;;; **************************
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** **** _
;;; ************************** |
;;; ************************** |
;;; **** **** |
;;; **** **** |
;;; **** **** | h1
;;; **** **** |
;;; **** **** |
;;; **** **** _|
;;; |_|
;;; w2
;;;
;;; |____|
;;; w4
;;;
;;; |___________|
;;; w3
;;;
;;; |__________________________|
;;; w1
(defun make-glyph-hash (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.6 ascent)))
(w2 (* 0.05 ascent))
(w3 (round (* 0.3 ascent)))
(w4 (* 1.2 stroke-width)) ; roughly
(h1 (round (* 0.40 ascent))))
(make-glyph (list (make-horizontal-stroke
font
(c 0 (- h1 stroke-height))
w1)
(make-horizontal-stroke
font
(c 0 (- ascent h1))
w1)
(make-slash font (- w1 w3 w4) (+ w2 w4))
(make-slash font (- w1 w2 w4) (+ w3 w4)))
#\# #\#)))))
;;;
;;;
;;;
;;; ******
;;; **********
;;; **** ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; *****
;;; ********
;;; **** **** ****
;;; **** **** ****
;;; **** **** ****
;;; **** *** ****
;;; **** *******
;;; **** *****
;;; **** *****
;;; **** ******
;;; **** ********
;;; **** **** ****
;;; ********* ****
;;; ****** ****
;;;
;;;
;;;
;;;
;;;
;;;
;;;
;;;
;;;
;;;
;;;
;;;
;;;
;;;
;;;
;;;
;;; w
;;; _____________
;;; | |
;;; f
;;; ********
;;; *****c******
;;; **** ****
;;; e****d b****g -
;;; **** |
;;; **** |
;;; **** |
;;; **** |
;;; a****h - |
;;; **** | |
;;; **** | | h2
;;; **** | |
;;; **** | |
;;; **** | h1 |
;;; | |
;;; ** | |
;;; **** | |
;;; ** - -
;;;
;;;
;;;
(defun make-glyph-question-mark (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(upper-case-h-width upper-case-h-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h0 (* 2.0 stroke-width))
(h1 (* 0.4 ascent))
(h2 (* 0.75 ascent))
(w (+ (* 2 (round (* 0.25 upper-case-h-width)))
(if (oddp stroke-width) 1 0)))
(pa (c (* 1/2 (- w stroke-width)) h1))
(pb (c (- w stroke-width) h2))
(pf (c (* 1/2 w) ascent))
(pc (- pf (c 0 stroke-height)))
(pe (c 0 h2))
(pd (+ pe stroke-width))
(pg (+ pb stroke-width))
(ph (+ pa stroke-width)))
(make-glyph (list (make-disk
(* 1/2 (c w stroke-width))
(* 1/2 stroke-width))
(make-vertical-stroke
font
(c (* 1/2 (- w stroke-width)) h0)
(- h1 h0))
(mf pa up ++ pb up ++ pc left ++ down pd --
pe up ++ pf right ++ pg down ++ down ph -- cycle))
#\? #\?)))))
(defun make-glyph-slash (font)
(with-accessors ((ascent ascent)
(slash-width slash-width)
(stroke-width stroke-width))
font
(make-glyph (list (make-slash font
(- slash-width (* 1.3 stroke-width))
(* 1.3 stroke-width)))
#\/ #\/)))
;;;
;;; _ b _
;;; | **** |
;;; | ***** |
;;; | ****** |h2
;;; | ******* _|
;;; h1| ****c***
;;; | **** ****
;;; |_ **** ****
;;; a d ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; |____|
;;; w1
;;;
;;;
(defun make-glyph-digit-1 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (round (* 0.3 ascent)))
(h2 (* 1.2 stroke-height))
(w1 (* 0.15 ascent))
(pa (c (- (ceiling w1) w1) (- ascent h1)))
(pb (c (ceiling w1) ascent))
(pc (c (ceiling w1) (- ascent h2)))
(pd (+ pa (* 1.0 stroke-width))))
(make-glyph (list (make-vertical-stroke font (ceiling w1) ascent)
(mf pa -- pb -- pc -- pd -- cycle))
#\1 #\l)))))
;;; w1
;;; ____
;;; | |
;;;
_ g _
;;; | **** |
;;; h1| ****d*** |
;;; | **** **** | h2
;;; |_ f****e **** _|
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; b****j -
;;; ****k l |
;;; ************ | h3
;;; ************ -
;;; a m
;;;
;;;
;;;
(defun make-glyph-digit-2 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (round (* 0.3 ascent)))
(h2 (round (* 0.25 ascent)))
(h3 (* 0.15 ascent))
(w0 digit-width)
(w1 (* 1/2 digit-width))
(pa (c 0 0))
(pb (c 0 h3))
(pc (c (- w0 stroke-width) (- ascent h2)))
(pd (c w1 (- ascent stroke-height)))
(pe (c stroke-width (- ascent h1)))
(pf (c 0 (- ascent h1)))
(pg (c w1 ascent))
(ph (+ pc stroke-width))
(pj (+ pb stroke-width))
(pk (c stroke-width stroke-height))
(pl (c w0 stroke-height))
(pm (c w0 0)))
(make-glyph (list (mf pa -- pb up ++ pc up ++ pd left ++ down pe --
pf up ++ pg right ++ ph down ++ down pj -- pk --
pl -- pm -- cycle))
#\2 #\2)))))
;;; m _
;;; ***** |
;;; ********* | h3
;;; **** j **** _|
l****k h****n
;;; g ****
;;; -w1--****p
;;; f****
c * * * *
;;; | **** e****q _
;;; h1| **** d **** |
;;; | ********* | h2
;;; |_ ***** _|
;;; a
;;; |____|
;;; w2
(defun make-glyph-digit-3 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (round (* 0.3 ascent)))
(h2 (* 0.3 ascent))
(h3 (* 0.25 ascent))
(w0 digit-width)
(w1 (round (* 0.4 w0)))
(w2 (* 1/2 w0))
(pa (c w2 0))
(pb (c 0 h1))
(pc (+ pb stroke-width))
(pd (+ pa (c 0 stroke-height)))
(pe (c (- w0 stroke-width) h2))
(pf (c w1 (- (* 0.55 ascent) (* 1/2 stroke-height))))
(pg (+ pf (c 0 stroke-height)))
(ph (c (- w0 stroke-width) (- ascent h3)))
(pj (c w2 (- ascent stroke-height)))
(pk (c stroke-width (- ascent h1)))
(pl (c 0 (- ascent h1)))
(pm (c w2 ascent))
(pn (+ ph stroke-width))
(pp (c (+ w1 stroke-width) (* 0.55 ascent)))
(pq (+ pe stroke-width)))
(make-glyph (list (mf pa left ++ up pb -- pc down ++ pd right ++
pe up ++ pf -- pg ++ up ph ++ left pj ++
down pk -- pl up ++ right pm ++ down pn ++
left pp & pp right ++ down pq ++ left cycle))
#\3 #\3)))))
;;;
;;; b
;;; ****
;;; *****
;;; ******
;;; *******
;;; ****c***
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; ****d **** e _
;;; aa*************** |
;;; ***************f |
;;; a **** |
;;; **** |
;;; **** | h1
;;; **** |
;;; **** |
;;; **** |
;;; **** |
;;; **** _|
;;; ****
;;; |_______| |_|
;;;
;;; w1 w2
;;;
(defun make-glyph-digit-4 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (round (* 0.4 ascent)))
(w0 digit-width)
(w1 (* 0.6 w0))
(w2 (round (* 0.2 w0)))
(pa (c (- (ceiling w1) w1) (- h1 stroke-height)))
(paa (+ pa (c 0 stroke-height)))
(pb (c (ceiling w1) ascent))
(pc (c (ceiling w1) (- ascent (* 1.6 stroke-height))))
(pd (+ paa stroke-width))
(pe (c (+ (ceiling w1) stroke-width w2) h1))
(pf (- pe (c 0 stroke-height))))
(make-glyph (list (mf pa -- paa -- pb -- pc -- pd -- pe -- pf -- cycle)
(make-vertical-stroke font (c (ceiling w1) 0) ascent))
#\4 #\4)))))
;;;
;;; _
;;; | ****************
;;; | ****************
;;; | ****
;;; | ****
;;; h4| ****
;;; | ****
;;; | ****
;;; | **** j _
;;; | **** **** |
;;; | ****h ******** |
;;; | ******* f **** |
;;; |_ ***** **** |
;;; g **** | _
|________| e****k |h2 |
;;; _ w2 **** | |
* * * | |
;;; | **** **** | |
;;; h1| **** **** | | h3
;;; | **** d **** | |
;;; | ********* | |
;;; |_ ***** _| _|
;;; a
;;; |_______|
;;; w1
;;;
(defun make-glyph-digit-5 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (round (* 0.25 ascent)))
(h2 (round (* 0.65 ascent)))
(h3 (* 1/2 h2))
(h4 (round (* 0.55 ascent)))
(w0 digit-width)
(w1 (* 0.5 w0))
(w2 (* 0.5 w0))
(pa (c w1 0))
(pb (c 0 h1))
(pc (+ pb stroke-width))
(pd (+ pa (c 0 stroke-height)))
(pe (c (- digit-width stroke-width) h3))
(pf (c w2 (- h2 stroke-height)))
(pg (c stroke-width (- ascent h4)))
(ph (+ pg (c 0 (* 0.8 stroke-height))))
(pj (+ pf (c 0 stroke-height)))
(pk (+ pe stroke-width)))
(make-glyph (list (mf pa left ++ up pb -- pc down ++ pd right ++
pe up ++ pf left ++ pg -- ph ++ right pj ++
down pk ++ left cycle)
(make-vertical-stroke
font (c 0 (- ascent h4)) h4)
(make-horizontal-stroke
font
(c stroke-width (- ascent stroke-height))
(round (* 0.9 (- w0 stroke-width)))))
#\5 #\5)))))
;;; w1
;;; ________
;;; | |
;;; d _
;;; ******* |
;;; *********** |
;;; **** g **** | h4
;;; **** **** |
_ |
;;; ****
;;; **** p _
;;; **** ***** |
;;; ****o********** |
;;; ******** m **** |
;;; - ****n **** |
;;; | - b****j l****q - |
;;; | | **** **** | | h1
;;; | | **** **** | |
| * * * * k * * * * |h2 |
;;; | | ********** | |
;;; |_ |_ ****** _| _|
;;; a
;;;
;;;
;;;
;;;
(defun make-glyph-digit-6 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (round (* 0.65 ascent)))
(h2 (* 0.32 ascent))
(h3 (* 0.3 ascent))
(h4 (* 0.25 ascent))
(h5 (* 0.45 ascent))
(w0 digit-width)
(w1 (* 0.5 w0))
(pa (c w1 0))
(pb (c 0 h3))
(pc (c 0 (- ascent h3)))
(pd (c w1 ascent))
(pe (c w0 (- ascent h4)))
(pf (- pe stroke-width))
(pg (- pd (c 0 stroke-height)))
(ph (+ pc stroke-width))
(pj (+ pb stroke-width))
(pk (+ pa (c 0 stroke-height)))
(pl (c (- w0 stroke-width) h2))
(pm (c w1 (- h1 stroke-height)))
(pn (c stroke-width h5))
(po (+ pn (c 0 stroke-height)))
(pp (+ pm (c 0 stroke-height)))
(pq (+ pl stroke-width)))
(make-glyph (list (mf pa left ++ up pb -- pc up ++ right pd ++
down pe -- pf up ++ pg left ++ down ph --
pj down ++ right pk ++ up pl ++ left pm ++
pn -- po ++ right pp ++ down pq ++ left cycle))
#\6 #\6)))))
;;;
;;;
;;;
;;;
;;; ********************
;;; ********************
;;; b****c
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; a d
;;; |_____|
;;; w1
;;;
(defun make-glyph-digit-7 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w0 digit-width)
(w1 (* 0.3 w0))
(pa (c w1 0))
(pb (c (- w0 stroke-width) (- ascent stroke-height)))
(pc (+ pb stroke-width))
(pd (+ pa stroke-width)))
(make-glyph (list (mf pa -- pb -- pc -- pd -- cycle)
(make-horizontal-stroke
font (c 0 (- ascent stroke-height)) digit-width))
#\7 #\7)))))
;;; w1
;;; _______
;;; | |
;;; k _
;;; ******* |
;;; *********** | h2
;;; **** n **** |
j****p
;;; **** ****
;;; **** c **** _
;;; *********** |
;;; *********** |
;;; **** g **** |
;;; **** **** |
;;; **** **** | h1
;;; - b****h f****d |
;;; | **** **** |
;;; h3 | **** e **** |
;;; | ************ |
;;; |_ ******** _|
;;; a
;;;
(defun make-glyph-digit-8 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w0 digit-width)
(ww1 (* 1/2 (round (* 0.8 w0))))
(w1 (+ ww1 (if (integerp ww1) 0 1/2)))
(h1 (* 0.60 ascent))
(h2 (* 0.25 ascent))
(h3 (* 0.30 ascent))
(pa (c (* 1/2 w0) 0))
(pb (c 0 h3))
(pc (c (* 1/2 w0) h1))
(pd (c w0 h3))
(pe (+ pa (c 0 stroke-height)))
(pf (- pd stroke-width))
(pg (- pc (c 0 stroke-height)))
(ph (+ pb stroke-width))
(pj (c (- (* 1/2 w0) w1) (- ascent h2)))
(pk (c (* 1/2 w0) ascent))
(pl (c (+ (* 1/2 w0) w1) (- ascent h2)))
(pm (- pl stroke-width))
(pn (- pk (c 0 stroke-height)))
(pp (+ pj stroke-width)))
(make-glyph (list (mf pa left ++ pb up ++ pc right ++
pd down ++ left cycle)
(mf pe right ++ pf up ++ pg left ++
ph down ++ right cycle)
(mf pg left ++ pj up ++ pk right ++
pl down ++ left cycle)
(mf pc right ++ pm up ++ pn left ++
pp down ++ right cycle))
#\8 #\8)))))
;;; w1
;;; ________
;;; | |
;;; _ o _ _ _
;;; | ******* | | |
;;; | *********** | | |
;;; h2| **** g **** | h3 | |
;;; | **** **** | | |
;;; - n****h f****p _| | | h1
;;; **** **** _| |
;;; **** k**** |
;;; **** j ****** |
;;; - *********l**** |
;;; | ***** **** _|
;;; | m ****
;;; | e****q
| - * * * *
;;; | | **** ****
;;;h5| h4 | **** d ****
;;; | | **********
;;; |_ |_ ******
;;; a
;;;
;;;
;;;
;;;
(defun make-glyph-digit-9 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (round (* 0.65 ascent)))
(h2 (* 0.32 ascent))
(h3 (* 0.3 ascent))
(h4 (* 0.25 ascent))
(h5 (* 0.45 ascent))
(w0 digit-width)
(w1 (* 0.5 w0))
(pa (c w1 0))
(pb (c 0 h4))
(pc (+ pb stroke-width))
(pd (+ pa (c 0 stroke-height)))
(pe (c (- w0 stroke-width) h3))
(pf (c (- w0 stroke-width) (- ascent h3)))
(pg (c w1 (- ascent stroke-height)))
(ph (c stroke-width (- ascent h2)))
(pj (c w1 (+ (- ascent h1) stroke-height)))
(pk (c (- w0 stroke-width) (+ h5 stroke-height)))
(pl (- pk (c 0 stroke-height)))
(pm (- pj (c 0 stroke-height)))
(pn (c 0 (- ascent h2)))
(po (+ pg (c 0 stroke-height)))
(pp (+ pf stroke-width))
(pq (+ pe stroke-width)))
(make-glyph (list (mf pa left ++ up pb -- pc down ++ right pd ++
up pe -- pf up ++ pg left ++ down ph ++
pj right ++ pk -- pl ++ left pm ++
up pn ++ right po ++ down pp -- pq down ++ left cycle))
#\9 #\9)))))
;;;
;;;
;;;
;;;
;;; d
;;; ***********
;;; ***************
;;; **** k ****
c****l j****e
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
;;; **** ****
b****m h****f -
;;; **** g **** |
;;; *************** | h1
;;; *********** _|
;;; a
;;;
;;;
;;;
(defun make-glyph-digit-0 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w0 digit-width)
(w1 (* 1/2 w0))
(h1 (round (* 0.3 ascent)))
(pa (c w1 0))
(pb (c 0 h1))
(pc (c 0 (- ascent h1)))
(pd (c w1 ascent))
(pe (c w0 (- ascent h1)))
(pf (c w0 h1))
(pg (+ pa (c 0 stroke-height)))
(ph (- pf stroke-width))
(pj (- pe stroke-width))
(pk (- pd (c 0 stroke-height)))
(pl (+ pc stroke-width))
(pm (+ pb stroke-width)))
(make-glyph (list (mf pa left ++ up pb -- pc up ++
pd right ++ down pe -- pf down ++ left cycle)
(mf pg right ++ up ph -- pj up ++
left pk ++ down pl -- pm down ++ right cycle))
#\l #\l)))))
(defun make-glyph-left-bracket (font)
(with-accessors ((bracket-width bracket-width)
(bracket-descent bracket-descent)
(bracket-ascent bracket-ascent)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(make-glyph (list (make-vertical-stroke font (c 0 (- bracket-descent)) (+ bracket-ascent bracket-descent))
(make-horizontal-stroke font (c 0 (- bracket-descent)) bracket-width)
(make-horizontal-stroke font (c 0 (- bracket-ascent stroke-height)) bracket-width))
#\l #\[))))
(defun make-glyph-backslash (font)
(with-accessors ((ascent ascent)
(slash-width slash-width))
font
(make-glyph (list (make-slash font 0 slash-width))
#\/ #\/)))
(defun make-glyph-right-bracket (font)
(with-accessors ((bracket-width bracket-width)
(bracket-descent bracket-descent)
(bracket-ascent bracket-ascent)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(make-glyph (list (make-vertical-stroke font (c (- bracket-width stroke-width) (- bracket-descent)) (+ bracket-ascent bracket-descent))
(make-horizontal-stroke font (c 0 (- bracket-descent)) bracket-width)
(make-horizontal-stroke font (c 0 (- bracket-ascent stroke-height)) bracket-width))
#\] #\l))))
;;;
;;; w2
;;; ___
;;; | |
;;; g
;;; *******h
;;; *******
;;; f****j
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; e****k -
;;; **** |
;;; d****l | h2
;;; **** |
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; b****n _
;;; ******* |
;;; *******o _| h1
;;; a
;;; |_|
;;; w1
;;;
;;;
(defun make-glyph-left-brace (font)
(with-accessors ((ascent ascent)
(bracket-width bracket-width)
(bracket-descent bracket-descent)
(bracket-ascent bracket-ascent)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (* 0.1 ascent))
(ww1 (ceiling w1))
(w2 (* 0.6 bracket-width))
(h0 (+ bracket-ascent bracket-descent))
(h1 (* 0.26 ascent))
(h2 (* 0.4 ascent))
(pa (c (+ ww1 w2) (- bracket-descent)))
(pb (c ww1 (- h1 bracket-descent)))
(pc (c ww1 (- (* 0.5 (- h0 h2)) bracket-descent)))
(pd (c (- ww1 w1) (- (* 0.5 h0) bracket-descent)))
(pe (c ww1 (- bracket-ascent (* 0.5 (- h0 h2)))))
(pf (c ww1 (- bracket-ascent h1)))
(pg (+ pa (c 0 h0)))
(ph (c (+ ww1 bracket-width) bracket-ascent))
(pj (+ pf stroke-width))
(pk (+ pe stroke-width))
(pl (+ pd (* 0.7 stroke-width)))
(pm (+ pc stroke-width))
(pn (+ pb stroke-width))
(po (c (+ ww1 bracket-width) (- bracket-descent))))
(make-glyph (list (mf pa left ++ up pb ++ up pc ++ pd &
pd ++ up pe ++ up pf ++ right pg ++
ph & ph ++ down pj ++ down pk ++
pl & pl ++ down pm ++ down pn ++
po & po ++ left cycle))
#\{ #\{)))))
;;;
;;; w2
;;; ___
;;; | |
;;; g
;;; f*******
;;; *******
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; d****j -
;;; **** |
;;; c****k | h2
;;; **** |
;;; b****l -
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; ****
;;; a****m _
;;; ******* |
;;; o******* _| h1
;;; n
;;; |_|
;;; w1
;;;
;;;
(defun make-glyph-right-brace (font)
(with-accessors ((ascent ascent)
(bracket-width bracket-width)
(bracket-descent bracket-descent)
(bracket-ascent bracket-ascent)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (* 0.1 ascent))
(w2 (* 0.6 bracket-width))
(h0 (+ bracket-ascent bracket-descent))
(h1 (* 0.26 ascent))
(h2 (* 0.4 ascent))
(pa (c (- bracket-width stroke-width) (- h1 bracket-descent)))
(pb (c (- bracket-width stroke-width) (- (* 0.5 (- h0 h2)) bracket-descent)))
(pc (c (- (+ bracket-width w1) (* 0.7 stroke-width)) (- (* 0.5 h0) bracket-descent)))
(pd (c (- bracket-width stroke-width) (- bracket-ascent (* 0.5 (- h0 h2)))))
(pe (c (- bracket-width stroke-width) (- bracket-ascent h1)))
(pf (c 0 bracket-ascent))
(pg (c (- bracket-width w2) bracket-ascent))
(ph (+ pe stroke-width))
(pj (+ pd stroke-width))
(pk (c (+ bracket-width w1) (- (* 0.5 h0) bracket-descent)))
(pl (+ pb stroke-width))
(pm (+ pa stroke-width))
(pn (c (- bracket-width w2) (- bracket-descent)))
(po (c 0 (- bracket-descent))))
(make-glyph (list (mf pa up ++ pb up ++ pc & pc ++ up pd ++
up pe ++ pf & pf ++ right pg ++ down ph ++
down pj ++ pk & pk ++ down pl ++ down pm ++
left pn +++ po & po ++ up cycle))
#\} #\})))))
(defun add-glyph (character glyphs glyph)
(setf (gethash character glyphs) glyph))
(defun add-kerning-info (font left-char right-char delta)
(setf (gethash (cons left-char right-char) (kerning-info font))
delta))
(defun compute-kerning-info (font)
(with-accessors ((stroke-width stroke-width)
(width width))
font
(add-kerning-info font #\i #\o (round (* 0.2 stroke-width)))
(add-kerning-info font #\o #\i (round (* 0.2 stroke-width)))
(add-kerning-info font #\o #\o (round (* 0.3 stroke-width)))
(add-kerning-info font #\x #\o (round (* 1.5 stroke-width)))
(add-kerning-info font #\c #\o (round (* 1.0 stroke-width)))
(add-kerning-info font #\o #\x (round (* 0.5 stroke-width)))
(add-kerning-info font #\f #\o (round (* 1.6 stroke-width)))
(add-kerning-info font #\o #\f (round (* 1.0 stroke-width)))
(add-kerning-info font #\f #\l (round (* 1.0 stroke-width)))
;; move the j closer to anything without descent
(add-kerning-info font #\i #\j (round (* 2.0 stroke-width)))
(add-kerning-info font #\l #\j (round (* 2.0 stroke-width)))
(add-kerning-info font #\o #\j (round (* 2.0 stroke-width)))
(add-kerning-info font #\c #\j (round (* 2.0 stroke-width)))
(add-kerning-info font #\x #\j (round (* 2.0 stroke-width)))
(add-kerning-info font #\f #\j (round (* 2.0 stroke-width)))
;; things that follow an `r' can sometimes move closer
(add-kerning-info font #\r #\o
(round (* (if (< width 6) 0 1.0) stroke-width)))))
(defun make-font (size resolution)
(let* ((pixel-size (round (/ (* size resolution) 72)))
(ascent (max 4 pixel-size))
(stroke-width (max 1 (round (* ascent 0.08))))
(font (make-instance 'font
:ascent ascent
:lower-case-ascent (max 2 (round (* ascent 0.6)))
:stroke-width stroke-width
:stroke-height (max 1 (round (* ascent 0.08)))
:j-width (* 3.0 stroke-width)
:j-hook-start (* 0.4 ascent)
:j-hook-extreme (* 2.0 stroke-width)
:slash-width (round (* 0.5 ascent))
2 * stroke - height
:bracket-width (max 2 (round (* ascent 0.2)))
:bracket-ascent (round (* ascent 1.0))
:descent (max 2 (round (* ascent 0.25)))
:width (max 3 (round (* ascent 0.50)))
:upper-case-h-width (round (* ascent 0.71))
:upper-case-o-width (round (* ascent 0.88))
:digit-width (round (* ascent 0.4))
:upper-case-h-bar-position (round (* ascent 0.56))))
(glyphs (glyphs font)))
(compute-kerning-info font)
;; Make a glyph for the space character
(let ((mask (make-array (list 1 (width font))
:element-type 'double-float
:initial-element 0d0)))
(add-glyph #\Space glyphs
(make-instance 'glyph
:x-offset 0 :y-offset -1
:left-shape #\l :right-shape #\l
:mask mask)))
;; Make a default glyph
(let ((mask (make-array (list 1 (width font))
:element-type 'double-float
:initial-element 05.d0)))
(add-glyph 'default glyphs
(make-instance 'glyph
:x-offset 0 :y-offset -1
:left-shape #\l :right-shape #\l
:mask mask)))
(add-glyph #\a glyphs (make-glyph-lower-case-a font))
(add-glyph #\b glyphs (make-glyph-lower-case-b font))
(add-glyph #\c glyphs (make-glyph-lower-case-c font))
(add-glyph #\d glyphs (make-glyph-lower-case-d font))
(add-glyph #\e glyphs (make-glyph-lower-case-e font))
(add-glyph #\f glyphs (make-glyph-lower-case-f font))
(add-glyph #\g glyphs (make-glyph-lower-case-g font))
(add-glyph #\h glyphs (make-glyph-lower-case-h font))
(add-glyph #\i glyphs (make-glyph-lower-case-i font))
(add-glyph #\j glyphs (make-glyph-lower-case-j font))
(add-glyph #\k glyphs (make-glyph-lower-case-k font))
(add-glyph #\l glyphs (make-glyph-lower-case-l font))
(add-glyph #\m glyphs (make-glyph-lower-case-m font))
(add-glyph #\n glyphs (make-glyph-lower-case-n font))
(add-glyph #\o glyphs (make-glyph-lower-case-o font))
(add-glyph #\p glyphs (make-glyph-lower-case-p font))
(add-glyph #\q glyphs (make-glyph-lower-case-q font))
(add-glyph #\r glyphs (make-glyph-lower-case-r font))
(add-glyph #\s glyphs (make-glyph-lower-case-s font))
(add-glyph #\t glyphs (make-glyph-lower-case-t font))
(add-glyph #\u glyphs (make-glyph-lower-case-u font))
(add-glyph #\v glyphs (make-glyph-lower-case-v font))
(add-glyph #\w glyphs (make-glyph-lower-case-w font))
(add-glyph #\x glyphs (make-glyph-lower-case-x font))
(add-glyph #\y glyphs (make-glyph-lower-case-y font))
(add-glyph #\z glyphs (make-glyph-lower-case-z font))
(add-glyph #\A glyphs (make-glyph-upper-case-a font))
(add-glyph #\B glyphs (make-glyph-upper-case-b font))
(add-glyph #\C glyphs (make-glyph-upper-case-c font))
(add-glyph #\D glyphs (make-glyph-upper-case-d font))
(add-glyph #\E glyphs (make-glyph-upper-case-e font))
(add-glyph #\F glyphs (make-glyph-upper-case-f font))
(add-glyph #\G glyphs (make-glyph-upper-case-g font))
(add-glyph #\H glyphs (make-glyph-upper-case-h font))
(add-glyph #\I glyphs (make-glyph-upper-case-i font))
(add-glyph #\J glyphs (make-glyph-upper-case-j font))
(add-glyph #\K glyphs (make-glyph-upper-case-k font))
(add-glyph #\L glyphs (make-glyph-upper-case-l font))
(add-glyph #\M glyphs (make-glyph-upper-case-m font))
(add-glyph #\N glyphs (make-glyph-upper-case-n font))
(add-glyph #\O glyphs (make-glyph-upper-case-o font))
(add-glyph #\P glyphs (make-glyph-upper-case-p font))
(add-glyph #\Q glyphs (make-glyph-upper-case-q font))
(add-glyph #\R glyphs (make-glyph-upper-case-r font))
(add-glyph #\S glyphs (make-glyph-upper-case-s font))
(add-glyph #\T glyphs (make-glyph-upper-case-t font))
(add-glyph #\U glyphs (make-glyph-upper-case-u font))
(add-glyph #\V glyphs (make-glyph-upper-case-v font))
(add-glyph #\W glyphs (make-glyph-upper-case-w font))
(add-glyph #\X glyphs (make-glyph-upper-case-x font))
(add-glyph #\Y glyphs (make-glyph-upper-case-y font))
(add-glyph #\Z glyphs (make-glyph-upper-case-z font))
(add-glyph #\! glyphs (make-glyph-exclamation-mark font))
(add-glyph #\" glyphs (make-glyph-double-quote font))
(add-glyph #\# glyphs (make-glyph-hash font))
(add-glyph #\. glyphs (make-glyph-period font))
(add-glyph #\, glyphs (make-glyph-comma font))
(add-glyph #\: glyphs (make-glyph-colon font))
(add-glyph #\; glyphs (make-glyph-semicolon font))
(add-glyph #\? glyphs (make-glyph-question-mark font))
(add-glyph #\/ glyphs (make-glyph-slash font))
(add-glyph #\1 glyphs (make-glyph-digit-1 font))
(add-glyph #\2 glyphs (make-glyph-digit-2 font))
(add-glyph #\3 glyphs (make-glyph-digit-3 font))
(add-glyph #\4 glyphs (make-glyph-digit-4 font))
(add-glyph #\5 glyphs (make-glyph-digit-5 font))
(add-glyph #\6 glyphs (make-glyph-digit-6 font))
(add-glyph #\7 glyphs (make-glyph-digit-7 font))
(add-glyph #\8 glyphs (make-glyph-digit-8 font))
(add-glyph #\9 glyphs (make-glyph-digit-9 font))
(add-glyph #\0 glyphs (make-glyph-digit-0 font))
(add-glyph #\[ glyphs (make-glyph-left-bracket font))
(add-glyph #\\ glyphs (make-glyph-backslash font))
(add-glyph #\] glyphs (make-glyph-right-bracket font))
(add-glyph #\{ glyphs (make-glyph-left-brace font))
(add-glyph #\} glyphs (make-glyph-right-brace font))
font))
(defun find-glyph (font char)
(or (gethash char (glyphs font))
(gethash 'default (glyphs font))))
(defun kerning (font left-glyph right-glyph)
(or (gethash (cons (right-shape left-glyph)
(left-shape right-glyph))
(kerning-info font))
0))
(defun draw-text (text font x y glyph-mask-fun)
(flet ((show-glyph (glyph x y)
(let ((mask (mask glyph))
(x-offset (x-offset glyph))
(y-offset (y-offset glyph)))
(funcall glyph-mask-fun mask (+ x x-offset) (+ y y-offset)))))
(show-glyph (find-glyph font (aref text 0)) x y)
(loop for i from 1 below (length text)
do (let* ((previous-glyph (find-glyph font (aref text (1- i))))
(this-glyph (find-glyph font (aref text i)))
(advance (if (null previous-glyph)
(width font)
(+ (x-offset previous-glyph)
(array-dimension (mask previous-glyph) 1)
(* 2 (stroke-width font)))))
(kerning (if (or (null previous-glyph)
(null this-glyph))
0
(kerning font previous-glyph this-glyph))))
(incf x (- advance kerning))
(unless (null this-glyph)
(show-glyph this-glyph x y))))))
| null | https://raw.githubusercontent.com/robert-strandh/CLIMatis/4949ddcc46d3f81596f956d12f64035e04589b29/Fonts/Camfer/camfer.lisp | lisp | FIXME: the bends in the `f', the `t', and the `j' should look the
same, but currently the code is duplicated. Improve by making
the width and the start of the bend font-wide parameters.
The horizontal distance from the right edge of the `j'
to the min-point of the hook
The vertical distance beteween the bottom of the j and
the point where the hook starts.
Basic character elements
|
**
**
|
If the stroke width is odd, then the x coordinate of the
center point will be in the middle of a pixel, and if is
even, then the x coordinate will be an integer. A similar
thing holds for the stroke height and the y coordinate.
|
*******
*************
**** | ****
**** 6 ****
**** ****
**** ****
**** ****
**** ****
**** 4 ****
**** | ****
*************
*******
|
0
| |
| |
| |
| |
| |
| |
| | 3
| | /
| |******
| ***|* | ***** /
| | **** |
| | **** |
| | **** | bend-start
| | **** |
| | **** |
|____| **** /
/ \
0 1
\_______________/
|
width
1 2
\ /
++++
++++
++++
++++
++++
++++
++++
++++
++++
++++
++++
++++
++++
++++
++++
++++
++++
++++
++++
++++
++++
++++
/ \
0 3
1 2
*****************************************
*****************************************
0 3
The characters
|
*********
*************
11 1 9-****- 14 - |
\ **** | |
************* - | |
*************** | | | h4
**** 5 **** | | h3 |
**** 7 **** | | | |
*************** | h1 | | |
******** **** _ _| _| _|
| | \
*******
*************
**** ****
**** */ -2
**** /
**** /
**** 0-*
**** \
**** \
**** *\ -1 \
**** **** |
************* | h
******* /
*******
*************
**** ****
****/ \****
*****************
*****************
*****************- 2 -
****\ | / |
**** **** \ | m
************* | h |
******* / _|
w2
________
| |
w3
_____
| |
| /
****
*******\
**** \ 8
**** |
**** |
**** |
**** |
\****/ |
/****\14 | h
****|_| |
**** w1 |
**** |
**** |
**** |
**** |
**** |
**** |
**** |
**** |
**** _|
/ \
0 1
| /
******* ****
***************
**** *****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** *****
***************
------ *******-****---- - -
**** | h1 |
5 \ | *** | h2
************ |
|
|_|
w2
|______|
w1
**
****
\ /
****
****
****
****
****
w1 ****
_____ ****
| |****
****
****
0-**** -
**** |
**** |
**** | h
\ \ ****
*******
****
/ |
|__|
w2
1 2
\ /
****
****
****
****
****
****
****
****
**** 4 5
**** \ /
**** ****
**** ****
**** ****
**********- 6 -
| **** **** | h2
h1 | **** **** |
| **** **** |
|_ **** **** _|
/ \ / \
0 11 8 7
|_______________|
w
average stroke for angled lines
---- /
| | *****
| |**********
| ***** \
0 -|*** |
| / |
|3 |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
----
|
*******
************
**** | ****
5 -****- 10
****** |
***************
****************
| ******
3 -****- 12 -
1 -* 2 **** |
**** | **** |
- 0 -****************** | h2
h1 | ************** |
|_ ******* _|
|
5 6
\ /
****
****
****
****
****
****
****
****
\****/
/****\
****
****
****
****
****
****
**** | /
*******
****
| \
w1
_____________
| |
w3
__
| |
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
*******
*******
*****
w2
guess and adjust y coordinate
w1
______________________
| |
w3
__
| |
**** ****
**** ****
**** e f ****
**** **** ****
**** **** ****
**** ****** ****
****d***l***g****
******* *******
******* *******
***** *****
a *****m k*****j
w4 w2
w1
______________
| |
c****d f****g
**** ****
**** ****
**** e**** _
******** |
****** | h1
******** _|
**** k****
**** ****
**** ****
w2 w3
w1
__________________
| |
w2
__
| |
**** ****
**** ****
**** ****
**** ****
****g ****
********
******
d****
****
****
c ****j
b******
a****
k
|_|
w3
|______|
w4
w1
_______________
| |
d**********c*****g
****
****
****
****
****
****
****
****
****
****h
b***************i
|____|
w2
w2
___
| |
be cf
*****
*******
*******
*********
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** **** _
**j***************k** |
*i*****************l* |
**** **** |
**** **** |
**** **** | h1
**** **** |
**** **** |
**** **** |
**** **** |
**** **** -
a d h g
|____________________________|
w1
|__|
w3
g h _
*************** |
****************** |
f e**** |
**** |
**** |
d****j | h
**** |
**** |
b c**** |
****************** |
*************** -
a k
|_____________|
w1
|____________________|
w2
w2
______________
| |
**********
************
**** ****
**** ****
**** ****
**** ****
**** ****
**** **** _
************* |
*************** |
**** **** |
**** **** |
**** **** |
**** **** | h
**** **** |
**** **** |
**** **** |
*************** |
************* -
|________________|
w1
f
*******
************
**** e ****
**** ***g
**** ***
**** **
**** *
**** h
****
****
****
**** c _
**** * |
**** ** | h2
**** *** -
**** ***d |
**** b **** | h1
************ |
******* -
a
|__________|
w1
*************
***************
**** *****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** *****
***************
*************
|________________|
w1
w1
____________________
| |
**********************
**********************
****
****
****
****
****
****
****
****
***************
***************
****
****|_________|
**** w2
****
****
****
****
****
*********************
*********************
w1
____________________
| |
**********************
**********************
****
****
****
****
****
****
****
****
***************
***************
****
****|_________|
**** w2
****
****
****
****
****
****
****
w2
________
| |
f
*******
************
**** e ****
**** ***g
**** ***
**** **
**** *
**** h
**** m n _
**** ************* |
**** ************* |
**** l k**** _ |
**** ***c | |
**** **** | h2 | h3
**** **** - |
**** b **** | h1 |
************ | |
******* - -
a
|__________|
w1
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**********************
**********************
****a ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
w2
__
| |g h
************
************
f e****
****
****
****
****
****
****
****
****
****
****
****
****
d****i -
**** |
b c***** | h1
*********** |
********* _|
a j
|______________|
w1
w2
___
| |
c d
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
****b**f* _
********* |
********** |
***** **** |
****a **** |
**** **** |
**** **** | h1
**** **** |
**** **** |
**** **** |
**** **** |
**** **** _|
e g
|__________________|
w1
w1
____________________
| |
a b e f
**** ****
***** *****
****** ******
******* *******
******** ********
**** **** **** ****
**** **** **** ****
**** ******** ****
**** ****** ****
**** **** ****
**** c d ****
**** |__| ****
**** w2 ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
w1
____________________
| |
a b
**** ****
***** ****
****** ****
******* ****
******** ****
**** **** ****
**** **** ****
**** **** ****
**** **** ****
**** **** ****
**** **** ****
**** **** ****
**** **** ****
**** **** ****
**** ********
**** *******
**** ******
**** *****
**** ****
d c
|__|
w2
*******
************
***** *****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
***** *****
************
*******
a
w1
______________
| |
**********
************
**** ****
**** ****
**** ****
**** ****
**** ****
**** **** _
************* |
*********** |
**** |
**** |
**** |
**** | h
**** |
**** |
**** _|
*******
************
***** *****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** b ****
**** * **** -
**** ****** |
***** ***** | h1
**************** |
******* **** -
a **** | h2
|__________| **** -
w2 d c
|________________|____|
w1 w3
w1
______________
| |
**********
************
**** ****
**** ****
**** ****
**** ****
**** ****
**** **** _
************* |
*****b**c** |
**** **** |
**** **** |
**** **** |
**** **** | h
**** **** |
**** **** |
**** **** _|
a d
|____| |__|
w3 w2
|______________|
w4
w2
_______________
| |
g _
********* | h1
************* |
**** k **h -|
**** ** | h2
f****l * -
**** j
**** m
***********
**********
b e ****
* ****
a** c ****
****************
**********
o
|_________________|
w1
w
____________________
| |
**********************
**********************
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** d **** |
************ | h
******* -
a
|________________|
w
w1
_____________________________
| |
w3
___
| |
a d h g
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
*********
*******
*******
*****
be cf
w2
w1
_______________________________________________
| |
w3
___
| |
a b o p
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** fj gk ****
**** ***** **** -
**** ******* **** |
**** ******* **** |
**** ********* **** |
**** **** **** **** |
**** **** **** **** |
**** **** **** **** |
**** **** **** **** |
**** **** **** **** | h
**** **** **** **** |
**** **** **** **** |
**** **** **** **** |
********* ********* |
******* ******* |
******* ******* |
***** ***** -
de ch mn lq
w2
We try to maintain the same slope of all the strokes.
w1
______________
| |
c****d f****g
**** ****
**** ****
**** e**** _
******** |
****** | h1
******** _|
**** k****
**** ****
**** ****
w2 w3
w1
__________________
| |
w2
__
| |
b c e f
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
********
******
a****d -
**** |
**** |
**** |
**** | h
**** |
**** |
**** |
**** -
w1
___________________
| |
*********************
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
a****d****************
*********************
w2
c
****
b********d
**********
h********f
****
g
w1
_____
| |
a b
********
******** _
******** |
******* |
****** |
***** | h1
**** |
**** |
c**** _|
**** -
******** |
********** |
c*****a****d |
********** |
********** |
********** |
********** |
******** |
******** |
******** |
******** |
******** |
******** |
****** |
****** |
****** |
****** |
****** |
****** |
**** |
**** | h
**** |
**** |
**** |
**** |
** |
** |
** |
** |
** |
*b |
|
**** |
******** |
********** |
********** |
******** |
**** -
Make this similar to the exclamation mark.
Make a "slash", i.e., a slanted line the height of the ascent
of the font.
x1
___
| |
****
****
****
****
****
****
|__|
w
|____________|
x2
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**************************
**************************
**** ****
**** ****
**** ****
**** **** _
************************** |
************************** |
**** **** |
**** **** |
**** **** | h1
**** **** |
**** **** |
**** **** _|
|_|
w2
|____|
w4
|___________|
w3
|__________________________|
w1
roughly
******
**********
**** ****
****
****
****
****
****
****
*****
********
**** **** ****
**** **** ****
**** **** ****
**** *** ****
**** *******
**** *****
**** *****
**** ******
**** ********
**** **** ****
********* ****
****** ****
w
_____________
| |
f
********
*****c******
**** ****
e****d b****g -
**** |
**** |
**** |
**** |
a****h - |
**** | |
**** | | h2
**** | |
**** | |
**** | h1 |
| |
** | |
**** | |
** - -
_ b _
| **** |
| ***** |
| ****** |h2
| ******* _|
h1| ****c***
| **** ****
|_ **** ****
a d ****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
|____|
w1
w1
____
| |
| **** |
h1| ****d*** |
| **** **** | h2
|_ f****e **** _|
****
****
****
****
****
****
****
b****j -
****k l |
************ | h3
************ -
a m
m _
***** |
********* | h3
**** j **** _|
g ****
-w1--****p
f****
| **** e****q _
h1| **** d **** |
| ********* | h2
|_ ***** _|
a
|____|
w2
b
****
*****
******
*******
****c***
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
****d **** e _
aa*************** |
***************f |
a **** |
**** |
**** | h1
**** |
**** |
**** |
**** |
**** _|
****
|_______| |_|
w1 w2
_
| ****************
| ****************
| ****
| ****
h4| ****
| ****
| ****
| **** j _
| **** **** |
| ****h ******** |
| ******* f **** |
|_ ***** **** |
g **** | _
_ w2 **** | |
| **** **** | |
h1| **** **** | | h3
| **** d **** | |
| ********* | |
|_ ***** _| _|
a
|_______|
w1
w1
________
| |
d _
******* |
*********** |
**** g **** | h4
**** **** |
****
**** p _
**** ***** |
****o********** |
******** m **** |
- ****n **** |
| - b****j l****q - |
| | **** **** | | h1
| | **** **** | |
| | ********** | |
|_ |_ ****** _| _|
a
********************
********************
b****c
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
****
a d
|_____|
w1
w1
_______
| |
k _
******* |
*********** | h2
**** n **** |
**** ****
**** c **** _
*********** |
*********** |
**** g **** |
**** **** |
**** **** | h1
- b****h f****d |
| **** **** |
h3 | **** e **** |
| ************ |
|_ ******** _|
a
w1
________
| |
_ o _ _ _
| ******* | | |
| *********** | | |
h2| **** g **** | h3 | |
| **** **** | | |
- n****h f****p _| | | h1
**** **** _| |
**** k**** |
**** j ****** |
- *********l**** |
| ***** **** _|
| m ****
| e****q
| | **** ****
h5| h4 | **** d ****
| | **********
|_ |_ ******
a
d
***********
***************
**** k ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** ****
**** g **** |
*************** | h1
*********** _|
a
w2
___
| |
g
*******h
*******
f****j
****
****
****
****
****
****
****
****
****
e****k -
**** |
d****l | h2
**** |
****
****
****
****
****
****
****
****
****
b****n _
******* |
*******o _| h1
a
|_|
w1
w2
___
| |
g
f*******
*******
****
****
****
****
****
****
****
****
****
d****j -
**** |
c****k | h2
**** |
b****l -
****
****
****
****
****
****
****
****
****
a****m _
******* |
o******* _| h1
n
|_|
w1
move the j closer to anything without descent
things that follow an `r' can sometimes move closer
Make a glyph for the space character
Make a default glyph
glyphs (make-glyph-semicolon font)) |
(in-package #:camfer)
(defgeneric ascent (font))
(defgeneric descent (font))
(defgeneric width (font))
(defclass font ()
((%ascent :initarg :ascent :reader ascent)
(%lower-case-ascent :initarg :lower-case-ascent :reader lower-case-ascent)
(%stroke-width :initarg :stroke-width :reader stroke-width)
(%stroke-height :initarg :stroke-height :reader stroke-height)
(%upper-case-h-width :initarg :upper-case-h-width :reader upper-case-h-width)
(%upper-case-o-width :initarg :upper-case-o-width :reader upper-case-o-width)
(%digit-width :initarg :digit-width :reader digit-width)
(%upper-case-h-bar-position :initarg :upper-case-h-bar-position
:reader upper-case-h-bar-position)
(%width :initarg :width :reader width)
(%descent :initarg :descent :reader descent)
(%j-width :initarg :j-width :reader j-width)
(%j-hook-extreme :initarg :j-hook-extreme :reader j-hook-extreme)
(%j-hook-start :initarg :j-hook-start :reader j-hook-start)
(%slash-width :initarg :slash-width :reader slash-width)
(%bracket-descent :initarg :bracket-descent :reader bracket-descent)
(%bracket-width :initarg :bracket-width :reader bracket-width)
(%bracket-ascent :initarg :bracket-ascent :reader bracket-ascent)
(%kerning-info :initform (make-hash-table :test #'equal) :reader kerning-info)
(%glyphs :initform (make-hash-table) :reader glyphs)))
(defclass glyph ()
((%x-offset :initarg :x-offset :reader x-offset)
(%y-offset :initarg :y-offset :reader y-offset)
(%left-shape :initarg :left-shape :reader left-shape)
(%right-shape :initarg :right-shape :reader right-shape)
(%mask :initarg :mask :reader mask)))
(defun make-glyph (paths left-shape right-shape)
(let ((x-min most-positive-fixnum)
(y-min most-positive-fixnum)
(x-max most-negative-fixnum)
(y-max most-negative-fixnum))
(flet ((convert-path-to-knots (path)
(let* ((dpath (paths:make-discrete-path path))
(iterator (paths:path-iterator dpath)))
(paths:path-iterator-reset iterator)
(loop with end = nil
collect (multiple-value-bind (interpolation knot end-p)
(paths:path-iterator-next iterator)
(declare (ignore interpolation))
(setf end end-p)
knot)
until end)))
(determine-min-max (x y alpha)
(declare (ignore alpha))
(setf x-min (min x-min x)
y-min (min y-min y)
x-max (max x-max x)
y-max (max y-max y))))
(let ((state (aa:make-state))
(knot-paths (mapcar #'convert-path-to-knots paths)))
(loop for path in knot-paths
do (loop for (p1 p2) on path
until (null p2)
do (aa:line-f state
(paths:point-x p1) (paths:point-y p1)
(paths:point-x p2) (paths:point-y p2))))
(aa:cells-sweep state #'determine-min-max)
(let* ((height (1+ (- y-max y-min)))
(width (1+ (- x-max x-min)))
(mask (make-array (list height width)
:element-type 'double-float
:initial-element 0d0)))
(aa:cells-sweep state (lambda (x y alpha)
(setf alpha (min 256 (max 0 alpha)))
(setf (aref mask (- y-max y) (- x x-min))
(/ alpha 256d0))))
(make-instance 'glyph
:x-offset x-min :y-offset (- y-max)
:left-shape left-shape :right-shape right-shape
:mask mask))))))
1
0 -****- 2
3
(defun make-dot (font center)
(with-accessors ((stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((x (realpart center))
(y (imagpart center))
(sw/2 (/ stroke-width 2))
(sh/2 (/ stroke-height 2))
(p0 (c (- x sw/2) y))
(p1 (c x (+ y sh/2)))
(p2 (c (+ x sw/2) y))
(p3 (c x (- y sh/2))))
(mf p0 up ++ p1 right ++ p2 down ++ p3 left ++ cycle)))))
2
1- * * * * -5 7-****-3
(defun make-o-paths (font)
(with-accessors ((width width)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(let* ((p0 (complex (/ width 2) 0))
(p1 (complex 0 (/ lower-case-ascent 2)))
(p2 (complex (/ width 2) lower-case-ascent))
(p3 (complex width (/ lower-case-ascent 2)))
(p4 (+ p0 (complex 0 stroke-height)))
(p5 (+ p1 stroke-width))
(p6 (- p2 (complex 0 stroke-height)))
(p7 (- p3 stroke-width)))
(list (mf p0 left ++ p1 up ++ p2 right ++ p3 down ++ cycle)
(mf p4 right ++ p7 up ++ p6 left ++ p5 down ++ cycle)))))
| * * | * * * * * * * * * 2
4-|****| 6 7- * * * * \
| |\5 * * * * |
(defun make-h-m-n-hook (font p0 width)
(with-accessors ((lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((bend-start (- lower-case-ascent (* stroke-height 3.0)))
(p1 (+ p0 stroke-width))
(p2 (+ p1 (c 0 bend-start)))
(p4 (- p2 width))
(p5 (+ p4 (* 0.5 stroke-width)))
(p3 (c (realpart (* 1/2 (+ p2 p4))) lower-case-ascent))
(p6 (- p3 (c 0 stroke-height)))
(p7 (- p2 stroke-width)))
(mf p0 --
p7 up ++
p6 left ++
down p5 --
p4 up ++
p3 right ++
down p2 --
p1 -- cycle)))))
(defun make-vertical-stroke (font p0 height)
(with-accessors ((stroke-width stroke-width))
font
(let* ((p1 (+ p0 (complex 0 height)))
(p2 (+ p1 stroke-width))
(p3 (+ p0 stroke-width)))
(mf p0 -- p1 -- p2 -- p3 -- cycle))))
(defun make-horizontal-stroke (font p0 width)
(with-accessors ((stroke-height stroke-height))
font
(let* ((p1 (+ p0 (complex 0 stroke-height)))
(p2 (+ p1 width))
(p3 (+ p0 width)))
(mf p0 -- p1 -- p2 -- p3 -- cycle))))
13
12- * * * 10 * * * * -
0 -****- 4 6-****- 2 - | h2 | |
3 8 15
(defun make-glyph-lower-case-a (font)
(with-accessors ((width width)
(lower-case-ascent lower-case-ascent )
(stroke-width stroke-width )
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (* lower-case-ascent 0.3))
(h2 (round (* lower-case-ascent 0.65)))
(h3 (* lower-case-ascent 0.7))
(h4 (round (* lower-case-ascent 0.75)))
(p0 (c 0 h1))
(p3 (c (* width 0.5) 0))
(p1 (+ p3 (c 0 h2)))
(p2 (+ p0 width))
(p4 (+ p0 stroke-width))
(p5 (- p1 (c 0 stroke-height)))
(p6 (- p2 stroke-width))
(p7 (+ p3 (c 0 stroke-height)))
(p8 (c (- width stroke-width) 0))
(p9 (c (- width stroke-width) h3))
(p10 (c (* width 0.6) (- lower-case-ascent stroke-height)))
(p12 (c (round (* width 0.1)) h4))
(p11 (+ p12 stroke-width))
(p13 (+ p10 (c 0 stroke-height)))
(p14 (+ p9 (c stroke-width 0)))
(p15 (c width 0)))
(make-glyph
(list (mf p0 up ++ p1 right ++ p2 down ++ p3 left ++ cycle)
(mf p4 down ++ p7 right ++ p6 up ++ p5 left ++ cycle)
(mf p8 -- p9 up ++ p10 left ++ down p11 --
p12 up ++ p13 right ++ down p14 -- p15 -- cycle))
#\a #\i)))))
(defun make-glyph-lower-case-b (font)
(with-accessors ((ascent ascent))
font
(make-glyph (cons (make-vertical-stroke font #c(0 0) ascent)
(make-o-paths font))
#\l #\o)))
(defun make-glyph-lower-case-c (font)
(with-accessors ((width width)
(lower-case-ascent lower-case-ascent)
(stroke-height stroke-height))
font
(let* ((h (* stroke-height (if (< width 5) 1 1.7)))
(p0 (complex (/ width 2) (/ lower-case-ascent 2)))
(p1 (complex width h))
(p2 (complex width (- lower-case-ascent h))))
(make-glyph (cons (mf p0 -- p1 -- p2 -- cycle)
(make-o-paths font))
#\o #\c))))
(defun make-glyph-lower-case-d (font)
(with-accessors ((ascent ascent)
(width width)
(stroke-width stroke-width))
font
(make-glyph (cons (make-vertical-stroke font (- width stroke-width) ascent)
(make-o-paths font))
#\o #\l)))
* * * * 4 5 * * * *
* * * * 3 0 6 * \ - 1 |
(defun make-glyph-lower-case-e (font)
(with-accessors ((width width)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(let* ((h (* stroke-height 1.7))
(m (ceiling (- lower-case-ascent stroke-height) 2))
(p0 (complex (/ width 2) m))
(p1 (complex width h))
(p2 (complex width m))
(p3 (complex stroke-width m))
(p4 (complex stroke-width (+ m stroke-height)))
(p5 (complex (- width stroke-width) (+ m stroke-height)))
(p6 (complex (- width stroke-width) m)))
(make-glyph (list* (mf p0 -- p1 -- p2 -- cycle)
(mf p4 -- p5 -- p6 -- p3 -- cycle)
(make-o-paths font))
#\o #\o))))
6 7
5 -****10 9 -
4 * * * * 11 |
3 -********- 12 |
2 -********- 13 |
1 * * * * |
0 15
(defun make-glyph-lower-case-f (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(j-width j-width)
(j-hook-start j-hook-start)
(lower-case-ascent lower-case-ascent))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (max 1 (round (* ascent 0.1))))
(w2 j-width)
(w3 (* ascent 0.2))
(h (- ascent j-hook-start))
(p0 (c w1 0))
(p1 (+ p0 (c 0 (- lower-case-ascent stroke-height))))
(p2 (- p1 (c w1 0)))
(p3 (+ p2 (c 0 stroke-height)))
(p4 (+ p1 (c 0 stroke-height)))
(p5 (+ p0 (c 0 h)))
(p6 (c (+ w1 w3) ascent))
(p7 (c (+ w1 w2) ascent))
(p8 (- p7 (c 0 stroke-height)))
(p9 (- p6 (c 0 stroke-height)))
(p10 (+ p5 stroke-width))
(p11 (+ p4 stroke-width))
(p12 (+ p3 stroke-width (* 2 w1)))
(p13 (+ p2 stroke-width (* 2 w1)))
(p14 (+ p1 stroke-width))
(p15 (+ p0 stroke-width)))
(make-glyph
(list (mf p0 -- p1 -- p2 -- p3 -- p4 -- p5 up ++
right p6 -- p7 -- p8 -- p9 left ++
down p10 -- p11 -- p12 -- p13 -- p14 -- p15 -- cycle))
#\f #\f)))))
6 7 -****- 2 _ | |
4 - * * * * * * * * * * _ |
3
(defun make-glyph-lower-case-g (font)
(with-accessors ((ascent ascent)
(width width)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(descent descent))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (* ascent 0.07))
(h2 descent)
(w1 (* width 0.5))
(w2 (round (* 0.2 width)))
(p0 (c (- width stroke-width) lower-case-ascent))
(p1 (+ p0 stroke-width))
(p2 (c width (- h1)))
(p3 (c w1 (- h2)))
(p4 (c w2 (- h2)))
(p5 (+ p4 (c 0 stroke-height)))
(p6 (+ p3 (c 0 stroke-height)))
(p7 (- p2 stroke-width)))
(make-glyph
(cons (mf p0 -- p1 -- p2 down ++ left p3 -- p4 --
p5 -- p6 right ++ up p7 -- cycle)
(make-o-paths font))
#\o #\q)))))
(defun make-glyph-lower-case-h (font)
(with-accessors ((ascent ascent)
(width width)
(stroke-width stroke-width))
font
(let ((w (round (* 0.9 width))))
(make-glyph (list (make-vertical-stroke font #c(0 0) ascent)
(make-h-m-n-hook font (- w stroke-width) w))
#\l #\i))))
(defun make-glyph-lower-case-i (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(make-glyph (list (make-vertical-stroke font #c(0 0) lower-case-ascent)
(make-dot font
(complex (/ stroke-height 2)
(+ lower-case-ascent (* 3/2 stroke-height)))))
#\i #\i)))
1 * * 2
6 7 8-****-3 _ |
5 4
(defun make-glyph-lower-case-j (font)
(with-accessors ((ascent ascent)
(descent descent)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(j-width j-width)
(j-hook-extreme j-hook-extreme)
(j-hook-start j-hook-start)
(width width))
font
(flet ((c (x y) (complex x y)))
(let* ((h (- descent j-hook-start))
( h ( * 0.1 descent ) )
FIXME , make these the same as for the ` f '
(w1 (- j-width stroke-width))
(w2 (- j-width j-hook-extreme))
( w2 ( * 1.0 stroke - width ) )
(p0 (c w1 0))
(p1 (+ p0 (c 0 lower-case-ascent)))
(p2 (+ p1 stroke-width))
(p3 (- p2 (c 0 (+ lower-case-ascent h))))
(p4 (c w2 (- descent)))
(p5 (c 0 (- descent)))
(p6 (+ p5 (c 0 stroke-height)))
(p7 (+ p4 (c 0 stroke-height)))
(p8 (- p3 stroke-width)))
(make-glyph (list (make-dot font
(c (+ w1 (/ stroke-width 2))
(+ lower-case-ascent (* 3/2 stroke-height))))
(mf p0 -- p1 -- p2 -- p3 down ++
left p4 -- p5 -- p6 -- p7 right ++
up p8 -- cycle))
#\j #\q)))))
* * * * 3 * * * *
* * * * * * 9 * * * * |
- * * * * 10 * * * * |
(defun make-glyph-lower-case-k (font)
(with-accessors ((ascent ascent)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(width width))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (* 0.4 lower-case-ascent))
(h2 (* 0.6 lower-case-ascent))
(w (round (* (if (< width 5) 1.1 0.9) width)))
(p0 (c 0 0))
(p1 (c 0 ascent))
(p2 (+ p1 stroke-width))
(p10 (c stroke-width h1))
(stroke (* 0.5 (+ stroke-width stroke-height)))
assume angles are around 45 degrees
(p3 (+ p10 (c 0 (* stroke 1.2))))
(p5 (c w lower-case-ascent))
(p4 (- p5 (* stroke 1.4)))
(dx10-5 (- w stroke-width))
(dy10-5 (- lower-case-ascent h1))
(dy10-6 (- h2 h1))
(dx10-6 (* dy10-6 (/ dx10-5 dy10-5)))
(p6 (c (+ stroke-width dx10-6) h2))
(p7 (c w 0))
(p8 (- p7 (* 1.4 stroke)))
(dy10-9 (- dy10-6 (* 0.7 stroke)))
(dx10-9 (* dy10-9 (/ dx10-5 dy10-5)))
(p9 (+ p10 (c dx10-9 dy10-9)))
(p11 (c stroke-width 0)))
(make-glyph
(list (mf p0 -- p1 -- p2 -- p3 -- p4 -- p5 -- p6 --
p7 -- p8 -- p9 -- p10 -- p11 -- cycle))
#\l #\x)))))
(defun make-glyph-lower-case-l (font)
(make-glyph (list (make-vertical-stroke font 0 (ascent font)))
#\l #\l))
(defun make-glyph-lower-case-m (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(width width))
font
(let ((d (round (* 0.5 width)))
(sw stroke-width))
(make-glyph
(list (make-vertical-stroke font #c(0 0) lower-case-ascent)
(make-h-m-n-hook font (+ sw d) (+ sw sw d))
(make-h-m-n-hook font (+ sw d sw d) (+ sw sw d)))
#\i #\i))))
(defun make-glyph-lower-case-n (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(width width)
(stroke-width stroke-width))
font
(let ((w (round (* 0.9 width))))
(make-glyph (list (make-vertical-stroke font #c(0 0) lower-case-ascent)
(make-h-m-n-hook font (- w stroke-width) w))
#\i #\i))))
(defun make-glyph-lower-case-o (font)
(make-glyph (make-o-paths font) #\o #\o))
(defun make-glyph-lower-case-p (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(descent descent))
font
(make-glyph (cons (make-vertical-stroke font
(complex 0 (- descent))
(+ lower-case-ascent descent))
(make-o-paths font))
#\p #\o)))
(defun make-glyph-lower-case-q (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(width width)
(stroke-width stroke-width)
(descent descent))
font
(make-glyph (cons (make-vertical-stroke font
(complex (- width stroke-width)
(- descent))
(+ lower-case-ascent descent))
(make-o-paths font))
#\o #\q)))
1
| * * * | 2
(defun make-glyph-lower-case-r (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(width width))
font
(flet ((c (x y) (complex x y)))
(let* ((bend-start (- lower-case-ascent (* stroke-height 3.0)))
(w (* 0.5 width))
(p0 (c 0 bend-start))
(p1 (c w lower-case-ascent))
(p2 (- p1 (c 0 stroke-height)))
(p3 (+ p0 (* 0.5 stroke-width))))
(make-glyph
(list (make-vertical-stroke font (c 0 0) lower-case-ascent)
(mf p0 up ++ right p1 -- p2 left ++ down p3 -- cycle))
#\i #\r)))))
6
* * * * * * * * * * * * * * * * * - 7
* * * * 9 * - 8
* * * * 11
4 * * * *
13
(defun make-glyph-lower-case-s (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(width width))
font
(flet ((c (x y) (complex x y)))
(let* ((upper-shrink (round (* width 0.1)))
(h1 (* lower-case-ascent 0.15))
(h2 (* lower-case-ascent 0.3))
(delta (if (or (and (oddp lower-case-ascent)
(evenp stroke-height))
(and (evenp lower-case-ascent)
(oddp stroke-height)))
1/2
0))
(p0 (c 0 h1))
assume angle about 45 degrees
(p1 (+ p0 (* stroke-width (c 0.7 0.7))))
(p13 (c (* 0.5 width) 0))
(p2 (+ p13 (c 0 stroke-height)))
(p12 (c width h2))
(p3 (- p12 stroke-width))
(p4 (c (* 0.5 width) (+ (* 1/2 (- lower-case-ascent stroke-height)) delta)))
(p11 (+ p4 (c 0 stroke-height)))
(p5 (c upper-shrink (- lower-case-ascent h2)))
(p10 (+ p5 stroke-width))
(p6 (c (* 0.5 width) lower-case-ascent))
(p9 (- p6 (c 0 stroke-height)))
(p7 (c (- width upper-shrink) (- lower-case-ascent h1)))
(p8 (+ p7 (- p0 p1))))
(make-glyph
(list (mf p0 -- p1 ++ right p2 ++ up p3 ++ left p4 ++
up p5 ++ right p6 ++ p7 -- p8 ++ left p9 ++
down p10 ++ right p11 ++ down p12 ++ left p13 ++ cycle))
#\o #\o)))))
4 * * * * 7
3 - * * * * * * * * * * - 8
2 - * * * * * * * * * * - 9
1 * * * * 10
0 -****- 11
* * * * 12 13
15 14
(defun make-glyph-lower-case-t (font)
(with-accessors ((ascent ascent)
(descent descent)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(j-width j-width)
(j-hook-extreme j-hook-extreme)
(j-hook-start j-hook-start)
(width width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (max 1 (round (* ascent 0.1))))
(p0 (c w1 j-hook-start))
(p1 (c w1 (- lower-case-ascent stroke-height)))
(p2 (- p1 w1))
(p3 (+ p2 (c 0 stroke-height)))
(p4 (+ p3 w1))
(p5 (c w1 (round (* 0.8 ascent))))
(p6 (+ p5 stroke-width))
(p7 (+ p4 stroke-width))
(p8 (+ p7 w1))
(p9 (- p8 (c 0 stroke-height)))
(p10 (+ p1 stroke-width))
(p11 (+ p0 stroke-width))
(p12 (c (+ w1 j-hook-extreme) stroke-height))
(p13 (c (+ w1 j-width) stroke-height))
(p14 (+ w1 j-width))
(p15 (+ w1 j-hook-extreme)))
(make-glyph
(list (mf p0 -- p1 -- p2 -- p3 -- p4 -- p5 -- p6 -- p7 -- p8 --
p9 -- p10 -- p11 down ++ right p12 -- p13 --
p14 -- p15 left ++ up cycle))
#\l #\t)))))
(defun make-glyph-lower-case-u (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(width width)
(stroke-width stroke-width))
font
(let ((w (round (* 0.9 width))))
(make-glyph (list (make-vertical-stroke font (- width stroke-width) lower-case-ascent)
(paths:path-rotate
(make-h-m-n-hook font (- w stroke-width) w)
pi
(paths:make-point (* 0.5 width) (* 0.5 lower-case-ascent))))
#\u #\i))))
1 * * * * 2 4 * * * * 5
* * * * 3 * * * *
0 * * * * * 6
|___|
(defun make-glyph-lower-case-v (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(width width)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (max 4 (round (* 0.9 width))))
(w2 (* 1.1 stroke-width))
(w3 (* 1.0 stroke-width))
(p0 (* 0.5 (- w1 w2)))
(p1 (c 0 lower-case-ascent))
(p2 (+ p1 w3))
(p4 (+ p1 (- w1 w3)))
(p5 (+ p1 w1))
(p6 (+ p0 w2)))
(make-glyph (list (mf p0 -- p1 -- p2 -- p3 -- p4 -- p5 -- p6 -- cycle))
#\v #\v)))))
b****c
|_____|___|
(defun make-glyph-lower-case-w (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(width width)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (max 5 (round (* 1.2 width))))
(w2 (* 1.0 stroke-width))
(w3 (* 1.0 stroke-width))
(w4 (* 0.2 w1))
(pa (c w4 0))
(pb (c 0 lower-case-ascent))
(pc (+ pb w3))
(pd (c (+ w4 (* 0.5 w2)) (* 1.0 stroke-height)))
(pe (c (* 0.5 (- w1 w2)) (* 0.7 lower-case-ascent)))
(pf (+ pe w2))
(pg (c (- w1 (+ w4 (* 0.5 w2))) (* 1.0 stroke-height)))
(ph (c (- w1 w3) lower-case-ascent))
(ppi (c w1 lower-case-ascent))
(pj (c (- w1 w4) 0))
(pk (- pj w2))
(pl (c (* 0.5 w1) (- (imagpart pe) (* 1.0 stroke-height))))
(pm (+ pa w2)))
(make-glyph (list (mf pa -- pb -- pc -- pd -- pe -- pf -- pg --
ph -- ppi -- pj -- pk -- pl -- pm -- cycle))
#\v #\v)))))
|
a****l
|____| |___|
(defun make-glyph-lower-case-x (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(width width)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (max 4 (round (* 0.9 width))))
(w2 (* 0.5 (- w1 (* 0.8 stroke-width))))
(w3 (* 1.3 stroke-width))
(h1 (* 1.0 stroke-width))
(pa (c 0 0))
(pb (c w2 (* 0.5 lower-case-ascent)))
(pc (c 0 lower-case-ascent))
(pd (+ pc w3))
(pe (c (* 0.5 w1) (+ (imagpart pb) (* 0.5 h1))))
(pf (c (- w1 w3) lower-case-ascent))
(pg (c w1 lower-case-ascent))
(ph (+ pb (- w1 (* 2 w2))))
(ppi (c w1 0))
(pj (c (- w1 w3) 0))
(pk (- pe (c 0 h1)))
(pl (c w3 0)))
(make-glyph
(list (mf pa -- pb -- pc -- pd -- pe -- pf --
pg -- ph -- ppi -- pj -- pk -- pl -- cycle))
#\x #\x)))))
e****f
(defun make-glyph-lower-case-y (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(width width)
(stroke-height stroke-height)
(stroke-width stroke-width)
(descent descent))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (max 4 (round (* 0.9 width))))
(w2 (* 1.0 stroke-width))
(w3 (* 0.1 w1))
(w4 (* 0.5 (- w1 (* 0.9 stroke-width))))
(pa (c w3 (- descent)))
(pb (+ pa (c 0 stroke-height)))
(pc (+ pb (* 0.03 w4)))
(pd (c w4 0))
(pe (c 0 lower-case-ascent))
(pf (+ pe w2))
(pg (c (* 0.5 w1) (* 0.9 stroke-height)))
(ph (c (- w1 w2) lower-case-ascent))
(ppi (c w1 lower-case-ascent))
(pj (+ ppi (* 1.2 (- pd ph))))
(pk (- pc (c 0 stroke-height))))
(make-glyph
(list (mf pa -- pb -- pc right ++ pd -- pe -- pf -- pg -- ph --
ppi -- pj (direction (- pd ph)) ++ left pk -- cycle))
#\v #\v)))))
e****************f
a***************j
(defun make-glyph-lower-case-z (font)
(with-accessors ((lower-case-ascent lower-case-ascent)
(width width)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (max 4 (round (* 0.9 width))))
(w2 (* 1.1 stroke-width))
(pa (c 0 0))
(pb (c 0 stroke-height))
(pc (c (- w1 w2) (- lower-case-ascent stroke-height)))
(pd (c 0 (- lower-case-ascent stroke-height)))
(pe (c 0 lower-case-ascent))
(pf (c w1 lower-case-ascent))
(pg (c w1 (- lower-case-ascent stroke-height)))
(ph (c w2 stroke-height))
(ppi (c w1 stroke-height))
(pj (c w1 0)))
(make-glyph
(list (mf pa -- pb -- pc -- pd -- pe -- pf -- pg --
ph -- ppi -- pj -- cycle))
#\z #\z)))))
(defun make-glyph-upper-case-a (font)
(with-accessors ((ascent ascent)
(lower-case-ascent lower-case-ascent)
(upper-case-h-width upper-case-h-width)
(j-hook-start j-hook-start)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w2 (round (* 1.2 stroke-width)))
(w1 (let ((w (round (* 1.2 upper-case-h-width))))
(if (= (mod w2 2) (mod w 2)) w (1- w))))
(w3 (* 1.05 stroke-width))
(h1 (round (* 0.4 ascent)))
(xb (* 1/2 (- w1 w2)))
(xj (* (/ xb ascent) h1))
(xi (* (/ xb ascent) (- h1 stroke-height)))
(pa (c 0 0))
(pb (c xb ascent))
(pc (+ pb w3))
(pd (+ pa w3))
(pf (c (* 1/2 (+ w1 w2)) ascent))
(pe (- pf w3))
(pg (c w1 0))
(ph (- pg w3))
(ppi (c xi (- h1 stroke-height)))
(pj (c xj h1))
(pk (c (- w1 xj) h1))
(pl (c (- w1 xi) (- h1 stroke-height))))
(make-glyph
(list (mf pa -- pb -- pc -- pd -- cycle)
(mf pe -- pf -- pg -- ph -- cycle)
(mf ppi -- pj -- pk -- pl -- cycle))
#\l #\l)))))
(defun make-loop (font pa w1 w2 h)
(with-accessors ((stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((pb (+ pa (c 0 stroke-height)))
(pc (+ pb w1))
(pd (+ pa (c (- w2 stroke-width) (/ h 2))))
(pf (+ pa (c 0 (- h stroke-height))))
(pe (+ pf w1))
(pg (+ pa (c 0 h)))
(ph (+ pg w1))
(pj (+ pd stroke-width))
(pk (+ pa w1)))
(mf pa -- pb -- pc right ++ up pd ++ left pe -- pf --
pg -- ph right ++ down pj ++ left pk -- cycle)))))
(defun make-glyph-upper-case-b (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.88 upper-case-h-width)))
(w2 (round (* 0.8 upper-case-h-width)))
(h upper-case-h-bar-position))
(make-glyph
(list (make-vertical-stroke font 0 ascent)
(make-loop font
(c stroke-width 0)
(* 0.5 w1)
w1
h)
(make-loop font
(c stroke-width (- h stroke-height))
(* 0.5 w2)
w2
(+ (- ascent h) stroke-height)))
#\l #\B)))))
(defun make-glyph-upper-case-c (font)
(with-accessors ((ascent ascent)
(upper-case-o-width upper-case-o-width)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (if (oddp upper-case-o-width)
(+ 1/2 (floor (* 1/3 upper-case-o-width)))
(round (* 1/3 upper-case-o-width))))
(h1 (* 0.12 ascent))
(h2 (* 1.1 stroke-height))
(pa (c (* 1/2 upper-case-o-width) 0))
(pb (+ pa (c 0 stroke-height)))
(pc (c (+ (* 1/2 upper-case-o-width) w1) (+ h1 h2)))
(pd (- pc (c 0 h2)))
(pf (+ pa (c 0 ascent)))
(pe (- pf (c 0 stroke-height)))
(ph (c (realpart pc) (- ascent (imagpart pc))))
(pg (c (realpart pd) (- ascent (imagpart pd))))
(center (paths:make-point (* 1/2 upper-case-o-width)
(* 1/2 ascent))))
(make-glyph
(list (paths:path-rotate
(make-loop font pa 0 (* 1/2 upper-case-o-width) ascent)
pi
center)
(mf pa -- pb right ++ pc -- pd ++ left cycle)
(mf pe -- pf right ++ pg -- ph ++ left cycle))
#\l #\C)))))
(defun make-glyph-upper-case-d (font)
(with-accessors ((ascent ascent)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.71 ascent))))
(make-glyph
(list (make-vertical-stroke font 0 ascent)
(make-loop font (c stroke-height 0) (* 0.3 w1) w1 ascent))
#\l #\l)))))
(defun make-glyph-upper-case-e (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.75 upper-case-h-width)))
(w2 (round (* 0.88 w1))))
(make-glyph
(list (make-vertical-stroke font 0 ascent)
(make-horizontal-stroke font 0 w1)
(make-horizontal-stroke
font (c 0 (- ascent stroke-height)) w1)
(make-horizontal-stroke
font (c 0 (- upper-case-h-bar-position stroke-height)) w2))
#\l #\E)))))
(defun make-glyph-upper-case-f (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.75 upper-case-h-width)))
(w2 (round (* 0.88 w1))))
(make-glyph
(list (make-vertical-stroke font 0 ascent)
(make-horizontal-stroke
font (c 0 (- ascent stroke-height)) w1)
(make-horizontal-stroke
font (c 0 (- upper-case-h-bar-position stroke-height)) w2))
#\l #\E)))))
* * * * | |
(defun make-glyph-upper-case-g (font)
(with-accessors ((ascent ascent)
(upper-case-o-width upper-case-o-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (if (oddp upper-case-o-width)
(+ 1/2 (floor (* 0.37 upper-case-o-width)))
(round (* 0.37 upper-case-o-width))))
(w2 (* 0.43 upper-case-o-width))
(h1 (* 0.06 ascent))
(h2 (* 1.1 stroke-height))
(h3 upper-case-h-bar-position)
(pa (c (* 1/2 upper-case-o-width) 0))
(pb (+ pa (c 0 stroke-height)))
(pc (c (+ (* 1/2 upper-case-o-width) w1) (+ h1 h2)))
(pd (- pc (c 0 h2)))
(pf (+ pa (c 0 ascent)))
(pe (- pf (c 0 stroke-height)))
(ph (c (realpart pc) (- ascent (imagpart pc))))
(pg (c (realpart pd) (- ascent (imagpart pd))))
(pj (- pd stroke-width))
(pk (c (- (+ (* 1/2 upper-case-o-width) w1) stroke-width)
(- h3 stroke-height)))
(pl (c w2 (- h3 stroke-height)))
(pm (c w2 h3))
(pn (c (+ (* 1/2 upper-case-o-width) w1) h3))
(center (paths:make-point (* 1/2 upper-case-o-width)
(* 1/2 ascent))))
(make-glyph
(list (paths:path-rotate
(make-loop font pa 0 (* 1/2 upper-case-o-width) ascent)
pi
center)
(mf pa -- pb right ++ pc -- pd ++ left cycle)
(mf pe -- pf right ++ pg -- ph ++ left cycle)
(mf pj -- pk -- pl -- pm -- pn -- pd -- cycle))
#\l #\C)))))
(defun make-glyph-upper-case-h (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w upper-case-h-width)
(pa (c stroke-width (- upper-case-h-bar-position stroke-height))))
(make-glyph
(list (make-vertical-stroke font (c 0 0) ascent)
(make-vertical-stroke font (c (- w stroke-width) 0) ascent)
(make-horizontal-stroke font pa (- w (* 2 stroke-width))))
#\l #\l)))))
(defun make-glyph-upper-case-i (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w (max 1 (round (* ascent 0.1))))
(h (- ascent (* 2 stroke-height))))
(make-glyph
(list (make-horizontal-stroke font (c 0 0) (+ (* 2 w) stroke-width))
(make-horizontal-stroke font (c 0 (- ascent stroke-height))
(+ (* 2 w) stroke-width))
(make-vertical-stroke font (c w stroke-height) h))
#\I #\I)))))
(defun make-glyph-upper-case-j (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(j-hook-start j-hook-start)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (max 3 (round (* 0.60 upper-case-h-width))))
(w2 (max 1 (round (* 0.250 upper-case-h-width))))
(h1 j-hook-start)
(pa (c 0 0))
(pb (+ pa (c 0 stroke-height)))
(pc (c (* 0.3 w1) stroke-height))
(pd (c (- w1 stroke-width) h1))
(pe (c (- w1 stroke-width) (- ascent stroke-height)))
(pf (c w2 (- ascent stroke-height)))
(pg (c w2 ascent))
(ph (c w1 ascent))
(ppi (+ pd stroke-width))
(pj (- pc (c 0 stroke-height))))
(make-glyph
(list (mf pa -- pb right ++ pc right ++ up pd -- pe -- pf --
pg -- ph -- ppi down ++ left pj -- cycle))
#\J #\l)))))
(defun make-glyph-upper-case-k (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.9 upper-case-h-width)))
(w2 (* 1.1 stroke-width))
(h1 (round (* 1.0 lower-case-ascent)))
(pb (c stroke-width h1))
(pa (- pb (c 0 (* 1.3 stroke-height))))
(pd (c w1 ascent))
(pc (- pd w2))
(pf (+ pb w2))
(pg (c w1 0))
(pe (- pg w2)))
(make-glyph
(list (make-vertical-stroke font (c 0 0) ascent)
(mf pa -- pb -- pc -- pd -- cycle)
(mf pb -- pf -- pg -- pe -- cycle))
#\l #\K)))))
(defun make-glyph-upper-case-l (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w (round (* 0.71 upper-case-h-width))))
(make-glyph
(list (make-vertical-stroke font (c 0 0) ascent)
(make-horizontal-stroke font (c 0 0) w))
#\l #\L)))))
(defun make-glyph-upper-case-m (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 1.2 upper-case-h-width)))
(w2 (* 1.0 stroke-width))
(pa (c 0 ascent))
(pb (+ pa w2))
(pc (c (* 0.5 (- w1 w2)) (- lower-case-ascent (* 1.3 stroke-height))))
(pd (+ pc w2))
(pe (c (- w1 w2) ascent))
(pf (+ pe w2)))
(make-glyph
(list (make-vertical-stroke font (c 0 0) ascent)
(make-vertical-stroke font (c (- w1 stroke-width) 0) ascent)
(mf pa -- pb -- pd -- pc -- cycle)
(mf pc -- pe -- pf -- pd -- cycle))
#\l #\l)))))
(defun make-glyph-upper-case-n (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(lower-case-ascent lower-case-ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 1.0 upper-case-h-width)))
(w2 (* 1.0 stroke-width))
(pa (c 0 ascent))
(pb (+ pa w2))
(pc (c w1 0))
(pd (- pc w2)))
(make-glyph
(list (make-vertical-stroke font (c 0 0) ascent)
(make-vertical-stroke font (c (- w1 stroke-width) 0) ascent)
(mf pa -- pb -- pc -- pd -- cycle))
#\l #\l)))))
(defun make-glyph-upper-case-o (font)
(with-accessors ((ascent ascent)
(upper-case-o-width upper-case-o-width))
font
(flet ((c (x y) (complex x y)))
(let* ((pa (c (* 1/2 upper-case-o-width) 0))
(center (paths:make-point (* 1/2 upper-case-o-width)
(* 1/2 ascent))))
(make-glyph
(list (paths:path-rotate
(make-loop font pa 0 (* 1/2 upper-case-o-width) ascent)
pi
center)
(make-loop font pa 0 (* 1/2 upper-case-o-width) ascent))
#\l #\l)))))
(defun make-glyph-upper-case-p (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.83 upper-case-h-width)))
(h (* 0.84 upper-case-h-bar-position)))
(make-glyph
(list (make-vertical-stroke font 0 ascent)
(make-loop font
(c 0 (- h stroke-height))
(* 0.55 w1)
w1
(+ (- ascent h) stroke-height)))
#\l #\P)))))
(defun make-glyph-upper-case-q (font)
(with-accessors ((ascent ascent)
(upper-case-o-width upper-case-o-width)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (* 0.9 upper-case-o-width))
(w2 (* 0.5 upper-case-o-width))
(w3 (* 0.15 ascent))
(h1 (* 0.2 ascent))
(h2 (* 0.1 ascent))
(pa (c (* 1/2 upper-case-o-width) 0))
(pb (c w2 h1))
(pd (c w1 (- h2)))
(pc (+ pd w3))
(center (paths:make-point (* 1/2 upper-case-o-width)
(* 1/2 ascent))))
(make-glyph
(list (paths:path-rotate
(make-loop font pa 0 (* 1/2 upper-case-o-width) ascent)
pi
center)
(make-loop font pa 0 (* 1/2 upper-case-o-width) ascent)
(mf pb -- pc -- pd -- cycle))
#\l #\Q)))))
(defun make-glyph-upper-case-r (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.83 upper-case-h-width)))
(w2 (* 1.2 stroke-width))
(w3 (* 0.6 w1))
(w4 (* 0.90 upper-case-h-width))
(h upper-case-h-bar-position)
(pa (c (- w4 w2) 0))
(pb (c w3 (- h (* 0.5 stroke-height))))
(pc (+ pb w2))
(pd (+ pa w2)))
(make-glyph
(list (make-vertical-stroke font 0 ascent)
(make-loop font
(c 0 (- h stroke-height))
(* 0.6 w1)
w1
(+ (- ascent h) stroke-height))
(mf pa -- pb -- pc -- pd -- cycle))
#\l #\R)))))
* * d****n
(defun make-glyph-upper-case-s (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.87 upper-case-h-width)))
(w2 (+ (* 2 (round (* 0.37 upper-case-h-width)))
(if (oddp w1) 1 0)))
(h1 (* 0.06 ascent))
(h2 (* 1.1 stroke-height))
(pa (c 0 h1))
(pb (+ pa (c 0 h2)))
(xo (* 1/2 w1))
(po (c xo 0))
(pc (+ po (c 0 stroke-height)))
(pm (c w1 (* 0.25 ascent)))
(pd (- pm stroke-width))
(ym (+ (* 1/2 (+ ascent stroke-height))
(if (= (mod ascent 2) (mod stroke-height 2)) 0 1/2)))
(pm (c xo ym))
(pe (- pm (c 0 stroke-height)))
(pf (c (* 1/2 (- w1 w2)) (* 0.75 ascent)))
(pg (c xo ascent))
(ph (c (* 1/2 (+ w1 w2)) (- ascent h1)))
(pj (- ph (c 0 h2)))
(pk (- pg (c 0 stroke-height)))
(pl (+ pf stroke-width))
(pn (+ pd stroke-width)))
(make-glyph
(list (mf pa -- pb ++ right pc ++ up pd ++ left pe ++
up pf ++ right pg ++ ph -- pj ++ left pk ++
down pl ++ right pm ++ down pn ++ left po ++ cycle))
#\S #\S)))))
(defun make-glyph-upper-case-t (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w (- (* 2 (round (* 0.5 upper-case-h-width)))
(if (oddp stroke-width) 1 0))))
(make-glyph (list (make-vertical-stroke
font (c (* 1/2 (- w stroke-width)) 0) ascent)
(make-horizontal-stroke
font (c 0 (- ascent stroke-height)) w))
#\T #\T)))))
b****c e****f -
(defun make-glyph-upper-case-u (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w (round (* 1.0 upper-case-h-width)))
(h (* 0.29 ascent))
(pa (c (* 1/2 w) 0))
(pb (c 0 h))
(pc (+ pb stroke-width))
(pd (+ pa (c 0 stroke-height)))
(pf (c w h))
(pe (- pf stroke-width)))
(make-glyph (list (make-vertical-stroke font pb (- ascent h))
(make-vertical-stroke font pe (- ascent h))
(mf pa left ++ pb -- pc down ++ right
pd ++ up pe -- pf down ++ left cycle))
#\l #\l)))))
|___|
(defun make-glyph-upper-case-v (font)
(with-accessors ((ascent ascent)
(lower-case-ascent lower-case-ascent)
(upper-case-h-width upper-case-h-width)
(j-hook-start j-hook-start)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w2 (round (* 1.2 stroke-width)))
(w1 (let ((w (round (* 1.2 upper-case-h-width))))
(if (= (mod w2 2) (mod w 2)) w (1- w))))
(w3 (* 1.05 stroke-width))
(xb (* 1/2 (- w1 w2)))
(pa (c 0 ascent))
(pb (c xb 0))
(pc (+ pb w3))
(pd (+ pa w3))
(pf (c (* 1/2 (+ w1 w2)) 0))
(pe (- pf w3))
(pg (c w1 ascent))
(ph (- pg w3)))
(make-glyph (list (mf pa -- pd -- pc -- pb -- cycle)
(mf ph -- pg -- pf -- pe -- cycle))
#\V #\V)))))
|___|
(defun make-glyph-upper-case-w (font)
(with-accessors ((ascent ascent)
(lower-case-ascent lower-case-ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 1.5 upper-case-h-width)))
(w2 (round (* 1.2 stroke-width)))
(h (round (* 1.5 upper-case-h-bar-position)))
(w3 (* 1.05 stroke-width))
(xd (/ (- w1 w2) 2 (+ 1 (/ h ascent))))
(pa (c 0 ascent))
(pb (+ pa w3))
(pd (c xd 0))
(pc (+ pd w3))
(ph (+ pd w2))
(pe (- ph w3))
(pf (c (* 1/2 (- w1 w2)) h))
(pg (+ pf w3))
(pk (+ pf w2))
(pj (- pk w3))
(pq (c (- w1 xd) 0))
(pn (- pq w3))
(pm (- pq w2))
(pl (+ pm w3))
(pp (c w1 ascent))
(po (- pp w3)))
(make-glyph (list (mf pa -- pb -- pc -- pd -- cycle)
(mf pe -- pf -- pg -- ph -- cycle)
(mf pj -- pk -- pl -- pm -- cycle)
(mf pn -- po -- pp -- pq -- cycle))
#\V #\V)))))
|
a****l
|____| |___|
(defun make-glyph-upper-case-x (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 1.1 upper-case-h-width)))
(w2 (* 0.5 (- w1 (* 0.8 stroke-width))))
(w3 (* 1.1 stroke-width))
(h1 (* 1.0 stroke-width))
(pa (c 0 0))
(pb (c w2 (* 0.5 ascent)))
(pc (c 0 ascent))
(pd (+ pc w3))
(pe (c (* 0.5 w1) (+ (imagpart pb) (* 0.5 h1))))
(pf (c (- w1 w3) ascent))
(pg (c w1 ascent))
(ph (+ pb (- w1 (* 2 w2))))
(ppi (c w1 0))
(pj (c (- w1 w3) 0))
(pk (- pe (c 0 h1)))
(pl (c w3 0)))
(make-glyph
(list (mf pa -- pb -- pc -- pd -- pe -- pf --
pg -- ph -- ppi -- pj -- pk -- pl -- cycle))
#\x #\x)))))
(defun make-glyph-upper-case-y (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(upper-case-h-bar-position upper-case-h-bar-position)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (+ (* 2 (round (* 0.5 upper-case-h-width)))
(if (oddp stroke-width) 1 0)))
(w2 (* 1.1 stroke-width))
(h (round (* 0.6 upper-case-h-bar-position)))
(xa (* 1/2 (- w1 stroke-width)))
(pa (c xa h))
(pb (c 0 ascent))
(pc (+ pb w2))
(pd (+ pa stroke-width))
(pe (c (- w1 w2) ascent))
(pf (+ pe w2)))
(make-glyph (list (make-vertical-stroke
font (c (* 1/2 (- w1 w2)) 0) h)
(mf pa -- pb -- pc -- pd -- cycle)
(mf pa -- pe -- pf -- pd -- cycle))
#\Y #\Y)))))
* * * * * * * * * * * * * * * *
|___|
(defun make-glyph-upper-case-z (font)
(with-accessors ((ascent ascent)
(upper-case-h-width upper-case-h-width)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.9 upper-case-h-width)))
(w2 (* 1.1 stroke-width))
(pa (c 0 stroke-height))
(pc (c w1 (- ascent stroke-height)))
(pb (- pc w2))
(pd (+ pa w2)))
(make-glyph (list (make-horizontal-stroke
font (c 0 0) w1)
(make-horizontal-stroke
font (c 0 (- ascent stroke-height)) w1)
(mf pa -- pb -- pc -- pd -- cycle))
#\Z #\Z)))))
a**********e
(defun make-disk (center radius)
(flet ((c (x y) (complex x y)))
(let* ((pa (- center radius))
(pe (+ center radius))
(pc (+ center (c 0 radius)))
(pg (- center (c 0 radius)))
(pb (+ center (/ (c (- radius) radius) (sqrt 2))))
(pd (+ center (/ (c radius radius) (sqrt 2))))
(pf (+ center (/ (c radius (- radius)) (sqrt 2))))
(ph (+ center (/ (c (- radius) (- radius)) (sqrt 2)))))
(mf pa up ++ pb ++ pc right ++ pd ++ pe down ++
pf ++ pg left ++ ph ++ cycle))))
(defun make-glyph-period (font)
(with-accessors ((stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(make-glyph (list (make-disk
(* 1 (c stroke-width stroke-width)) (* 1 stroke-width)))
#\. #\.))))
(defun make-comma-hook (font)
(with-accessors ((stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (* 1.5 stroke-width))
(h1 (* 2.0 stroke-height))
(cw1 (ceiling w1))
(pa (c (+ cw1 (* 0.7 stroke-width)) stroke-width))
(pb (c (+ cw1 (* 2 stroke-width)) stroke-width))
(pc (c (- cw1 w1) (- h1))))
(mf pa -- pb down ++ left pc & pc ++ up cycle)))))
(defun make-glyph-comma (font)
(with-accessors ((stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (* 2.0 stroke-width))
(cw1 (ceiling w1)))
(make-glyph (list (make-disk
(c (+ stroke-width cw1) stroke-width)
stroke-width)
(make-comma-hook font))
#\, #\.)))))
(defun make-glyph-colon (font)
(with-accessors ((stroke-width stroke-width)
(lower-case-ascent lower-case-ascent))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 stroke-width)
(h1 (max 5 lower-case-ascent)))
(make-glyph (list (make-disk (c w1 w1) w1)
(make-disk (c w1 (- h1 w1)) w1))
#\: #\:)))))
(defun make-glyph-semicolon (font)
(with-accessors ((stroke-width stroke-width)
(lower-case-ascent lower-case-ascent))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (* 2.0 stroke-width))
(cw1 (ceiling w1))
(h1 (max 5 lower-case-ascent)))
(make-glyph (list (make-disk
(c (+ stroke-width cw1) stroke-width)
stroke-width)
(make-disk
(c (+ stroke-width cw1)
(- h1 stroke-width))
stroke-width)
(make-comma-hook font))
#\, #\.)))))
(defun make-glyph-exclamation-mark (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h (round (* 1.0 ascent)))
(pa (c (* 1/2 stroke-width) (- h stroke-width)))
(pb (c (* 1/2 stroke-width) (* 2 stroke-width)))
(pc (- pa (* 1/2 stroke-width)))
(pd (+ pa (* 1/2 stroke-width))))
(make-glyph (list (make-disk
(* 1/2 (c stroke-width stroke-width))
(* 1/2 stroke-width))
(make-disk pa (* 1/2 stroke-width))
(mf pc -- pd down ++ pb & pb ++ up cycle))
#\. #\.)))))
(defun make-quote (font xpos)
(with-accessors ((ascent ascent)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (round (* 1.0 ascent)))
(h2 (* 0.3 ascent))
(pa (c (+ xpos (* 1/2 stroke-width)) (- h1 stroke-width)))
(pb (c (+ xpos (* 1/2 stroke-width)) (- ascent h2)))
(pc (- pa (* 1/2 stroke-width)))
(pd (+ pa (* 1/2 stroke-width))))
(list (make-disk pa (* 1/2 stroke-width))
(mf pc -- pd down ++ pb & pb ++ up cycle))))))
(defun make-glyph-double-quote (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width))
font
(let ((w (max (* 2 stroke-width) (round (* 0.2 ascent)))))
(make-glyph (append (make-quote font 0)
(make-quote font w))
#\" #\"))))
(defun make-slash (font x1 x2)
(with-accessors ((ascent ascent)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((angle (atan (- x2 x1 stroke-width) ascent))
(w (/ stroke-width (cos angle)))
(pa (c x1 ascent))
(pb (+ pa w))
(pc (c x2 0))
(pd (- pc w)))
(mf pa -- pb -- pc -- pd -- cycle)))))
(defun make-glyph-hash (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (round (* 0.6 ascent)))
(w2 (* 0.05 ascent))
(w3 (round (* 0.3 ascent)))
(h1 (round (* 0.40 ascent))))
(make-glyph (list (make-horizontal-stroke
font
(c 0 (- h1 stroke-height))
w1)
(make-horizontal-stroke
font
(c 0 (- ascent h1))
w1)
(make-slash font (- w1 w3 w4) (+ w2 w4))
(make-slash font (- w1 w2 w4) (+ w3 w4)))
#\# #\#)))))
(defun make-glyph-question-mark (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(upper-case-h-width upper-case-h-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h0 (* 2.0 stroke-width))
(h1 (* 0.4 ascent))
(h2 (* 0.75 ascent))
(w (+ (* 2 (round (* 0.25 upper-case-h-width)))
(if (oddp stroke-width) 1 0)))
(pa (c (* 1/2 (- w stroke-width)) h1))
(pb (c (- w stroke-width) h2))
(pf (c (* 1/2 w) ascent))
(pc (- pf (c 0 stroke-height)))
(pe (c 0 h2))
(pd (+ pe stroke-width))
(pg (+ pb stroke-width))
(ph (+ pa stroke-width)))
(make-glyph (list (make-disk
(* 1/2 (c w stroke-width))
(* 1/2 stroke-width))
(make-vertical-stroke
font
(c (* 1/2 (- w stroke-width)) h0)
(- h1 h0))
(mf pa up ++ pb up ++ pc left ++ down pd --
pe up ++ pf right ++ pg down ++ down ph -- cycle))
#\? #\?)))))
(defun make-glyph-slash (font)
(with-accessors ((ascent ascent)
(slash-width slash-width)
(stroke-width stroke-width))
font
(make-glyph (list (make-slash font
(- slash-width (* 1.3 stroke-width))
(* 1.3 stroke-width)))
#\/ #\/)))
(defun make-glyph-digit-1 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (round (* 0.3 ascent)))
(h2 (* 1.2 stroke-height))
(w1 (* 0.15 ascent))
(pa (c (- (ceiling w1) w1) (- ascent h1)))
(pb (c (ceiling w1) ascent))
(pc (c (ceiling w1) (- ascent h2)))
(pd (+ pa (* 1.0 stroke-width))))
(make-glyph (list (make-vertical-stroke font (ceiling w1) ascent)
(mf pa -- pb -- pc -- pd -- cycle))
#\1 #\l)))))
_ g _
(defun make-glyph-digit-2 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (round (* 0.3 ascent)))
(h2 (round (* 0.25 ascent)))
(h3 (* 0.15 ascent))
(w0 digit-width)
(w1 (* 1/2 digit-width))
(pa (c 0 0))
(pb (c 0 h3))
(pc (c (- w0 stroke-width) (- ascent h2)))
(pd (c w1 (- ascent stroke-height)))
(pe (c stroke-width (- ascent h1)))
(pf (c 0 (- ascent h1)))
(pg (c w1 ascent))
(ph (+ pc stroke-width))
(pj (+ pb stroke-width))
(pk (c stroke-width stroke-height))
(pl (c w0 stroke-height))
(pm (c w0 0)))
(make-glyph (list (mf pa -- pb up ++ pc up ++ pd left ++ down pe --
pf up ++ pg right ++ ph down ++ down pj -- pk --
pl -- pm -- cycle))
#\2 #\2)))))
l****k h****n
c * * * *
(defun make-glyph-digit-3 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (round (* 0.3 ascent)))
(h2 (* 0.3 ascent))
(h3 (* 0.25 ascent))
(w0 digit-width)
(w1 (round (* 0.4 w0)))
(w2 (* 1/2 w0))
(pa (c w2 0))
(pb (c 0 h1))
(pc (+ pb stroke-width))
(pd (+ pa (c 0 stroke-height)))
(pe (c (- w0 stroke-width) h2))
(pf (c w1 (- (* 0.55 ascent) (* 1/2 stroke-height))))
(pg (+ pf (c 0 stroke-height)))
(ph (c (- w0 stroke-width) (- ascent h3)))
(pj (c w2 (- ascent stroke-height)))
(pk (c stroke-width (- ascent h1)))
(pl (c 0 (- ascent h1)))
(pm (c w2 ascent))
(pn (+ ph stroke-width))
(pp (c (+ w1 stroke-width) (* 0.55 ascent)))
(pq (+ pe stroke-width)))
(make-glyph (list (mf pa left ++ up pb -- pc down ++ pd right ++
pe up ++ pf -- pg ++ up ph ++ left pj ++
down pk -- pl up ++ right pm ++ down pn ++
left pp & pp right ++ down pq ++ left cycle))
#\3 #\3)))))
(defun make-glyph-digit-4 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (round (* 0.4 ascent)))
(w0 digit-width)
(w1 (* 0.6 w0))
(w2 (round (* 0.2 w0)))
(pa (c (- (ceiling w1) w1) (- h1 stroke-height)))
(paa (+ pa (c 0 stroke-height)))
(pb (c (ceiling w1) ascent))
(pc (c (ceiling w1) (- ascent (* 1.6 stroke-height))))
(pd (+ paa stroke-width))
(pe (c (+ (ceiling w1) stroke-width w2) h1))
(pf (- pe (c 0 stroke-height))))
(make-glyph (list (mf pa -- paa -- pb -- pc -- pd -- pe -- pf -- cycle)
(make-vertical-stroke font (c (ceiling w1) 0) ascent))
#\4 #\4)))))
|________| e****k |h2 |
* * * | |
(defun make-glyph-digit-5 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (round (* 0.25 ascent)))
(h2 (round (* 0.65 ascent)))
(h3 (* 1/2 h2))
(h4 (round (* 0.55 ascent)))
(w0 digit-width)
(w1 (* 0.5 w0))
(w2 (* 0.5 w0))
(pa (c w1 0))
(pb (c 0 h1))
(pc (+ pb stroke-width))
(pd (+ pa (c 0 stroke-height)))
(pe (c (- digit-width stroke-width) h3))
(pf (c w2 (- h2 stroke-height)))
(pg (c stroke-width (- ascent h4)))
(ph (+ pg (c 0 (* 0.8 stroke-height))))
(pj (+ pf (c 0 stroke-height)))
(pk (+ pe stroke-width)))
(make-glyph (list (mf pa left ++ up pb -- pc down ++ pd right ++
pe up ++ pf left ++ pg -- ph ++ right pj ++
down pk ++ left cycle)
(make-vertical-stroke
font (c 0 (- ascent h4)) h4)
(make-horizontal-stroke
font
(c stroke-width (- ascent stroke-height))
(round (* 0.9 (- w0 stroke-width)))))
#\5 #\5)))))
_ |
| * * * * k * * * * |h2 |
(defun make-glyph-digit-6 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (round (* 0.65 ascent)))
(h2 (* 0.32 ascent))
(h3 (* 0.3 ascent))
(h4 (* 0.25 ascent))
(h5 (* 0.45 ascent))
(w0 digit-width)
(w1 (* 0.5 w0))
(pa (c w1 0))
(pb (c 0 h3))
(pc (c 0 (- ascent h3)))
(pd (c w1 ascent))
(pe (c w0 (- ascent h4)))
(pf (- pe stroke-width))
(pg (- pd (c 0 stroke-height)))
(ph (+ pc stroke-width))
(pj (+ pb stroke-width))
(pk (+ pa (c 0 stroke-height)))
(pl (c (- w0 stroke-width) h2))
(pm (c w1 (- h1 stroke-height)))
(pn (c stroke-width h5))
(po (+ pn (c 0 stroke-height)))
(pp (+ pm (c 0 stroke-height)))
(pq (+ pl stroke-width)))
(make-glyph (list (mf pa left ++ up pb -- pc up ++ right pd ++
down pe -- pf up ++ pg left ++ down ph --
pj down ++ right pk ++ up pl ++ left pm ++
pn -- po ++ right pp ++ down pq ++ left cycle))
#\6 #\6)))))
(defun make-glyph-digit-7 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w0 digit-width)
(w1 (* 0.3 w0))
(pa (c w1 0))
(pb (c (- w0 stroke-width) (- ascent stroke-height)))
(pc (+ pb stroke-width))
(pd (+ pa stroke-width)))
(make-glyph (list (mf pa -- pb -- pc -- pd -- cycle)
(make-horizontal-stroke
font (c 0 (- ascent stroke-height)) digit-width))
#\7 #\7)))))
j****p
(defun make-glyph-digit-8 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w0 digit-width)
(ww1 (* 1/2 (round (* 0.8 w0))))
(w1 (+ ww1 (if (integerp ww1) 0 1/2)))
(h1 (* 0.60 ascent))
(h2 (* 0.25 ascent))
(h3 (* 0.30 ascent))
(pa (c (* 1/2 w0) 0))
(pb (c 0 h3))
(pc (c (* 1/2 w0) h1))
(pd (c w0 h3))
(pe (+ pa (c 0 stroke-height)))
(pf (- pd stroke-width))
(pg (- pc (c 0 stroke-height)))
(ph (+ pb stroke-width))
(pj (c (- (* 1/2 w0) w1) (- ascent h2)))
(pk (c (* 1/2 w0) ascent))
(pl (c (+ (* 1/2 w0) w1) (- ascent h2)))
(pm (- pl stroke-width))
(pn (- pk (c 0 stroke-height)))
(pp (+ pj stroke-width)))
(make-glyph (list (mf pa left ++ pb up ++ pc right ++
pd down ++ left cycle)
(mf pe right ++ pf up ++ pg left ++
ph down ++ right cycle)
(mf pg left ++ pj up ++ pk right ++
pl down ++ left cycle)
(mf pc right ++ pm up ++ pn left ++
pp down ++ right cycle))
#\8 #\8)))))
| - * * * *
(defun make-glyph-digit-9 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((h1 (round (* 0.65 ascent)))
(h2 (* 0.32 ascent))
(h3 (* 0.3 ascent))
(h4 (* 0.25 ascent))
(h5 (* 0.45 ascent))
(w0 digit-width)
(w1 (* 0.5 w0))
(pa (c w1 0))
(pb (c 0 h4))
(pc (+ pb stroke-width))
(pd (+ pa (c 0 stroke-height)))
(pe (c (- w0 stroke-width) h3))
(pf (c (- w0 stroke-width) (- ascent h3)))
(pg (c w1 (- ascent stroke-height)))
(ph (c stroke-width (- ascent h2)))
(pj (c w1 (+ (- ascent h1) stroke-height)))
(pk (c (- w0 stroke-width) (+ h5 stroke-height)))
(pl (- pk (c 0 stroke-height)))
(pm (- pj (c 0 stroke-height)))
(pn (c 0 (- ascent h2)))
(po (+ pg (c 0 stroke-height)))
(pp (+ pf stroke-width))
(pq (+ pe stroke-width)))
(make-glyph (list (mf pa left ++ up pb -- pc down ++ right pd ++
up pe -- pf up ++ pg left ++ down ph ++
pj right ++ pk -- pl ++ left pm ++
up pn ++ right po ++ down pp -- pq down ++ left cycle))
#\9 #\9)))))
c****l j****e
b****m h****f -
(defun make-glyph-digit-0 (font)
(with-accessors ((ascent ascent)
(stroke-width stroke-width)
(stroke-height stroke-height)
(digit-width digit-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w0 digit-width)
(w1 (* 1/2 w0))
(h1 (round (* 0.3 ascent)))
(pa (c w1 0))
(pb (c 0 h1))
(pc (c 0 (- ascent h1)))
(pd (c w1 ascent))
(pe (c w0 (- ascent h1)))
(pf (c w0 h1))
(pg (+ pa (c 0 stroke-height)))
(ph (- pf stroke-width))
(pj (- pe stroke-width))
(pk (- pd (c 0 stroke-height)))
(pl (+ pc stroke-width))
(pm (+ pb stroke-width)))
(make-glyph (list (mf pa left ++ up pb -- pc up ++
pd right ++ down pe -- pf down ++ left cycle)
(mf pg right ++ up ph -- pj up ++
left pk ++ down pl -- pm down ++ right cycle))
#\l #\l)))))
(defun make-glyph-left-bracket (font)
(with-accessors ((bracket-width bracket-width)
(bracket-descent bracket-descent)
(bracket-ascent bracket-ascent)
(stroke-height stroke-height))
font
(flet ((c (x y) (complex x y)))
(make-glyph (list (make-vertical-stroke font (c 0 (- bracket-descent)) (+ bracket-ascent bracket-descent))
(make-horizontal-stroke font (c 0 (- bracket-descent)) bracket-width)
(make-horizontal-stroke font (c 0 (- bracket-ascent stroke-height)) bracket-width))
#\l #\[))))
(defun make-glyph-backslash (font)
(with-accessors ((ascent ascent)
(slash-width slash-width))
font
(make-glyph (list (make-slash font 0 slash-width))
#\/ #\/)))
(defun make-glyph-right-bracket (font)
(with-accessors ((bracket-width bracket-width)
(bracket-descent bracket-descent)
(bracket-ascent bracket-ascent)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(make-glyph (list (make-vertical-stroke font (c (- bracket-width stroke-width) (- bracket-descent)) (+ bracket-ascent bracket-descent))
(make-horizontal-stroke font (c 0 (- bracket-descent)) bracket-width)
(make-horizontal-stroke font (c 0 (- bracket-ascent stroke-height)) bracket-width))
#\] #\l))))
(defun make-glyph-left-brace (font)
(with-accessors ((ascent ascent)
(bracket-width bracket-width)
(bracket-descent bracket-descent)
(bracket-ascent bracket-ascent)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (* 0.1 ascent))
(ww1 (ceiling w1))
(w2 (* 0.6 bracket-width))
(h0 (+ bracket-ascent bracket-descent))
(h1 (* 0.26 ascent))
(h2 (* 0.4 ascent))
(pa (c (+ ww1 w2) (- bracket-descent)))
(pb (c ww1 (- h1 bracket-descent)))
(pc (c ww1 (- (* 0.5 (- h0 h2)) bracket-descent)))
(pd (c (- ww1 w1) (- (* 0.5 h0) bracket-descent)))
(pe (c ww1 (- bracket-ascent (* 0.5 (- h0 h2)))))
(pf (c ww1 (- bracket-ascent h1)))
(pg (+ pa (c 0 h0)))
(ph (c (+ ww1 bracket-width) bracket-ascent))
(pj (+ pf stroke-width))
(pk (+ pe stroke-width))
(pl (+ pd (* 0.7 stroke-width)))
(pm (+ pc stroke-width))
(pn (+ pb stroke-width))
(po (c (+ ww1 bracket-width) (- bracket-descent))))
(make-glyph (list (mf pa left ++ up pb ++ up pc ++ pd &
pd ++ up pe ++ up pf ++ right pg ++
ph & ph ++ down pj ++ down pk ++
pl & pl ++ down pm ++ down pn ++
po & po ++ left cycle))
#\{ #\{)))))
(defun make-glyph-right-brace (font)
(with-accessors ((ascent ascent)
(bracket-width bracket-width)
(bracket-descent bracket-descent)
(bracket-ascent bracket-ascent)
(stroke-height stroke-height)
(stroke-width stroke-width))
font
(flet ((c (x y) (complex x y)))
(let* ((w1 (* 0.1 ascent))
(w2 (* 0.6 bracket-width))
(h0 (+ bracket-ascent bracket-descent))
(h1 (* 0.26 ascent))
(h2 (* 0.4 ascent))
(pa (c (- bracket-width stroke-width) (- h1 bracket-descent)))
(pb (c (- bracket-width stroke-width) (- (* 0.5 (- h0 h2)) bracket-descent)))
(pc (c (- (+ bracket-width w1) (* 0.7 stroke-width)) (- (* 0.5 h0) bracket-descent)))
(pd (c (- bracket-width stroke-width) (- bracket-ascent (* 0.5 (- h0 h2)))))
(pe (c (- bracket-width stroke-width) (- bracket-ascent h1)))
(pf (c 0 bracket-ascent))
(pg (c (- bracket-width w2) bracket-ascent))
(ph (+ pe stroke-width))
(pj (+ pd stroke-width))
(pk (c (+ bracket-width w1) (- (* 0.5 h0) bracket-descent)))
(pl (+ pb stroke-width))
(pm (+ pa stroke-width))
(pn (c (- bracket-width w2) (- bracket-descent)))
(po (c 0 (- bracket-descent))))
(make-glyph (list (mf pa up ++ pb up ++ pc & pc ++ up pd ++
up pe ++ pf & pf ++ right pg ++ down ph ++
down pj ++ pk & pk ++ down pl ++ down pm ++
left pn +++ po & po ++ up cycle))
#\} #\})))))
(defun add-glyph (character glyphs glyph)
(setf (gethash character glyphs) glyph))
(defun add-kerning-info (font left-char right-char delta)
(setf (gethash (cons left-char right-char) (kerning-info font))
delta))
(defun compute-kerning-info (font)
(with-accessors ((stroke-width stroke-width)
(width width))
font
(add-kerning-info font #\i #\o (round (* 0.2 stroke-width)))
(add-kerning-info font #\o #\i (round (* 0.2 stroke-width)))
(add-kerning-info font #\o #\o (round (* 0.3 stroke-width)))
(add-kerning-info font #\x #\o (round (* 1.5 stroke-width)))
(add-kerning-info font #\c #\o (round (* 1.0 stroke-width)))
(add-kerning-info font #\o #\x (round (* 0.5 stroke-width)))
(add-kerning-info font #\f #\o (round (* 1.6 stroke-width)))
(add-kerning-info font #\o #\f (round (* 1.0 stroke-width)))
(add-kerning-info font #\f #\l (round (* 1.0 stroke-width)))
(add-kerning-info font #\i #\j (round (* 2.0 stroke-width)))
(add-kerning-info font #\l #\j (round (* 2.0 stroke-width)))
(add-kerning-info font #\o #\j (round (* 2.0 stroke-width)))
(add-kerning-info font #\c #\j (round (* 2.0 stroke-width)))
(add-kerning-info font #\x #\j (round (* 2.0 stroke-width)))
(add-kerning-info font #\f #\j (round (* 2.0 stroke-width)))
(add-kerning-info font #\r #\o
(round (* (if (< width 6) 0 1.0) stroke-width)))))
(defun make-font (size resolution)
(let* ((pixel-size (round (/ (* size resolution) 72)))
(ascent (max 4 pixel-size))
(stroke-width (max 1 (round (* ascent 0.08))))
(font (make-instance 'font
:ascent ascent
:lower-case-ascent (max 2 (round (* ascent 0.6)))
:stroke-width stroke-width
:stroke-height (max 1 (round (* ascent 0.08)))
:j-width (* 3.0 stroke-width)
:j-hook-start (* 0.4 ascent)
:j-hook-extreme (* 2.0 stroke-width)
:slash-width (round (* 0.5 ascent))
2 * stroke - height
:bracket-width (max 2 (round (* ascent 0.2)))
:bracket-ascent (round (* ascent 1.0))
:descent (max 2 (round (* ascent 0.25)))
:width (max 3 (round (* ascent 0.50)))
:upper-case-h-width (round (* ascent 0.71))
:upper-case-o-width (round (* ascent 0.88))
:digit-width (round (* ascent 0.4))
:upper-case-h-bar-position (round (* ascent 0.56))))
(glyphs (glyphs font)))
(compute-kerning-info font)
(let ((mask (make-array (list 1 (width font))
:element-type 'double-float
:initial-element 0d0)))
(add-glyph #\Space glyphs
(make-instance 'glyph
:x-offset 0 :y-offset -1
:left-shape #\l :right-shape #\l
:mask mask)))
(let ((mask (make-array (list 1 (width font))
:element-type 'double-float
:initial-element 05.d0)))
(add-glyph 'default glyphs
(make-instance 'glyph
:x-offset 0 :y-offset -1
:left-shape #\l :right-shape #\l
:mask mask)))
(add-glyph #\a glyphs (make-glyph-lower-case-a font))
(add-glyph #\b glyphs (make-glyph-lower-case-b font))
(add-glyph #\c glyphs (make-glyph-lower-case-c font))
(add-glyph #\d glyphs (make-glyph-lower-case-d font))
(add-glyph #\e glyphs (make-glyph-lower-case-e font))
(add-glyph #\f glyphs (make-glyph-lower-case-f font))
(add-glyph #\g glyphs (make-glyph-lower-case-g font))
(add-glyph #\h glyphs (make-glyph-lower-case-h font))
(add-glyph #\i glyphs (make-glyph-lower-case-i font))
(add-glyph #\j glyphs (make-glyph-lower-case-j font))
(add-glyph #\k glyphs (make-glyph-lower-case-k font))
(add-glyph #\l glyphs (make-glyph-lower-case-l font))
(add-glyph #\m glyphs (make-glyph-lower-case-m font))
(add-glyph #\n glyphs (make-glyph-lower-case-n font))
(add-glyph #\o glyphs (make-glyph-lower-case-o font))
(add-glyph #\p glyphs (make-glyph-lower-case-p font))
(add-glyph #\q glyphs (make-glyph-lower-case-q font))
(add-glyph #\r glyphs (make-glyph-lower-case-r font))
(add-glyph #\s glyphs (make-glyph-lower-case-s font))
(add-glyph #\t glyphs (make-glyph-lower-case-t font))
(add-glyph #\u glyphs (make-glyph-lower-case-u font))
(add-glyph #\v glyphs (make-glyph-lower-case-v font))
(add-glyph #\w glyphs (make-glyph-lower-case-w font))
(add-glyph #\x glyphs (make-glyph-lower-case-x font))
(add-glyph #\y glyphs (make-glyph-lower-case-y font))
(add-glyph #\z glyphs (make-glyph-lower-case-z font))
(add-glyph #\A glyphs (make-glyph-upper-case-a font))
(add-glyph #\B glyphs (make-glyph-upper-case-b font))
(add-glyph #\C glyphs (make-glyph-upper-case-c font))
(add-glyph #\D glyphs (make-glyph-upper-case-d font))
(add-glyph #\E glyphs (make-glyph-upper-case-e font))
(add-glyph #\F glyphs (make-glyph-upper-case-f font))
(add-glyph #\G glyphs (make-glyph-upper-case-g font))
(add-glyph #\H glyphs (make-glyph-upper-case-h font))
(add-glyph #\I glyphs (make-glyph-upper-case-i font))
(add-glyph #\J glyphs (make-glyph-upper-case-j font))
(add-glyph #\K glyphs (make-glyph-upper-case-k font))
(add-glyph #\L glyphs (make-glyph-upper-case-l font))
(add-glyph #\M glyphs (make-glyph-upper-case-m font))
(add-glyph #\N glyphs (make-glyph-upper-case-n font))
(add-glyph #\O glyphs (make-glyph-upper-case-o font))
(add-glyph #\P glyphs (make-glyph-upper-case-p font))
(add-glyph #\Q glyphs (make-glyph-upper-case-q font))
(add-glyph #\R glyphs (make-glyph-upper-case-r font))
(add-glyph #\S glyphs (make-glyph-upper-case-s font))
(add-glyph #\T glyphs (make-glyph-upper-case-t font))
(add-glyph #\U glyphs (make-glyph-upper-case-u font))
(add-glyph #\V glyphs (make-glyph-upper-case-v font))
(add-glyph #\W glyphs (make-glyph-upper-case-w font))
(add-glyph #\X glyphs (make-glyph-upper-case-x font))
(add-glyph #\Y glyphs (make-glyph-upper-case-y font))
(add-glyph #\Z glyphs (make-glyph-upper-case-z font))
(add-glyph #\! glyphs (make-glyph-exclamation-mark font))
(add-glyph #\" glyphs (make-glyph-double-quote font))
(add-glyph #\# glyphs (make-glyph-hash font))
(add-glyph #\. glyphs (make-glyph-period font))
(add-glyph #\, glyphs (make-glyph-comma font))
(add-glyph #\: glyphs (make-glyph-colon font))
(add-glyph #\? glyphs (make-glyph-question-mark font))
(add-glyph #\/ glyphs (make-glyph-slash font))
(add-glyph #\1 glyphs (make-glyph-digit-1 font))
(add-glyph #\2 glyphs (make-glyph-digit-2 font))
(add-glyph #\3 glyphs (make-glyph-digit-3 font))
(add-glyph #\4 glyphs (make-glyph-digit-4 font))
(add-glyph #\5 glyphs (make-glyph-digit-5 font))
(add-glyph #\6 glyphs (make-glyph-digit-6 font))
(add-glyph #\7 glyphs (make-glyph-digit-7 font))
(add-glyph #\8 glyphs (make-glyph-digit-8 font))
(add-glyph #\9 glyphs (make-glyph-digit-9 font))
(add-glyph #\0 glyphs (make-glyph-digit-0 font))
(add-glyph #\[ glyphs (make-glyph-left-bracket font))
(add-glyph #\\ glyphs (make-glyph-backslash font))
(add-glyph #\] glyphs (make-glyph-right-bracket font))
(add-glyph #\{ glyphs (make-glyph-left-brace font))
(add-glyph #\} glyphs (make-glyph-right-brace font))
font))
(defun find-glyph (font char)
(or (gethash char (glyphs font))
(gethash 'default (glyphs font))))
(defun kerning (font left-glyph right-glyph)
(or (gethash (cons (right-shape left-glyph)
(left-shape right-glyph))
(kerning-info font))
0))
(defun draw-text (text font x y glyph-mask-fun)
(flet ((show-glyph (glyph x y)
(let ((mask (mask glyph))
(x-offset (x-offset glyph))
(y-offset (y-offset glyph)))
(funcall glyph-mask-fun mask (+ x x-offset) (+ y y-offset)))))
(show-glyph (find-glyph font (aref text 0)) x y)
(loop for i from 1 below (length text)
do (let* ((previous-glyph (find-glyph font (aref text (1- i))))
(this-glyph (find-glyph font (aref text i)))
(advance (if (null previous-glyph)
(width font)
(+ (x-offset previous-glyph)
(array-dimension (mask previous-glyph) 1)
(* 2 (stroke-width font)))))
(kerning (if (or (null previous-glyph)
(null this-glyph))
0
(kerning font previous-glyph this-glyph))))
(incf x (- advance kerning))
(unless (null this-glyph)
(show-glyph this-glyph x y))))))
|
bea5078e0274c019839fb51e8bc58a0e042e902598775f141fa1855b7674f3ab | pfdietz/ansi-test | ensure-directories-exist.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Mon Jan 5 20:53:03 2004
Contains : Tests of ENSURE - DIRECTORIES - EXIST
(deftest ensure-directories-exist.1
(let* ((pn (make-pathname :name "ensure-directories-exist.txt"
:defaults *default-pathname-defaults*))
(results nil)
(verbosity
(with-output-to-string
(*standard-output*)
(setq results (multiple-value-list (ensure-directories-exist pn))))))
(values
(length results)
(equalt (truename pn) (truename (first results)))
(second results)
verbosity))
2 t nil "")
(deftest ensure-directories-exist.2
(with-open-file
(s "ensure-directories-exist.txt" :direction :input)
(let* ((results (multiple-value-list (ensure-directories-exist s))))
(values
(length results)
(equalt (truename (first results)) (truename s))
(second results))))
2 t nil)
(deftest ensure-directories-exist.3
(let ((s (open "ensure-directories-exist.txt" :direction :input)))
(close s)
(let* ((results (multiple-value-list (ensure-directories-exist s))))
(values
(length results)
(equalt (truename (first results)) (truename s))
(second results))))
2 t nil)
(deftest ensure-directories-exist.4
(let* ((pn (make-pathname :name "ensure-directories-exist.txt"
:defaults *default-pathname-defaults*))
(results nil)
(verbosity
(with-output-to-string
(*standard-output*)
(setq results (multiple-value-list
(ensure-directories-exist pn :verbose nil))))))
(values
(length results)
(equalt (truename pn) (truename (first results)))
(second results)
verbosity))
2 t nil "")
(deftest ensure-directories-exist.5
(let* ((pn (make-pathname :name "ensure-directories-exist.txt"
:defaults *default-pathname-defaults*))
(results nil)
(verbosity
(with-output-to-string
(*standard-output*)
(setq results (multiple-value-list
(ensure-directories-exist pn :verbose t))))))
(values
(length results)
(equalt (truename pn) (truename (first results)))
(second results)
verbosity))
2 t nil "")
(deftest ensure-directories-exist.6
(let* ((pn (make-pathname :name "ensure-directories-exist.txt"
:defaults *default-pathname-defaults*))
(results nil)
(verbosity
(with-output-to-string
(*standard-output*)
(setq results (multiple-value-list
(ensure-directories-exist
pn :allow-other-keys nil))))))
(values
(length results)
(equalt (truename pn) (truename (first results)))
(second results)
verbosity))
2 t nil "")
(deftest ensure-directories-exist.7
(let* ((pn (make-pathname :name "ensure-directories-exist.txt"
:defaults *default-pathname-defaults*))
(results nil)
(verbosity
(with-output-to-string
(*standard-output*)
(setq results (multiple-value-list
(ensure-directories-exist
pn :allow-other-keys t :nonsense t))))))
(values
(length results)
(equalt (truename pn) (truename (first results)))
(second results)
verbosity))
2 t nil "")
;;; Case where directory shouldn't exist
;; The directort ansi-tests/scratch must not exist before this
;; test is run
(deftest ensure-directories-exist.8
(let* ((subdir (make-pathname :directory '(:relative "scratch")
:defaults *default-pathname-defaults*))
(pn (make-pathname :name "foo" :type "txt"
:defaults subdir)))
(assert (not (probe-file pn)) ()
"Delete subdirectory scratch and its contents!")
(let* ((results nil)
(verbosity
(with-output-to-string
(*standard-output*)
(setq results (multiple-value-list (ensure-directories-exist pn)))))
(result-pn (first results))
(created (second results)))
;; Create the file and write to it
(with-open-file (*standard-output*
pn :direction :output :if-exists :error
:if-does-not-exist :create)
(print nil))
(values
(length results)
(notnot created)
(equalt pn result-pn)
(notnot (probe-file pn))
verbosity
)))
2 t t t "")
Specialized string tests
(deftest ensure-directories-exist.9
(do-special-strings
(str "ensure-directories-exist.txt" nil)
(let* ((results (multiple-value-list (ensure-directories-exist str))))
(assert (eql (length results) 2))
(assert (equalt (truename (first results)) (truename str)))
(assert (null (second results)))))
nil)
FIXME
Need to add a LPN test
(deftest ensure-directories-exist.error.1
(signals-error-always
(ensure-directories-exist
(make-pathname :directory '(:relative :wild)
:defaults *default-pathname-defaults*))
file-error)
t t)
(deftest ensure-directories-exist.error.2
(signals-error (ensure-directories-exist) program-error)
t)
| null | https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/files/ensure-directories-exist.lsp | lisp | -*- Mode: Lisp -*-
Case where directory shouldn't exist
The directort ansi-tests/scratch must not exist before this
test is run
Create the file and write to it | Author :
Created : Mon Jan 5 20:53:03 2004
Contains : Tests of ENSURE - DIRECTORIES - EXIST
(deftest ensure-directories-exist.1
(let* ((pn (make-pathname :name "ensure-directories-exist.txt"
:defaults *default-pathname-defaults*))
(results nil)
(verbosity
(with-output-to-string
(*standard-output*)
(setq results (multiple-value-list (ensure-directories-exist pn))))))
(values
(length results)
(equalt (truename pn) (truename (first results)))
(second results)
verbosity))
2 t nil "")
(deftest ensure-directories-exist.2
(with-open-file
(s "ensure-directories-exist.txt" :direction :input)
(let* ((results (multiple-value-list (ensure-directories-exist s))))
(values
(length results)
(equalt (truename (first results)) (truename s))
(second results))))
2 t nil)
(deftest ensure-directories-exist.3
(let ((s (open "ensure-directories-exist.txt" :direction :input)))
(close s)
(let* ((results (multiple-value-list (ensure-directories-exist s))))
(values
(length results)
(equalt (truename (first results)) (truename s))
(second results))))
2 t nil)
(deftest ensure-directories-exist.4
(let* ((pn (make-pathname :name "ensure-directories-exist.txt"
:defaults *default-pathname-defaults*))
(results nil)
(verbosity
(with-output-to-string
(*standard-output*)
(setq results (multiple-value-list
(ensure-directories-exist pn :verbose nil))))))
(values
(length results)
(equalt (truename pn) (truename (first results)))
(second results)
verbosity))
2 t nil "")
(deftest ensure-directories-exist.5
(let* ((pn (make-pathname :name "ensure-directories-exist.txt"
:defaults *default-pathname-defaults*))
(results nil)
(verbosity
(with-output-to-string
(*standard-output*)
(setq results (multiple-value-list
(ensure-directories-exist pn :verbose t))))))
(values
(length results)
(equalt (truename pn) (truename (first results)))
(second results)
verbosity))
2 t nil "")
(deftest ensure-directories-exist.6
(let* ((pn (make-pathname :name "ensure-directories-exist.txt"
:defaults *default-pathname-defaults*))
(results nil)
(verbosity
(with-output-to-string
(*standard-output*)
(setq results (multiple-value-list
(ensure-directories-exist
pn :allow-other-keys nil))))))
(values
(length results)
(equalt (truename pn) (truename (first results)))
(second results)
verbosity))
2 t nil "")
(deftest ensure-directories-exist.7
(let* ((pn (make-pathname :name "ensure-directories-exist.txt"
:defaults *default-pathname-defaults*))
(results nil)
(verbosity
(with-output-to-string
(*standard-output*)
(setq results (multiple-value-list
(ensure-directories-exist
pn :allow-other-keys t :nonsense t))))))
(values
(length results)
(equalt (truename pn) (truename (first results)))
(second results)
verbosity))
2 t nil "")
(deftest ensure-directories-exist.8
(let* ((subdir (make-pathname :directory '(:relative "scratch")
:defaults *default-pathname-defaults*))
(pn (make-pathname :name "foo" :type "txt"
:defaults subdir)))
(assert (not (probe-file pn)) ()
"Delete subdirectory scratch and its contents!")
(let* ((results nil)
(verbosity
(with-output-to-string
(*standard-output*)
(setq results (multiple-value-list (ensure-directories-exist pn)))))
(result-pn (first results))
(created (second results)))
(with-open-file (*standard-output*
pn :direction :output :if-exists :error
:if-does-not-exist :create)
(print nil))
(values
(length results)
(notnot created)
(equalt pn result-pn)
(notnot (probe-file pn))
verbosity
)))
2 t t t "")
Specialized string tests
(deftest ensure-directories-exist.9
(do-special-strings
(str "ensure-directories-exist.txt" nil)
(let* ((results (multiple-value-list (ensure-directories-exist str))))
(assert (eql (length results) 2))
(assert (equalt (truename (first results)) (truename str)))
(assert (null (second results)))))
nil)
FIXME
Need to add a LPN test
(deftest ensure-directories-exist.error.1
(signals-error-always
(ensure-directories-exist
(make-pathname :directory '(:relative :wild)
:defaults *default-pathname-defaults*))
file-error)
t t)
(deftest ensure-directories-exist.error.2
(signals-error (ensure-directories-exist) program-error)
t)
|
c1385cbef3105ecfcc2d1d4b749f9c1d5eae8b775cfd832d6e1fe199edf96c33 | kaznum/programming_in_ocaml_exercise | checkbox.ml | open Tk
let top = openTk()
let tv = Textvariable.create ()
let cb = Checkbutton.create top
~text:"Press me!" ~variable:tv ~onvalue:"on" ~offvalue:"off"
let () =
Checkbutton.configure cb
~command:
(fun () -> Checkbutton.flash cb; print_endline (Textvariable.get tv));
pack [cb] ~side:`Top;
mainLoop()
| null | https://raw.githubusercontent.com/kaznum/programming_in_ocaml_exercise/6f6a5d62a7a87a1c93561db88f08ae4e445b7d4e/ch15/checkbox.ml | ocaml | open Tk
let top = openTk()
let tv = Textvariable.create ()
let cb = Checkbutton.create top
~text:"Press me!" ~variable:tv ~onvalue:"on" ~offvalue:"off"
let () =
Checkbutton.configure cb
~command:
(fun () -> Checkbutton.flash cb; print_endline (Textvariable.get tv));
pack [cb] ~side:`Top;
mainLoop()
| |
2a612fe627ae9e3e98f8d30cf769d9f5448fe6bfe35d52519ac8320aa8bf538c | pirapira/coq2rust | ascii_syntax.ml | (***********************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - Rocquencourt & LRI - CNRS - Orsay
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(***********************************************************************)
open Pp
open Errors
open Util
open Names
open Glob_term
open Globnames
open Coqlib
exception Non_closed_ascii
let make_dir l = DirPath.make (List.rev_map Id.of_string l)
let make_kn dir id = Globnames.encode_mind (make_dir dir) (Id.of_string id)
let make_path dir id = Libnames.make_path (make_dir dir) (Id.of_string id)
let ascii_module = ["Coq";"Strings";"Ascii"]
let ascii_path = make_path ascii_module "ascii"
let ascii_kn = make_kn ascii_module "ascii"
let path_of_Ascii = ((ascii_kn,0),1)
let static_glob_Ascii = ConstructRef path_of_Ascii
let make_reference id = find_reference "Ascii interpretation" ascii_module id
let glob_Ascii = lazy (make_reference "Ascii")
open Lazy
let interp_ascii dloc p =
let rec aux n p =
if Int.equal n 0 then [] else
let mp = p mod 2 in
GRef (dloc,(if Int.equal mp 0 then glob_false else glob_true),None)
:: (aux (n-1) (p/2)) in
GApp (dloc,GRef(dloc,force glob_Ascii,None), aux 8 p)
let interp_ascii_string dloc s =
let p =
if Int.equal (String.length s) 1 then int_of_char s.[0]
else
if Int.equal (String.length s) 3 && is_digit s.[0] && is_digit s.[1] && is_digit s.[2]
then int_of_string s
else
user_err_loc (dloc,"interp_ascii_string",
str "Expects a single character or a three-digits ascii code.") in
interp_ascii dloc p
let uninterp_ascii r =
let rec uninterp_bool_list n = function
| [] when Int.equal n 0 -> 0
| GRef (_,k,_)::l when Globnames.eq_gr k glob_true -> 1+2*(uninterp_bool_list (n-1) l)
| GRef (_,k,_)::l when Globnames.eq_gr k glob_false -> 2*(uninterp_bool_list (n-1) l)
| _ -> raise Non_closed_ascii in
try
let aux = function
| GApp (_,GRef (_,k,_),l) when Globnames.eq_gr k (force glob_Ascii) -> uninterp_bool_list 8 l
| _ -> raise Non_closed_ascii in
Some (aux r)
with
Non_closed_ascii -> None
let make_ascii_string n =
if n>=32 && n<=126 then String.make 1 (char_of_int n)
else Printf.sprintf "%03d" n
let uninterp_ascii_string r = Option.map make_ascii_string (uninterp_ascii r)
let _ =
Notation.declare_string_interpreter "char_scope"
(ascii_path,ascii_module)
interp_ascii_string
([GRef (Loc.ghost,static_glob_Ascii,None)], uninterp_ascii_string, true)
| null | https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/plugins/syntax/ascii_syntax.ml | ocaml | *********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
********************************************************************* | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - Rocquencourt & LRI - CNRS - Orsay
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Pp
open Errors
open Util
open Names
open Glob_term
open Globnames
open Coqlib
exception Non_closed_ascii
let make_dir l = DirPath.make (List.rev_map Id.of_string l)
let make_kn dir id = Globnames.encode_mind (make_dir dir) (Id.of_string id)
let make_path dir id = Libnames.make_path (make_dir dir) (Id.of_string id)
let ascii_module = ["Coq";"Strings";"Ascii"]
let ascii_path = make_path ascii_module "ascii"
let ascii_kn = make_kn ascii_module "ascii"
let path_of_Ascii = ((ascii_kn,0),1)
let static_glob_Ascii = ConstructRef path_of_Ascii
let make_reference id = find_reference "Ascii interpretation" ascii_module id
let glob_Ascii = lazy (make_reference "Ascii")
open Lazy
let interp_ascii dloc p =
let rec aux n p =
if Int.equal n 0 then [] else
let mp = p mod 2 in
GRef (dloc,(if Int.equal mp 0 then glob_false else glob_true),None)
:: (aux (n-1) (p/2)) in
GApp (dloc,GRef(dloc,force glob_Ascii,None), aux 8 p)
let interp_ascii_string dloc s =
let p =
if Int.equal (String.length s) 1 then int_of_char s.[0]
else
if Int.equal (String.length s) 3 && is_digit s.[0] && is_digit s.[1] && is_digit s.[2]
then int_of_string s
else
user_err_loc (dloc,"interp_ascii_string",
str "Expects a single character or a three-digits ascii code.") in
interp_ascii dloc p
let uninterp_ascii r =
let rec uninterp_bool_list n = function
| [] when Int.equal n 0 -> 0
| GRef (_,k,_)::l when Globnames.eq_gr k glob_true -> 1+2*(uninterp_bool_list (n-1) l)
| GRef (_,k,_)::l when Globnames.eq_gr k glob_false -> 2*(uninterp_bool_list (n-1) l)
| _ -> raise Non_closed_ascii in
try
let aux = function
| GApp (_,GRef (_,k,_),l) when Globnames.eq_gr k (force glob_Ascii) -> uninterp_bool_list 8 l
| _ -> raise Non_closed_ascii in
Some (aux r)
with
Non_closed_ascii -> None
let make_ascii_string n =
if n>=32 && n<=126 then String.make 1 (char_of_int n)
else Printf.sprintf "%03d" n
let uninterp_ascii_string r = Option.map make_ascii_string (uninterp_ascii r)
let _ =
Notation.declare_string_interpreter "char_scope"
(ascii_path,ascii_module)
interp_ascii_string
([GRef (Loc.ghost,static_glob_Ascii,None)], uninterp_ascii_string, true)
|
fa3890b532ad9a2ee2bbc8120b2a3b067ba7689017a7f8fff521cf4d80285308 | binghe/cl-net-snmp | clozure-mib.lisp | ;;;; -*- Mode: Lisp -*-
Generated from MIB : LISP;CLOZURE - MIB.TXT by CL - NET - SNMP
(in-package :asn.1)
(eval-when (:load-toplevel :execute)
(setf *current-module* '|Clozure-MIB|))
(defpackage :|ASN.1/Clozure-MIB|
(:nicknames :|Clozure-MIB|)
(:use :common-lisp :asn.1)
(:import-from :|ASN.1/SNMPv2-SMI| module-identity object-type
object-identity notification-type |enterprises|)
(:import-from :asn.1/lisp-mib |commonLisp|))
(in-package :|Clozure-MIB|)
(defoid |ccl| (|commonLisp| 8)
(:type 'module-identity)
(:description "The MIB module for Clozure CL"))
(in-package :asn.1)
(eval-when (:load-toplevel :execute)
(pushnew '|Clozure-MIB| *mib-modules*)
(setf *current-module* nil))
| null | https://raw.githubusercontent.com/binghe/cl-net-snmp/3cf053bce75734097f0d7e2245a53fa0c45f5e05/compiled-mibs/clozure-mib.lisp | lisp | -*- Mode: Lisp -*-
CLOZURE - MIB.TXT by CL - NET - SNMP | (in-package :asn.1)
(eval-when (:load-toplevel :execute)
(setf *current-module* '|Clozure-MIB|))
(defpackage :|ASN.1/Clozure-MIB|
(:nicknames :|Clozure-MIB|)
(:use :common-lisp :asn.1)
(:import-from :|ASN.1/SNMPv2-SMI| module-identity object-type
object-identity notification-type |enterprises|)
(:import-from :asn.1/lisp-mib |commonLisp|))
(in-package :|Clozure-MIB|)
(defoid |ccl| (|commonLisp| 8)
(:type 'module-identity)
(:description "The MIB module for Clozure CL"))
(in-package :asn.1)
(eval-when (:load-toplevel :execute)
(pushnew '|Clozure-MIB| *mib-modules*)
(setf *current-module* nil))
|
5e96dce1a160a14f0ced4f4699061051ba02d8625d5cf8405f4ac550980690b8 | robert-strandh/SICL | variable-description.lisp | (cl:in-package #:sicl-environment)
;;; Instances of this class are used to put compile-time information
;;; about variables in the compilation environment.
(defclass variable-description ()
((%type :initarg :type :initform t :reader type)))
(defclass special-variable-description (variable-description)
())
(defun make-special-variable-description ()
(make-instance 'special-variable-description))
(defclass constant-variable-description (variable-description)
((%value :initarg :value :reader value)))
(defun make-constant-variable-description (value)
(make-instance 'constant-variable-description
:value value))
(defgeneric variable-description
(environment variable-name))
(defmethod variable-description
(environment variable-name)
(let ((client (client environment)))
(clostrum:variable-description client environment variable-name)))
(defgeneric (setf variable-description)
(description environment variable-name))
(defmethod (setf variable-description)
(description environment variable-name)
(let ((client (client environment)))
(setf (clostrum:variable-description client environment variable-name)
description)))
| null | https://raw.githubusercontent.com/robert-strandh/SICL/87f626ff6d00526f33971e0d533024f5c6b06c1f/Code/Environment-Clostrum/variable-description.lisp | lisp | Instances of this class are used to put compile-time information
about variables in the compilation environment. | (cl:in-package #:sicl-environment)
(defclass variable-description ()
((%type :initarg :type :initform t :reader type)))
(defclass special-variable-description (variable-description)
())
(defun make-special-variable-description ()
(make-instance 'special-variable-description))
(defclass constant-variable-description (variable-description)
((%value :initarg :value :reader value)))
(defun make-constant-variable-description (value)
(make-instance 'constant-variable-description
:value value))
(defgeneric variable-description
(environment variable-name))
(defmethod variable-description
(environment variable-name)
(let ((client (client environment)))
(clostrum:variable-description client environment variable-name)))
(defgeneric (setf variable-description)
(description environment variable-name))
(defmethod (setf variable-description)
(description environment variable-name)
(let ((client (client environment)))
(setf (clostrum:variable-description client environment variable-name)
description)))
|
7d75cb8e85ed68c08ac253d962a5153e2607cbc7b3134483ce460379019f8c56 | Ekdohibs/joujou | Apply.ml | (* This intermediate language describes the result of defunctionalization.
It retains the key features of the previous calculus, [Tail], in that
the ordering of computations is explicit and every function call is a
tail call. Furthermore, lambda-abstractions disappear. A memory block
[Con] now contains an integer tag followed with a number of fields,
which hold values. [TailCall] and [ContCall] remain, but call a function
described by a memory block.
A number of (closed, mutually recursive)
functions can be defined at the top level. *)
type tag =
int
and variable =
Atom.atom
and binop = Tail.binop =
| OpAdd
| OpSub
| OpMul
| OpDiv
and value = Tail.value =
| VVar of variable
| VLit of int
| VBinOp of value * binop * value
(* A block contains an integer tag, followed with a number of fields. *)
and block =
| Con of tag * value list
(* The construct [Swi (v, branches)] reads the integer tag stored in the
memory block at address [v] and performs a case analysis on this tag,
transferring control to the appropriate branch. (The value [v] should be a
pointer to a memory block.) *)
and term =
| Exit
| TailCall of value * value list
| ContCall of value * value * value list
| Print of value * term
| LetVal of variable * value * term
| LetBlo of variable * block * term
| IfZero of value * term * term
| Swi of value * branch list * term option
(* A branch [tag xs -> t] is labeled with an integer tag [tag], and is
executed if the memory block carries this tag. The variables [xs] are
then bounds to the fields of the memory block. (The length of the list
[xs] should be the number of fields of the memory block.) *)
and branch =
| Branch of tag * variable list * term
(* A toplevel function declaration mentions the function's name, tag, free
variables, formal parameters, and body. *)
and function_declaration =
| Fun of variable * tag * variable list * variable list * term
(* A complete program consits of a set of toplevel function declarations
and a term (the "main program"). The functions are considered mutually
recursive: every function may refer to every function. *)
and program =
| Prog of function_declaration list * term
[@@deriving show { with_path = false }]
(* -------------------------------------------------------------------------- *)
(* Constructor functions. *)
let vvar =
Tail.vvar
let vvars =
Tail.vvars
(* [let x_1 = v_1 in ... let x_n = v_n in t] *)
let rec sequential_let (xs : variable list) (vs : value list) (t : term) =
match xs, vs with
| [], [] ->
t
| x :: xs, v :: vs ->
LetVal (x, v, sequential_let xs vs t)
| _ ->
assert false
(* [let x_1 = v_1 and ... x_n = v_n in t] *)
let parallel_let (xs : variable list) (vs : value list) (t : term) =
assert (List.length xs = List.length vs);
assert (Atom.Set.disjoint (Atom.Set.of_list xs) (Tail.fv_values vs));
sequential_let xs vs t
let gen_tag =
let c = ref 0 in fun () -> (incr c; !c - 1)
| null | https://raw.githubusercontent.com/Ekdohibs/joujou/02ef5052f93623da99ed2e871a59c99a5e6026a1/Apply.ml | ocaml | This intermediate language describes the result of defunctionalization.
It retains the key features of the previous calculus, [Tail], in that
the ordering of computations is explicit and every function call is a
tail call. Furthermore, lambda-abstractions disappear. A memory block
[Con] now contains an integer tag followed with a number of fields,
which hold values. [TailCall] and [ContCall] remain, but call a function
described by a memory block.
A number of (closed, mutually recursive)
functions can be defined at the top level.
A block contains an integer tag, followed with a number of fields.
The construct [Swi (v, branches)] reads the integer tag stored in the
memory block at address [v] and performs a case analysis on this tag,
transferring control to the appropriate branch. (The value [v] should be a
pointer to a memory block.)
A branch [tag xs -> t] is labeled with an integer tag [tag], and is
executed if the memory block carries this tag. The variables [xs] are
then bounds to the fields of the memory block. (The length of the list
[xs] should be the number of fields of the memory block.)
A toplevel function declaration mentions the function's name, tag, free
variables, formal parameters, and body.
A complete program consits of a set of toplevel function declarations
and a term (the "main program"). The functions are considered mutually
recursive: every function may refer to every function.
--------------------------------------------------------------------------
Constructor functions.
[let x_1 = v_1 in ... let x_n = v_n in t]
[let x_1 = v_1 and ... x_n = v_n in t] |
type tag =
int
and variable =
Atom.atom
and binop = Tail.binop =
| OpAdd
| OpSub
| OpMul
| OpDiv
and value = Tail.value =
| VVar of variable
| VLit of int
| VBinOp of value * binop * value
and block =
| Con of tag * value list
and term =
| Exit
| TailCall of value * value list
| ContCall of value * value * value list
| Print of value * term
| LetVal of variable * value * term
| LetBlo of variable * block * term
| IfZero of value * term * term
| Swi of value * branch list * term option
and branch =
| Branch of tag * variable list * term
and function_declaration =
| Fun of variable * tag * variable list * variable list * term
and program =
| Prog of function_declaration list * term
[@@deriving show { with_path = false }]
let vvar =
Tail.vvar
let vvars =
Tail.vvars
let rec sequential_let (xs : variable list) (vs : value list) (t : term) =
match xs, vs with
| [], [] ->
t
| x :: xs, v :: vs ->
LetVal (x, v, sequential_let xs vs t)
| _ ->
assert false
let parallel_let (xs : variable list) (vs : value list) (t : term) =
assert (List.length xs = List.length vs);
assert (Atom.Set.disjoint (Atom.Set.of_list xs) (Tail.fv_values vs));
sequential_let xs vs t
let gen_tag =
let c = ref 0 in fun () -> (incr c; !c - 1)
|
21fa6761995fa7de3288a434a6f1bfd8b7868bdfbd756c960427305e533789ef | racket/racket7 | syntax.rkt | #lang racket/base
(require "test-util.rkt")
(parameterize ([current-contract-namespace
(make-basic-contract-namespace)])
(test/pos-blame
'syntax/c1
'(contract (syntax/c boolean?)
#'x
'pos
'neg))
(test/spec-passed
'syntax/c2
'(contract (syntax/c symbol?)
#'x
'pos
'neg))
(test/no-error '(syntax/c (list/c #f)))
(contract-error-test 'syntax/c-non-flat '(syntax/c (vector/c #f))
(λ (x) (regexp-match? #rx"flat-contract[?]" (exn-message x)))))
| null | https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/pkgs/racket-test/tests/racket/contract/syntax.rkt | racket | #lang racket/base
(require "test-util.rkt")
(parameterize ([current-contract-namespace
(make-basic-contract-namespace)])
(test/pos-blame
'syntax/c1
'(contract (syntax/c boolean?)
#'x
'pos
'neg))
(test/spec-passed
'syntax/c2
'(contract (syntax/c symbol?)
#'x
'pos
'neg))
(test/no-error '(syntax/c (list/c #f)))
(contract-error-test 'syntax/c-non-flat '(syntax/c (vector/c #f))
(λ (x) (regexp-match? #rx"flat-contract[?]" (exn-message x)))))
| |
7999522f9086ad9d15af649c6accbed4ebb3f117995ec774b6bf9cf90b8be769 | nickzuber/infrared | ast_utils.ml | *
* Copyright ( c ) 2013 - present , Facebook , Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open Ast
type binding = Loc.t * string
let rec bindings_of_pattern =
let open Pattern in
let property acc =
let open Object in
function
| Property (_, { Property.pattern = (_, p); _ })
| RestProperty (_, { RestProperty.argument = (_, p) }) ->
bindings_of_pattern acc p
in
let element acc =
let open Array in
function
| None -> acc
| Some (Element (_, p))
| Some (RestElement (_, { RestElement.argument = (_, p) })) ->
bindings_of_pattern acc p
in
fun acc ->
function
| Identifier { Identifier.name; _ } ->
name::acc
| Object { Object.properties; _ } ->
List.fold_left property acc properties
| Array { Array.elements; _ } ->
List.fold_left element acc elements
| Assignment { Assignment.left = (_, p); _ } ->
bindings_of_pattern acc p
| Expression _ ->
failwith "expression pattern"
let bindings_of_variable_declarations =
let open Ast.Statement.VariableDeclaration in
List.fold_left (fun acc -> function
| _, { Declarator.id = (_, pattern); _ } ->
bindings_of_pattern acc pattern
) []
let partition_directives statements =
let open Ast.Statement in
let rec helper directives = function
| ((_, Expression { Expression.directive = Some _; _ }) as directive)::rest ->
helper (directive::directives) rest
| rest -> List.rev directives, rest
in
helper [] statements
| null | https://raw.githubusercontent.com/nickzuber/infrared/b67bc728458047650439649605af7a8072357b3c/InfraredParser/flow_parser/lib/ast_utils.ml | ocaml | *
* Copyright ( c ) 2013 - present , Facebook , Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open Ast
type binding = Loc.t * string
let rec bindings_of_pattern =
let open Pattern in
let property acc =
let open Object in
function
| Property (_, { Property.pattern = (_, p); _ })
| RestProperty (_, { RestProperty.argument = (_, p) }) ->
bindings_of_pattern acc p
in
let element acc =
let open Array in
function
| None -> acc
| Some (Element (_, p))
| Some (RestElement (_, { RestElement.argument = (_, p) })) ->
bindings_of_pattern acc p
in
fun acc ->
function
| Identifier { Identifier.name; _ } ->
name::acc
| Object { Object.properties; _ } ->
List.fold_left property acc properties
| Array { Array.elements; _ } ->
List.fold_left element acc elements
| Assignment { Assignment.left = (_, p); _ } ->
bindings_of_pattern acc p
| Expression _ ->
failwith "expression pattern"
let bindings_of_variable_declarations =
let open Ast.Statement.VariableDeclaration in
List.fold_left (fun acc -> function
| _, { Declarator.id = (_, pattern); _ } ->
bindings_of_pattern acc pattern
) []
let partition_directives statements =
let open Ast.Statement in
let rec helper directives = function
| ((_, Expression { Expression.directive = Some _; _ }) as directive)::rest ->
helper (directive::directives) rest
| rest -> List.rev directives, rest
in
helper [] statements
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.