_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
|
---|---|---|---|---|---|---|---|---|
48d6bf8077860540504e7d3f8fc4bc4580cb8d92e18f70c09528eb51db4088a1 | bvaugon/ocapic | stream.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1997 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. *)
(* *)
(**************************************************************************)
(** Streams and parsers. *)
type 'a t
(** The type of streams holding values of type ['a]. *)
exception Failure
* Raised by parsers when none of the first components of the stream
patterns is accepted .
patterns is accepted. *)
exception Error of string
* Raised by parsers when the first component of a stream pattern is
accepted , but one of the following components is rejected .
accepted, but one of the following components is rejected. *)
* { 6 Stream builders }
val from : (int -> 'a option) -> 'a t
* [ Stream.from f ] returns a stream built from the function [ f ] .
To create a new stream element , the function [ f ] is called with
the current stream count . The user function [ f ] must return either
[ Some < value > ] for a value or [ None ] to specify the end of the
stream .
Do note that the indices passed to [ f ] may not start at [ 0 ] in the
general case . For example , [ [ < ' 0 ; ' 1 ; Stream.from f > ] ] would call
[ f ] the first time with count [ 2 ] .
To create a new stream element, the function [f] is called with
the current stream count. The user function [f] must return either
[Some <value>] for a value or [None] to specify the end of the
stream.
Do note that the indices passed to [f] may not start at [0] in the
general case. For example, [[< '0; '1; Stream.from f >]] would call
[f] the first time with count [2].
*)
val of_list : 'a list -> 'a t
(** Return the stream holding the elements of the list in the same
order. *)
val of_string : string -> char t
(** Return the stream of the characters of the string parameter. *)
val of_bytes : bytes -> char t
* Return the stream of the characters of the bytes parameter .
@since 4.02.0
@since 4.02.0 *)
* { 6 Stream iterator }
val iter : ('a -> unit) -> 'a t -> unit
(** [Stream.iter f s] scans the whole stream s, applying function [f]
in turn to each stream element encountered. *)
* { 6 Predefined parsers }
val next : 'a t -> 'a
* Return the first element of the stream and remove it from the
stream . Raise Stream . Failure if the stream is empty .
stream. Raise Stream.Failure if the stream is empty. *)
val empty : 'a t -> unit
(** Return [()] if the stream is empty, else raise [Stream.Failure]. *)
* { 6 Useful functions }
val peek : 'a t -> 'a option
* Return [ Some ] of " the first element " of the stream , or [ None ] if
the stream is empty .
the stream is empty. *)
val junk : 'a t -> unit
* Remove the first element of the stream , possibly unfreezing
it before .
it before. *)
val count : 'a t -> int
(** Return the current count of the stream elements, i.e. the number
of the stream elements discarded. *)
val npeek : int -> 'a t -> 'a list
* [ npeek n ] returns the list of the [ n ] first elements of
the stream , or all its remaining elements if less than [ n ]
elements are available .
the stream, or all its remaining elements if less than [n]
elements are available. *)
(**/**)
(* The following is for system use only. Do not call directly. *)
val iapp : 'a t -> 'a t -> 'a t
val icons : 'a -> 'a t -> 'a t
val ising : 'a -> 'a t
val lapp : (unit -> 'a t) -> 'a t -> 'a t
val lcons : (unit -> 'a) -> 'a t -> 'a t
val lsing : (unit -> 'a) -> 'a t
val sempty : 'a t
val slazy : (unit -> 'a t) -> 'a t
| null | https://raw.githubusercontent.com/bvaugon/ocapic/a14cd9ec3f5022aeb5fe2264d595d7e8f1ddf58a/lib/stream.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.
************************************************************************
* Streams and parsers.
* The type of streams holding values of type ['a].
* Return the stream holding the elements of the list in the same
order.
* Return the stream of the characters of the string parameter.
* [Stream.iter f s] scans the whole stream s, applying function [f]
in turn to each stream element encountered.
* Return [()] if the stream is empty, else raise [Stream.Failure].
* Return the current count of the stream elements, i.e. the number
of the stream elements discarded.
*/*
The following is for system use only. Do not call directly. | , projet Cristal , INRIA Rocquencourt
Copyright 1997 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
type 'a t
exception Failure
* Raised by parsers when none of the first components of the stream
patterns is accepted .
patterns is accepted. *)
exception Error of string
* Raised by parsers when the first component of a stream pattern is
accepted , but one of the following components is rejected .
accepted, but one of the following components is rejected. *)
* { 6 Stream builders }
val from : (int -> 'a option) -> 'a t
* [ Stream.from f ] returns a stream built from the function [ f ] .
To create a new stream element , the function [ f ] is called with
the current stream count . The user function [ f ] must return either
[ Some < value > ] for a value or [ None ] to specify the end of the
stream .
Do note that the indices passed to [ f ] may not start at [ 0 ] in the
general case . For example , [ [ < ' 0 ; ' 1 ; Stream.from f > ] ] would call
[ f ] the first time with count [ 2 ] .
To create a new stream element, the function [f] is called with
the current stream count. The user function [f] must return either
[Some <value>] for a value or [None] to specify the end of the
stream.
Do note that the indices passed to [f] may not start at [0] in the
general case. For example, [[< '0; '1; Stream.from f >]] would call
[f] the first time with count [2].
*)
val of_list : 'a list -> 'a t
val of_string : string -> char t
val of_bytes : bytes -> char t
* Return the stream of the characters of the bytes parameter .
@since 4.02.0
@since 4.02.0 *)
* { 6 Stream iterator }
val iter : ('a -> unit) -> 'a t -> unit
* { 6 Predefined parsers }
val next : 'a t -> 'a
* Return the first element of the stream and remove it from the
stream . Raise Stream . Failure if the stream is empty .
stream. Raise Stream.Failure if the stream is empty. *)
val empty : 'a t -> unit
* { 6 Useful functions }
val peek : 'a t -> 'a option
* Return [ Some ] of " the first element " of the stream , or [ None ] if
the stream is empty .
the stream is empty. *)
val junk : 'a t -> unit
* Remove the first element of the stream , possibly unfreezing
it before .
it before. *)
val count : 'a t -> int
val npeek : int -> 'a t -> 'a list
* [ npeek n ] returns the list of the [ n ] first elements of
the stream , or all its remaining elements if less than [ n ]
elements are available .
the stream, or all its remaining elements if less than [n]
elements are available. *)
val iapp : 'a t -> 'a t -> 'a t
val icons : 'a -> 'a t -> 'a t
val ising : 'a -> 'a t
val lapp : (unit -> 'a t) -> 'a t -> 'a t
val lcons : (unit -> 'a) -> 'a t -> 'a t
val lsing : (unit -> 'a) -> 'a t
val sempty : 'a t
val slazy : (unit -> 'a t) -> 'a t
|
40e4d9bb9cb7f6617cf76774b8b8c1f5d283bd72cfa0f615ebe92bf5432b219b | zoomhub/zoomhub | LogLevel.hs | module ZoomHub.Log.LogLevel
( LogLevel (..),
parse,
)
where
data LogLevel
= Debug
| Info
| Warning
| Error
deriving (Eq, Ord)
instance Show LogLevel where
show Debug = "debug"
show Info = "info"
show Warning = "warning"
show Error = "error"
parse :: String -> Maybe LogLevel
parse "debug" = Just Debug
parse "info" = Just Info
parse "warning" = Just Warning
parse "error" = Just Error
parse _ = Nothing
| null | https://raw.githubusercontent.com/zoomhub/zoomhub/2c97e96af0dc2f033793f3d41fc38fea8dff867b/src/ZoomHub/Log/LogLevel.hs | haskell | module ZoomHub.Log.LogLevel
( LogLevel (..),
parse,
)
where
data LogLevel
= Debug
| Info
| Warning
| Error
deriving (Eq, Ord)
instance Show LogLevel where
show Debug = "debug"
show Info = "info"
show Warning = "warning"
show Error = "error"
parse :: String -> Maybe LogLevel
parse "debug" = Just Debug
parse "info" = Just Info
parse "warning" = Just Warning
parse "error" = Just Error
parse _ = Nothing
|
|
e98ba95d1a972363153f1774a794fc6e646a3ba3b283c67a5a00767c5298df9d | acl2/acl2 | (FOO
(197 91 (:REWRITE DEFAULT-+-2))
(127 91 (:REWRITE DEFAULT-+-1))
(72 18 (:REWRITE COMMUTATIVITY-OF-+))
(72 18 (:DEFINITION INTEGER-ABS))
(72 9 (:DEFINITION LENGTH))
(45 9 (:DEFINITION LEN))
(31 23 (:REWRITE DEFAULT-<-2))
(27 23 (:REWRITE DEFAULT-<-1))
(18 18 (:REWRITE DEFAULT-UNARY-MINUS))
(14 14 (:REWRITE DEFAULT-CAR))
(9 9 (:TYPE-PRESCRIPTION LEN))
(9 9 (:REWRITE DEFAULT-REALPART))
(9 9 (:REWRITE DEFAULT-NUMERATOR))
(9 9 (:REWRITE DEFAULT-IMAGPART))
(9 9 (:REWRITE DEFAULT-DENOMINATOR))
(9 9 (:REWRITE DEFAULT-COERCE-2))
(9 9 (:REWRITE DEFAULT-COERCE-1))
(3 3 (:LINEAR ACL2-COUNT-CAR-CDR-LINEAR))
)
| null | https://raw.githubusercontent.com/acl2/acl2/f64742cc6d41c35f9d3f94e154cd5fd409105d34/books/kestrel/std/system/.sys/guard-theorem-no-simplify-dollar-tests%40useless-runes.lsp | lisp | (FOO
(197 91 (:REWRITE DEFAULT-+-2))
(127 91 (:REWRITE DEFAULT-+-1))
(72 18 (:REWRITE COMMUTATIVITY-OF-+))
(72 18 (:DEFINITION INTEGER-ABS))
(72 9 (:DEFINITION LENGTH))
(45 9 (:DEFINITION LEN))
(31 23 (:REWRITE DEFAULT-<-2))
(27 23 (:REWRITE DEFAULT-<-1))
(18 18 (:REWRITE DEFAULT-UNARY-MINUS))
(14 14 (:REWRITE DEFAULT-CAR))
(9 9 (:TYPE-PRESCRIPTION LEN))
(9 9 (:REWRITE DEFAULT-REALPART))
(9 9 (:REWRITE DEFAULT-NUMERATOR))
(9 9 (:REWRITE DEFAULT-IMAGPART))
(9 9 (:REWRITE DEFAULT-DENOMINATOR))
(9 9 (:REWRITE DEFAULT-COERCE-2))
(9 9 (:REWRITE DEFAULT-COERCE-1))
(3 3 (:LINEAR ACL2-COUNT-CAR-CDR-LINEAR))
)
|
||
b6968831e97422bd3315f1d087a150657c8315fa87c3d784439f3ad13c294164 | UU-ComputerScience/uu-cco | TcArithBool.hs | import CCO.ArithBool (checkTy)
import CCO.Component (component, printer, ioWrap)
import CCO.Tree (parser, Tree (fromTree, toTree))
import Control.Arrow (Arrow (arr), (>>>))
main = ioWrap $ parser >>> component toTree >>>
component checkTy >>>
arr fromTree >>> printer | null | https://raw.githubusercontent.com/UU-ComputerScience/uu-cco/cca433c8a6f4d27407800404dea80c08fd567093/uu-cco-examples/src/TcArithBool.hs | haskell | import CCO.ArithBool (checkTy)
import CCO.Component (component, printer, ioWrap)
import CCO.Tree (parser, Tree (fromTree, toTree))
import Control.Arrow (Arrow (arr), (>>>))
main = ioWrap $ parser >>> component toTree >>>
component checkTy >>>
arr fromTree >>> printer |
|
51709bf5c9ab54f7c0d9020b722be65e71569b2e3bf590e8c0fbbad357e5b127 | ygrek/mldonkey | url.ml | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
mldonkey is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You should have received a copy of the GNU General Public License
along with mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
mldonkey is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Buffer
type url = {
proto : string;
server : string;
port : int;
full_file : string;
short_file : string;
user : string;
passwd : string;
args : (string*string) list;
string : string;
}
(* encode using RFC 1738 form *)
let encode s =
let pos = ref 0 in
let len = String.length s in
let res = String.create (3*len) in
let hexa_digit x =
if x >= 10 then Char.chr (Char.code 'A' + x - 10)
else Char.chr (Char.code '0' + x) in
for i=0 to len-1 do
match s.[i] with
| 'a'..'z' | 'A'..'Z' | '0'..'9' | '.' | '-' | '*' | '_' | '\''| '(' | ')'->
res.[!pos] <- s.[i]; incr pos
| c ->
res.[!pos] <- '%';
res.[!pos+1] <- hexa_digit (Char.code c / 16);
res.[!pos+2] <- hexa_digit (Char.code c mod 16);
pos := !pos + 3
done;
String.sub res 0 !pos
* decodes a sting according RFC 1738
or x - www - form - urlencoded ( ' + ' with ' ' )
@param raw true use RFC 1738
@param string string to decode
or x-www-form-urlencoded ('+' with ' ')
@param raw true use RFC 1738
@param string string to decode
*)
let decode ?(raw=true) s =
let len = String.length s in
let r = Buffer.create len in
let rec iter i =
if i < len then
match s.[i] with
| '%' ->
let n =
try
int_of_string with leading " 0x " , string is read hexadecimal
Buffer.add_char r (char_of_int (int_of_string ("0x" ^ (String.sub s (i+1) 2))));
3
with _ ->
Buffer.add_char r '%';
1
in
iter (i+n)
(* if not raw decode '+' -> ' ' else don't change char *)
| '+' -> let c = if raw then '+' else ' ' in
Buffer.add_char r c; iter (i+1)
| c -> Buffer.add_char r c; iter (i+1)
in
iter 0;
Buffer.contents r
let to_string url =
let res = Buffer.create 80 in
add_string res url.proto;
add_string res "://";
if url.user <> "" || url.passwd <> "" then begin
add_string res url.user;
add_string res ":";
add_string res url.passwd;
add_string res "@";
end;
add_string res url.server;
(match url.proto, url.port with
"http", 80
| "ftp", 21
| "ssh", 22 -> ()
| ("http" | "ftp" | "ssh"), _ ->
(add_char res ':'; add_string res (string_of_int url.port));
| _, port when port <> 0 ->
(add_char res ':'; add_string res (string_of_int url.port));
| _ -> ());
add_string res url.full_file;
contents res
let cut_args url_end =
if url_end = "" then []
else
let args = String2.split url_end '&' in
List.map (fun s ->
let (name, value) = String2.cut_at s '=' in
decode ~raw:false name, decode ~raw:false value
) args
let create proto user passwd server port full_file =
let short_file, args = String2.cut_at full_file '?' in
let args = cut_args args in
let user , passw , server =
let userpass , server = String2.cut_at server ' @ ' in
if server = " " then " " , " " , server
else
let user , pass = String2.cut_at userpass ' : ' in
user , pass , server
in
let user, passw, server =
let userpass, server = String2.cut_at server '@' in
if server = "" then "", "", server
else
let user, pass = String2.cut_at userpass ':' in
user, pass, server
in
*)
let url =
{
proto = proto;
server = server;
port = port;
full_file = full_file;
short_file = short_file;
user = user;
passwd = passwd;
args = args;
string = "";
}
in
{ url with string = to_string url }
let port = if proto = " ftp " & & port = 80 then 21 else port in
let url = { proto = proto ; server = server ; port = port ; full_file = file ;
user = user ; passwd = pass ; file = short_file ; args = args ; string = " " } in
{ url with string = to_string url }
let port = if proto = "ftp" && port = 80 then 21 else port in
let url = { proto=proto; server=server; port=port; full_file=file;
user=user; passwd=pass; file = short_file; args = args; string = "" } in
{ url with string = to_string url }
*)
let put_args s args =
if args = [] then s else
let res = Buffer.create 256 in
Buffer.add_string res s;
Buffer.add_char res (if String.contains s '?' then '&' else '?');
let rec manage_args = function
| [] -> assert false
| [a, ""] ->
Buffer.add_string res (encode a)
| [a, b] ->
Buffer.add_string res (encode a); Buffer.add_char res '='; Buffer.add_string res
(encode b)
| (a,b)::l ->
Buffer.add_string res (encode a); Buffer.add_char res '='; Buffer.add_string res
(encode b);
Buffer.add_char res '&'; manage_args l in
lprintf " len args % d " ( args ) ; lprint_newline ( ) ;
manage_args args;
Buffer.contents res
let of_string ?(args=[]) s =
let remove_leading_slashes s =
let len = String.length s in
let left =
let rec aux i =
if i < len && s.[i] = '/' then aux (i+1) else i in
aux 0 in
if left = 0 then s
else
String.sub s left (len - left) in
(* redefine s to remove all leading slashes *)
let s = remove_leading_slashes s in
let s = put_args s args in
let url =
let get_two init_pos =
let pos = ref init_pos in
while s.[!pos] <> ':' && s.[!pos] <> '/' && s.[!pos] <> '@' do
incr pos
done;
let first = String.sub s init_pos (!pos - init_pos) in
if s.[!pos] = ':'
then
(let deb = !pos+1 in
while s.[!pos] <> '@' && s.[!pos] <> '/' do
incr pos
done;
(first, String.sub s deb (!pos-deb), !pos))
else
(first, "", !pos) in
let cut init_pos default_port =
let stra, strb, new_pos = get_two init_pos in
let user, pass, host, port, end_pos =
if s.[new_pos] = '@'
then
(let host, port_str, end_pos = get_two (new_pos+1) in
let port =
if port_str="" then default_port else int_of_string port_str in
stra, strb, host, port, end_pos)
else
(let port = if strb="" then default_port else int_of_string strb in
"", "", stra, port, new_pos) in
let len = String.length s in
let file = String.sub s end_pos (len - end_pos) in
host, port, file, user, pass in
try
let colon = String.index s ':' in
let len = String.length s in
if len > colon + 2 &&
s.[colon+1] = '/' &&
s.[colon+2] = '/' then
let proto = String.sub s 0 colon in
let port = match proto with
"http" -> 80
| "ftp" -> 21
| "ssh" -> 22
| _ -> 0
in
let host, port, full_file, user, pass = cut (colon+3) port in
create proto user pass host port full_file
else
raise Not_found
with Not_found ->
let short_file, args = String2.cut_at s '?' in
let args = cut_args args in
{
proto = "file";
server = "";
port = 0;
full_file = s;
short_file = short_file;
user = "";
passwd = "";
args = args;
string = s;
}
if String2.check_prefix s " http:// "
then
try
with _ - > raise ( Invalid_argument " this string is not a valid http url " )
else if String2.check_prefix s " ftp:// "
then
try
let host , port , file , user , pass = cut 6 21 in
create " ftp " user pass host port full_file
with _ - > raise ( Invalid_argument " this string is not a valid ftp url " )
else if String2.check_prefix s " ssh:// "
then
try
let host , port , file , user , pass = cut 6 22 in
create " ssh " user pass host port full_file
with _ - > raise ( Invalid_argument " this string is not a valid ssh url " )
else
let file = s in
Printf2.lprintf " NEW URL FOR % s\n " file ;
create " file"~proto : " file " file
if String2.check_prefix s "http://"
then
try
with _ -> raise (Invalid_argument "this string is not a valid http url")
else if String2.check_prefix s "ftp://"
then
try
let host, port, file, user, pass = cut 6 21 in
create "ftp" user pass host port full_file
with _ -> raise (Invalid_argument "this string is not a valid ftp url")
else if String2.check_prefix s "ssh://"
then
try
let host, port, file, user, pass = cut 6 22 in
create "ssh" user pass host port full_file
with _ -> raise (Invalid_argument "this string is not a valid ssh url")
else
let file = s in
Printf2.lprintf "NEW URL FOR %s\n" file;
create "file"~proto: "file" file
*)
in
url
let to_string url = url.string
let to_string_no_args url =
let res = Buffer.create 80 in
add_string res url.proto;
add_string res "://";
add_string res url.server;
(match url.proto, url.port with
"http", 80
| "ftp", 21
| "ssh", 22 -> ()
| ("http" | "ftp" | "ssh"), _ ->
(add_char res ':'; add_string res (string_of_int url.port));
| _, port when port <> 0 ->
(add_char res ':'; add_string res (string_of_int url.port));
| _ -> ());
add_string res url.short_file;
contents res
open Options
let option =
define_option_class "URL"
(fun v -> of_string (value_to_string v))
(fun url -> string_to_value (to_string url)) | null | https://raw.githubusercontent.com/ygrek/mldonkey/333868a12bb6cd25fed49391dd2c3a767741cb51/src/utils/lib/url.ml | ocaml | encode using RFC 1738 form
if not raw decode '+' -> ' ' else don't change char
redefine s to remove all leading slashes | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
mldonkey is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You should have received a copy of the GNU General Public License
along with mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
mldonkey is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Buffer
type url = {
proto : string;
server : string;
port : int;
full_file : string;
short_file : string;
user : string;
passwd : string;
args : (string*string) list;
string : string;
}
let encode s =
let pos = ref 0 in
let len = String.length s in
let res = String.create (3*len) in
let hexa_digit x =
if x >= 10 then Char.chr (Char.code 'A' + x - 10)
else Char.chr (Char.code '0' + x) in
for i=0 to len-1 do
match s.[i] with
| 'a'..'z' | 'A'..'Z' | '0'..'9' | '.' | '-' | '*' | '_' | '\''| '(' | ')'->
res.[!pos] <- s.[i]; incr pos
| c ->
res.[!pos] <- '%';
res.[!pos+1] <- hexa_digit (Char.code c / 16);
res.[!pos+2] <- hexa_digit (Char.code c mod 16);
pos := !pos + 3
done;
String.sub res 0 !pos
* decodes a sting according RFC 1738
or x - www - form - urlencoded ( ' + ' with ' ' )
@param raw true use RFC 1738
@param string string to decode
or x-www-form-urlencoded ('+' with ' ')
@param raw true use RFC 1738
@param string string to decode
*)
let decode ?(raw=true) s =
let len = String.length s in
let r = Buffer.create len in
let rec iter i =
if i < len then
match s.[i] with
| '%' ->
let n =
try
int_of_string with leading " 0x " , string is read hexadecimal
Buffer.add_char r (char_of_int (int_of_string ("0x" ^ (String.sub s (i+1) 2))));
3
with _ ->
Buffer.add_char r '%';
1
in
iter (i+n)
| '+' -> let c = if raw then '+' else ' ' in
Buffer.add_char r c; iter (i+1)
| c -> Buffer.add_char r c; iter (i+1)
in
iter 0;
Buffer.contents r
let to_string url =
let res = Buffer.create 80 in
add_string res url.proto;
add_string res "://";
if url.user <> "" || url.passwd <> "" then begin
add_string res url.user;
add_string res ":";
add_string res url.passwd;
add_string res "@";
end;
add_string res url.server;
(match url.proto, url.port with
"http", 80
| "ftp", 21
| "ssh", 22 -> ()
| ("http" | "ftp" | "ssh"), _ ->
(add_char res ':'; add_string res (string_of_int url.port));
| _, port when port <> 0 ->
(add_char res ':'; add_string res (string_of_int url.port));
| _ -> ());
add_string res url.full_file;
contents res
let cut_args url_end =
if url_end = "" then []
else
let args = String2.split url_end '&' in
List.map (fun s ->
let (name, value) = String2.cut_at s '=' in
decode ~raw:false name, decode ~raw:false value
) args
let create proto user passwd server port full_file =
let short_file, args = String2.cut_at full_file '?' in
let args = cut_args args in
let user , passw , server =
let userpass , server = String2.cut_at server ' @ ' in
if server = " " then " " , " " , server
else
let user , pass = String2.cut_at userpass ' : ' in
user , pass , server
in
let user, passw, server =
let userpass, server = String2.cut_at server '@' in
if server = "" then "", "", server
else
let user, pass = String2.cut_at userpass ':' in
user, pass, server
in
*)
let url =
{
proto = proto;
server = server;
port = port;
full_file = full_file;
short_file = short_file;
user = user;
passwd = passwd;
args = args;
string = "";
}
in
{ url with string = to_string url }
let port = if proto = " ftp " & & port = 80 then 21 else port in
let url = { proto = proto ; server = server ; port = port ; full_file = file ;
user = user ; passwd = pass ; file = short_file ; args = args ; string = " " } in
{ url with string = to_string url }
let port = if proto = "ftp" && port = 80 then 21 else port in
let url = { proto=proto; server=server; port=port; full_file=file;
user=user; passwd=pass; file = short_file; args = args; string = "" } in
{ url with string = to_string url }
*)
let put_args s args =
if args = [] then s else
let res = Buffer.create 256 in
Buffer.add_string res s;
Buffer.add_char res (if String.contains s '?' then '&' else '?');
let rec manage_args = function
| [] -> assert false
| [a, ""] ->
Buffer.add_string res (encode a)
| [a, b] ->
Buffer.add_string res (encode a); Buffer.add_char res '='; Buffer.add_string res
(encode b)
| (a,b)::l ->
Buffer.add_string res (encode a); Buffer.add_char res '='; Buffer.add_string res
(encode b);
Buffer.add_char res '&'; manage_args l in
lprintf " len args % d " ( args ) ; lprint_newline ( ) ;
manage_args args;
Buffer.contents res
let of_string ?(args=[]) s =
let remove_leading_slashes s =
let len = String.length s in
let left =
let rec aux i =
if i < len && s.[i] = '/' then aux (i+1) else i in
aux 0 in
if left = 0 then s
else
String.sub s left (len - left) in
let s = remove_leading_slashes s in
let s = put_args s args in
let url =
let get_two init_pos =
let pos = ref init_pos in
while s.[!pos] <> ':' && s.[!pos] <> '/' && s.[!pos] <> '@' do
incr pos
done;
let first = String.sub s init_pos (!pos - init_pos) in
if s.[!pos] = ':'
then
(let deb = !pos+1 in
while s.[!pos] <> '@' && s.[!pos] <> '/' do
incr pos
done;
(first, String.sub s deb (!pos-deb), !pos))
else
(first, "", !pos) in
let cut init_pos default_port =
let stra, strb, new_pos = get_two init_pos in
let user, pass, host, port, end_pos =
if s.[new_pos] = '@'
then
(let host, port_str, end_pos = get_two (new_pos+1) in
let port =
if port_str="" then default_port else int_of_string port_str in
stra, strb, host, port, end_pos)
else
(let port = if strb="" then default_port else int_of_string strb in
"", "", stra, port, new_pos) in
let len = String.length s in
let file = String.sub s end_pos (len - end_pos) in
host, port, file, user, pass in
try
let colon = String.index s ':' in
let len = String.length s in
if len > colon + 2 &&
s.[colon+1] = '/' &&
s.[colon+2] = '/' then
let proto = String.sub s 0 colon in
let port = match proto with
"http" -> 80
| "ftp" -> 21
| "ssh" -> 22
| _ -> 0
in
let host, port, full_file, user, pass = cut (colon+3) port in
create proto user pass host port full_file
else
raise Not_found
with Not_found ->
let short_file, args = String2.cut_at s '?' in
let args = cut_args args in
{
proto = "file";
server = "";
port = 0;
full_file = s;
short_file = short_file;
user = "";
passwd = "";
args = args;
string = s;
}
if String2.check_prefix s " http:// "
then
try
with _ - > raise ( Invalid_argument " this string is not a valid http url " )
else if String2.check_prefix s " ftp:// "
then
try
let host , port , file , user , pass = cut 6 21 in
create " ftp " user pass host port full_file
with _ - > raise ( Invalid_argument " this string is not a valid ftp url " )
else if String2.check_prefix s " ssh:// "
then
try
let host , port , file , user , pass = cut 6 22 in
create " ssh " user pass host port full_file
with _ - > raise ( Invalid_argument " this string is not a valid ssh url " )
else
let file = s in
Printf2.lprintf " NEW URL FOR % s\n " file ;
create " file"~proto : " file " file
if String2.check_prefix s "http://"
then
try
with _ -> raise (Invalid_argument "this string is not a valid http url")
else if String2.check_prefix s "ftp://"
then
try
let host, port, file, user, pass = cut 6 21 in
create "ftp" user pass host port full_file
with _ -> raise (Invalid_argument "this string is not a valid ftp url")
else if String2.check_prefix s "ssh://"
then
try
let host, port, file, user, pass = cut 6 22 in
create "ssh" user pass host port full_file
with _ -> raise (Invalid_argument "this string is not a valid ssh url")
else
let file = s in
Printf2.lprintf "NEW URL FOR %s\n" file;
create "file"~proto: "file" file
*)
in
url
let to_string url = url.string
let to_string_no_args url =
let res = Buffer.create 80 in
add_string res url.proto;
add_string res "://";
add_string res url.server;
(match url.proto, url.port with
"http", 80
| "ftp", 21
| "ssh", 22 -> ()
| ("http" | "ftp" | "ssh"), _ ->
(add_char res ':'; add_string res (string_of_int url.port));
| _, port when port <> 0 ->
(add_char res ':'; add_string res (string_of_int url.port));
| _ -> ());
add_string res url.short_file;
contents res
open Options
let option =
define_option_class "URL"
(fun v -> of_string (value_to_string v))
(fun url -> string_to_value (to_string url)) |
25611f11d1ada5eec16087aa834c6e73abe046a050221a6fc53b6b706b1bbbee | dyoo/whalesong | m1.rkt | #lang s-exp "../../lang/base.rkt" | null | https://raw.githubusercontent.com/dyoo/whalesong/636e0b4e399e4523136ab45ef4cd1f5a84e88cdc/whalesong/tests/older-tests/require-test/m1.rkt | racket | #lang s-exp "../../lang/base.rkt" |
|
1124c7f681b75779e17145f116a39f5f2792f5b4c40283870302a3c211bcb53b | igorhvr/bedlam | schemechan.scm | (import file-manipulation)
(define-record-type :schemer
(make-schemer at-repl env queue)
schemer?
(at-repl schemer-at-repl? schemer-at-repl!)
(env schemers-env set-schemers-env!)
(queue schemers-queue set-schemers-queue!))
(define-record-type :scheme-channel
(make-scheme-channel schemers)
scheme-channel?
(schemers scheme-channel-schemers set-scheme-channel-schemers!))
(define (make-schemechan channel message ignore term)
(do-join term
(make-channel-record term (channel-bot channel) #f '()
(list scheme-channel) #f #f))
"Okay.")
(define (queue-empty? schemer)
(equal? (schemers-queue schemer) ""))
(define (add-text-to-queue! schemer text)
(set-schemers-queue! schemer
(string-append (schemers-queue schemer)
text
(string #\newline))))
(define (queue-complete? schemer)
(let* ([text (schemers-queue schemer)]
[sexpr (with/fc (lambda (m e) #!eof)
(lambda ()
(with-input-from-string text read-code)))])
(not (or (and (void? sexpr) (not (equal? text "#!void")))
(eof-object? sexpr)))))
(define (queue->s-expressions channel schemer)
(with/fc (lambda (m e)
(clear-queue! schemer)
(send-messages (channel-bot channel)
(channel-name channel)
(make-error-message
(error-location m)
(error-message m))))
(lambda ()
(let ([datum (with-input-from-string
(schemers-queue schemer)
(lambda ()
(let loop ([c (read-code)])
(if (eof-object? c)
'()
(cons c (loop (read-code)))))))])
(clear-queue! schemer)
datum))))
(define (clear-queue! schemer)
(set-schemers-queue! schemer ""))
(define (scheme-channel channel message)
(import srfi-13)
(unless (channel-seed channel)
(set-channel-seed! channel (make-scheme-channel
'())))
(let ([schemechan (channel-seed channel)]
[nick (string-downcase (message-nick message))])
(unless (message-is-private? message)
(unless (assoc nick (scheme-channel-schemers schemechan))
(set-scheme-channel-schemers!
schemechan (cons (cons nick
(make-schemer
#f (make-scheme-channel-env schemechan) ""))
(scheme-channel-schemers schemechan))))
(let ([schemer (cdr (assoc nick (scheme-channel-schemers schemechan)))]
[text (message-text message)]
[commands '(".exit" ".repl" ".attach" ".reset" ".help")])
(let* ([i (string-index text #\space)]
[command (trim (or (and i (substring text 0 i))
text))])
(if (member command commands)
(cond [(equal? command ".exit")
(clear-queue! schemer)
(schemer-at-repl! schemer #f)
(send-messages (channel-bot channel)
(message-nick message)
"You are now chatting.")]
[(equal? command ".repl")
(schemer-at-repl! schemer #t)
(send-messages (channel-bot channel)
(message-nick message)
"You are now in the REPL.")]
[(equal? command ".attach")
(let ([user (string-downcase
(trim
(substring text i (string-length text))))])
(set-schemers-env!
schemer (schemers-env
(cdr (assoc user (scheme-channel-schemers
schemechan))))))]
[(equal? command ".reset")
(set-schemers-env! schemer
(make-scheme-channel-env schemechan))]
[(equal? command ".help")
(send-messages (channel-bot channel)
(message-nick message)
(string-append
"Welcome to the Scheme IRC REPL\n"
"The following commands are available\n"
".repl - Enters the REPL. All text after this is sent to your\n"
"Scheme session, which is distinct from others.\n"
".exit - When in the REPL, returns to chat mode (exits the REPL).\n"
".attach <nick> - Allows you to join <nick>'s Scheme session.\n"
".reset - Clears your Scheme session.\n"
".help - This screen"))])
(when (schemer-at-repl? schemer)
(add-text-to-queue! schemer text)
(when (queue-complete? schemer)
(strict-r5rs-compliance #t)
(send-messages
(channel-bot channel) (channel-name channel)
(let loop ([vs (queue->s-expressions channel
schemer)])
(if (null? vs)
""
(string-append
(eval-within-n-ms
(car vs) 5000
(schemers-env schemer))
(string #\newline)
(loop (cdr vs))))))))))))))
(define simple-gen-sym
(let ([x 0])
(lambda (var)
(set! x (+ x 1))
(string->symbol (format "~a_~a" var x)))))
(define (make-scheme-channel-env schemechan)
(let* ([etmp (sandbox (scheme-report-environment 5))]
[special-var (string->uninterned-symbol "no-binding")]
[from (lambda (user binding)
(let ([user (string-downcase (trim user))])
(if (assoc user (scheme-channel-schemers schemechan))
(let ([rv (getprop binding
(schemers-env
(cdr (assoc user (scheme-channel-schemers
schemechan))))
special-var)])
(if (eq? rv special-var)
(eval binding (null-environment 5))
rv))
(eval binding (null-environment 5)))))]
[load-from-url
(lambda (url)
(with/fc (lambda (m e)
(if (eq? (error-location m) 'load)
(throw m e)
(my-load url etmp)))
(lambda ()
(when (file-is-file? url)
(error 'load "Loading from local files not permitted.")))))])
(for-each (lambda (b v)
(putprop b etmp v))
'($sc-put-cte $syntax-dispatch syntax-error _load gen-sym
|@optimizer::optimize| with/fc
with-failure-continuation : throw make-error load)
(list $sc-put-cte $syntax-dispatch syntax-error my-load
simple-gen-sym optimize with/fc with/fc from throw
make-error load-from-url))
(putprop 'sc-expand etmp
(lambda (v)
(let ((old-env (interaction-environment etmp)))
(dynamic-wind
void
(lambda () (sc-expand v '(e) '(e)))
(lambda () (interaction-environment
old-env))))))
etmp))
(define (init-schemechan-plugin)
(let ()
(import srfi-1)
(add-part-hook
(lambda (channel sender login hostname)
(when (get-channel channel)
(let ([schemechan (channel-seed (get-channel channel))]
[sender (string-downcase sender)])
(when (and schemechan
(assoc sender (scheme-channel-schemers schemechan)))
(set-scheme-channel-schemers!
(delete (cdr (assoc sender
(scheme-channel-schemers schemechan)))
(scheme-channel-schemers scheme-channel-schemers)))))))))) | null | https://raw.githubusercontent.com/igorhvr/bedlam/b62e0d047105bb0473bdb47c58b23f6ca0f79a4e/sisc/sisc-contrib/irc/scheme/sarah/plugins/schemechan.scm | scheme | (import file-manipulation)
(define-record-type :schemer
(make-schemer at-repl env queue)
schemer?
(at-repl schemer-at-repl? schemer-at-repl!)
(env schemers-env set-schemers-env!)
(queue schemers-queue set-schemers-queue!))
(define-record-type :scheme-channel
(make-scheme-channel schemers)
scheme-channel?
(schemers scheme-channel-schemers set-scheme-channel-schemers!))
(define (make-schemechan channel message ignore term)
(do-join term
(make-channel-record term (channel-bot channel) #f '()
(list scheme-channel) #f #f))
"Okay.")
(define (queue-empty? schemer)
(equal? (schemers-queue schemer) ""))
(define (add-text-to-queue! schemer text)
(set-schemers-queue! schemer
(string-append (schemers-queue schemer)
text
(string #\newline))))
(define (queue-complete? schemer)
(let* ([text (schemers-queue schemer)]
[sexpr (with/fc (lambda (m e) #!eof)
(lambda ()
(with-input-from-string text read-code)))])
(not (or (and (void? sexpr) (not (equal? text "#!void")))
(eof-object? sexpr)))))
(define (queue->s-expressions channel schemer)
(with/fc (lambda (m e)
(clear-queue! schemer)
(send-messages (channel-bot channel)
(channel-name channel)
(make-error-message
(error-location m)
(error-message m))))
(lambda ()
(let ([datum (with-input-from-string
(schemers-queue schemer)
(lambda ()
(let loop ([c (read-code)])
(if (eof-object? c)
'()
(cons c (loop (read-code)))))))])
(clear-queue! schemer)
datum))))
(define (clear-queue! schemer)
(set-schemers-queue! schemer ""))
(define (scheme-channel channel message)
(import srfi-13)
(unless (channel-seed channel)
(set-channel-seed! channel (make-scheme-channel
'())))
(let ([schemechan (channel-seed channel)]
[nick (string-downcase (message-nick message))])
(unless (message-is-private? message)
(unless (assoc nick (scheme-channel-schemers schemechan))
(set-scheme-channel-schemers!
schemechan (cons (cons nick
(make-schemer
#f (make-scheme-channel-env schemechan) ""))
(scheme-channel-schemers schemechan))))
(let ([schemer (cdr (assoc nick (scheme-channel-schemers schemechan)))]
[text (message-text message)]
[commands '(".exit" ".repl" ".attach" ".reset" ".help")])
(let* ([i (string-index text #\space)]
[command (trim (or (and i (substring text 0 i))
text))])
(if (member command commands)
(cond [(equal? command ".exit")
(clear-queue! schemer)
(schemer-at-repl! schemer #f)
(send-messages (channel-bot channel)
(message-nick message)
"You are now chatting.")]
[(equal? command ".repl")
(schemer-at-repl! schemer #t)
(send-messages (channel-bot channel)
(message-nick message)
"You are now in the REPL.")]
[(equal? command ".attach")
(let ([user (string-downcase
(trim
(substring text i (string-length text))))])
(set-schemers-env!
schemer (schemers-env
(cdr (assoc user (scheme-channel-schemers
schemechan))))))]
[(equal? command ".reset")
(set-schemers-env! schemer
(make-scheme-channel-env schemechan))]
[(equal? command ".help")
(send-messages (channel-bot channel)
(message-nick message)
(string-append
"Welcome to the Scheme IRC REPL\n"
"The following commands are available\n"
".repl - Enters the REPL. All text after this is sent to your\n"
"Scheme session, which is distinct from others.\n"
".exit - When in the REPL, returns to chat mode (exits the REPL).\n"
".attach <nick> - Allows you to join <nick>'s Scheme session.\n"
".reset - Clears your Scheme session.\n"
".help - This screen"))])
(when (schemer-at-repl? schemer)
(add-text-to-queue! schemer text)
(when (queue-complete? schemer)
(strict-r5rs-compliance #t)
(send-messages
(channel-bot channel) (channel-name channel)
(let loop ([vs (queue->s-expressions channel
schemer)])
(if (null? vs)
""
(string-append
(eval-within-n-ms
(car vs) 5000
(schemers-env schemer))
(string #\newline)
(loop (cdr vs))))))))))))))
(define simple-gen-sym
(let ([x 0])
(lambda (var)
(set! x (+ x 1))
(string->symbol (format "~a_~a" var x)))))
(define (make-scheme-channel-env schemechan)
(let* ([etmp (sandbox (scheme-report-environment 5))]
[special-var (string->uninterned-symbol "no-binding")]
[from (lambda (user binding)
(let ([user (string-downcase (trim user))])
(if (assoc user (scheme-channel-schemers schemechan))
(let ([rv (getprop binding
(schemers-env
(cdr (assoc user (scheme-channel-schemers
schemechan))))
special-var)])
(if (eq? rv special-var)
(eval binding (null-environment 5))
rv))
(eval binding (null-environment 5)))))]
[load-from-url
(lambda (url)
(with/fc (lambda (m e)
(if (eq? (error-location m) 'load)
(throw m e)
(my-load url etmp)))
(lambda ()
(when (file-is-file? url)
(error 'load "Loading from local files not permitted.")))))])
(for-each (lambda (b v)
(putprop b etmp v))
'($sc-put-cte $syntax-dispatch syntax-error _load gen-sym
|@optimizer::optimize| with/fc
with-failure-continuation : throw make-error load)
(list $sc-put-cte $syntax-dispatch syntax-error my-load
simple-gen-sym optimize with/fc with/fc from throw
make-error load-from-url))
(putprop 'sc-expand etmp
(lambda (v)
(let ((old-env (interaction-environment etmp)))
(dynamic-wind
void
(lambda () (sc-expand v '(e) '(e)))
(lambda () (interaction-environment
old-env))))))
etmp))
(define (init-schemechan-plugin)
(let ()
(import srfi-1)
(add-part-hook
(lambda (channel sender login hostname)
(when (get-channel channel)
(let ([schemechan (channel-seed (get-channel channel))]
[sender (string-downcase sender)])
(when (and schemechan
(assoc sender (scheme-channel-schemers schemechan)))
(set-scheme-channel-schemers!
(delete (cdr (assoc sender
(scheme-channel-schemers schemechan)))
(scheme-channel-schemers scheme-channel-schemers)))))))))) |
|
db4143c0be3782099334b36a42d67cd9018e54344c7fbf643a1a3d0034c0d94f | erlef/rebar3_hex | rebar3_hex_SUITE.erl | -module(rebar3_hex_SUITE).
-compile(export_all).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
all() ->
[task_args_test, task_state_test, gather_opts_test, init_test, help_test, repo_opt].
gather_opts_test(_Config) ->
State = rebar_state:new(),
CmdArgs = {[{foo,"bar"}, {count, 42}, {other, eh}], []},
State1 = rebar_state:command_parsed_args(State, CmdArgs),
?assertMatch(#{count := 42, foo := "bar"}, rebar3_hex:gather_opts([count, foo], State1)).
task_args_test(_Config) ->
State = rebar_state:new(),
CmdArgs = {[{task, thing}, {foo,"bar"}, {count, 42}], []},
State1 = rebar_state:command_parsed_args(State, CmdArgs),
?assertMatch({thing,[{foo,"bar"},{count,42}]}, rebar3_hex:task_args(State1)),
CmdArgs2 = {[{foo,"bar"}, {count, 42}], []},
State2 = rebar_state:command_parsed_args(State, CmdArgs2),
?assertMatch({undefined,[{foo,"bar"},{count,42}]}, rebar3_hex:task_args(State2)).
task_state_test(_Config) ->
State = rebar_state:new(),
CmdArgs = {[{task, "thing"}, {foo,"bar"}, {count, 42}], ["bar"]},
State1 = rebar_state:command_parsed_args(State, CmdArgs),
?assertMatch(#{count := 42, foo := "bar", task := thing, bar := true}, rebar3_hex:get_args(State1)),
CmdArgs2 = {[{foo,false}, {count, 42}], []},
State2 = rebar_state:command_parsed_args(State, CmdArgs2),
?assertMatch(#{count := 42, foo := false}, rebar3_hex:get_args(State2)).
repo_opt(_Config) ->
?assertEqual({repo,114,"repo",string,
"Repository to use for this command."}, rebar3_hex:repo_opt()).
init_test(_Config) ->
{ok, State} = rebar3_hex:init(rebar_state:new()),
?assertEqual(state_t, element(1, State)).
%% Smoke test to ensure we don't crash
help_test(_Config) ->
%% Silent output during our tests
ok = meck:new(io_lib, [unstick, passthrough]),
meck:expect(io_lib, format, 2, fun(_,_) -> "" end),
Checks = [
{rebar3_hex_publish, publish},
{rebar3_hex_cut, cut},
{rebar3_hex_owner, owner},
{rebar3_hex_organization, organization},
{rebar3_hex_retire, retire},
{rebar3_hex_search, search},
{rebar3_hex_user, user}
],
lists:foreach(fun get_help/1, Checks),
meck:unload(io_lib),
ok.
get_help({Mod, Task}) ->
State = rebar_state:new(),
{ok, State1} = Mod:init(State),
Providers = rebar_state:providers(State1),
Provider = providers:get_provider(Task, Providers, hex),
?assertMatch(ok, providers:help(Provider)).
| null | https://raw.githubusercontent.com/erlef/rebar3_hex/17137b87050a3f24b60caa5abed93a3635621769/test/rebar3_hex_SUITE.erl | erlang | Smoke test to ensure we don't crash
Silent output during our tests | -module(rebar3_hex_SUITE).
-compile(export_all).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
all() ->
[task_args_test, task_state_test, gather_opts_test, init_test, help_test, repo_opt].
gather_opts_test(_Config) ->
State = rebar_state:new(),
CmdArgs = {[{foo,"bar"}, {count, 42}, {other, eh}], []},
State1 = rebar_state:command_parsed_args(State, CmdArgs),
?assertMatch(#{count := 42, foo := "bar"}, rebar3_hex:gather_opts([count, foo], State1)).
task_args_test(_Config) ->
State = rebar_state:new(),
CmdArgs = {[{task, thing}, {foo,"bar"}, {count, 42}], []},
State1 = rebar_state:command_parsed_args(State, CmdArgs),
?assertMatch({thing,[{foo,"bar"},{count,42}]}, rebar3_hex:task_args(State1)),
CmdArgs2 = {[{foo,"bar"}, {count, 42}], []},
State2 = rebar_state:command_parsed_args(State, CmdArgs2),
?assertMatch({undefined,[{foo,"bar"},{count,42}]}, rebar3_hex:task_args(State2)).
task_state_test(_Config) ->
State = rebar_state:new(),
CmdArgs = {[{task, "thing"}, {foo,"bar"}, {count, 42}], ["bar"]},
State1 = rebar_state:command_parsed_args(State, CmdArgs),
?assertMatch(#{count := 42, foo := "bar", task := thing, bar := true}, rebar3_hex:get_args(State1)),
CmdArgs2 = {[{foo,false}, {count, 42}], []},
State2 = rebar_state:command_parsed_args(State, CmdArgs2),
?assertMatch(#{count := 42, foo := false}, rebar3_hex:get_args(State2)).
repo_opt(_Config) ->
?assertEqual({repo,114,"repo",string,
"Repository to use for this command."}, rebar3_hex:repo_opt()).
init_test(_Config) ->
{ok, State} = rebar3_hex:init(rebar_state:new()),
?assertEqual(state_t, element(1, State)).
help_test(_Config) ->
ok = meck:new(io_lib, [unstick, passthrough]),
meck:expect(io_lib, format, 2, fun(_,_) -> "" end),
Checks = [
{rebar3_hex_publish, publish},
{rebar3_hex_cut, cut},
{rebar3_hex_owner, owner},
{rebar3_hex_organization, organization},
{rebar3_hex_retire, retire},
{rebar3_hex_search, search},
{rebar3_hex_user, user}
],
lists:foreach(fun get_help/1, Checks),
meck:unload(io_lib),
ok.
get_help({Mod, Task}) ->
State = rebar_state:new(),
{ok, State1} = Mod:init(State),
Providers = rebar_state:providers(State1),
Provider = providers:get_provider(Task, Providers, hex),
?assertMatch(ok, providers:help(Provider)).
|
88f199b71466de6c5f1982d92c173e5f87bcfdddae74c9851ea9bb175b6fb6d9 | bsaleil/lc | pnpoly.scm.scm | ;;------------------------------------------------------------------------------
Macros
(##define-macro (def-macro form . body)
`(##define-macro ,form (let () ,@body)))
(def-macro (FLOATvector-const . lst) `',(list->f64vector lst))
(def-macro (FLOATvector? x) `(f64vector? ,x))
(def-macro (FLOATvector . lst) `(f64vector ,@lst))
(def-macro (FLOATmake-vector n . init) `(make-f64vector ,n ,@init))
(def-macro (FLOATvector-ref v i) `(f64vector-ref ,v ,i))
(def-macro (FLOATvector-set! v i x) `(f64vector-set! ,v ,i ,x))
(def-macro (FLOATvector-length v) `(f64vector-length ,v))
(def-macro (nuc-const . lst)
`',(list->vector
(map (lambda (x)
(if (vector? x)
(list->f64vector (vector->list x))
x))
lst)))
(def-macro (FLOAT+ . lst) `(+ ,@lst))
(def-macro (FLOAT- . lst) `(- ,@lst))
(def-macro (FLOAT* . lst) `(* ,@lst))
(def-macro (FLOAT/ . lst) `(/ ,@lst))
(def-macro (FLOAT= . lst) `(= ,@lst))
(def-macro (FLOAT< . lst) `(< ,@lst))
(def-macro (FLOAT<= . lst) `(<= ,@lst))
(def-macro (FLOAT> . lst) `(> ,@lst))
(def-macro (FLOAT>= . lst) `(>= ,@lst))
(def-macro (FLOATnegative? . lst) `(negative? ,@lst))
(def-macro (FLOATpositive? . lst) `(positive? ,@lst))
(def-macro (FLOATzero? . lst) `(zero? ,@lst))
(def-macro (FLOATabs . lst) `(abs ,@lst))
(def-macro (FLOATsin . lst) `(sin ,@lst))
(def-macro (FLOATcos . lst) `(cos ,@lst))
(def-macro (FLOATatan . lst) `(atan ,@lst))
(def-macro (FLOATsqrt . lst) `(sqrt ,@lst))
(def-macro (FLOATmin . lst) `(min ,@lst))
(def-macro (FLOATmax . lst) `(max ,@lst))
(def-macro (FLOATround . lst) `(round ,@lst))
(def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst))
(def-macro (GENERIC+ . lst) `(+ ,@lst))
(def-macro (GENERIC- . lst) `(- ,@lst))
(def-macro (GENERIC* . lst) `(* ,@lst))
(def-macro (GENERIC/ . lst) `(/ ,@lst))
(def-macro (GENERICquotient . lst) `(quotient ,@lst))
(def-macro (GENERICremainder . lst) `(remainder ,@lst))
(def-macro (GENERICmodulo . lst) `(modulo ,@lst))
(def-macro (GENERIC= . lst) `(= ,@lst))
(def-macro (GENERIC< . lst) `(< ,@lst))
(def-macro (GENERIC<= . lst) `(<= ,@lst))
(def-macro (GENERIC> . lst) `(> ,@lst))
(def-macro (GENERIC>= . lst) `(>= ,@lst))
(def-macro (GENERICexpt . lst) `(expt ,@lst))
;;------------------------------------------------------------------------------
Functions used by LC to get time info
(def-macro (##lc-time expr)
(let ((sym (gensym)))
`(let ((r (##lc-exec-stats (lambda () ,expr))))
(##print-perm-string "CPU time: ")
(##print-double (+ (cdr (assoc "User time" (cdr r)))
(cdr (assoc "Sys time" (cdr r)))))
(##print-perm-string "\n")
(##print-perm-string "GC CPU time: ")
(##print-double (+ (cdr (assoc "GC user time" (cdr r)))
(cdr (assoc "GC sys time" (cdr r)))))
(##print-perm-string "\n")
(map (lambda (el)
(##print-perm-string (car el))
(##print-perm-string ": ")
(##print-double (cdr el))
(##print-perm-string "\n"))
(cdr r))
r)))
(define (##lc-exec-stats thunk)
(let* ((at-start (##process-statistics))
(result (thunk))
(at-end (##process-statistics)))
(define (get-info msg idx)
(cons msg
(- (f64vector-ref at-end idx)
(f64vector-ref at-start idx))))
(list
result
(get-info "User time" 0)
(get-info "Sys time" 1)
(get-info "Real time" 2)
(get-info "GC user time" 3)
(get-info "GC sys time" 4)
(get-info "GC real time" 5)
(get-info "Nb gcs" 6))))
;;------------------------------------------------------------------------------
(define (run-bench name count ok? run)
(let loop ((i count) (result '(undefined)))
(if (< 0 i)
(loop (- i 1) (run))
result)))
(define (run-benchmark name count ok? run-maker . args)
(let ((run (apply run-maker args)))
(let ((result (car (##lc-time (run-bench name count ok? run)))))
(if (not (ok? result))
(begin
(display "*** wrong result ***")
(newline)
(display "*** got: ")
(write result)
(newline))))))
; Gabriel benchmarks
(define boyer-iters 20)
(define browse-iters 600)
(define cpstak-iters 1000)
(define ctak-iters 100)
(define dderiv-iters 2000000)
(define deriv-iters 2000000)
(define destruc-iters 500)
(define diviter-iters 1000000)
(define divrec-iters 1000000)
(define puzzle-iters 100)
(define tak-iters 2000)
(define takl-iters 300)
(define trav1-iters 100)
(define trav2-iters 20)
(define triangl-iters 10)
and benchmarks
(define ack-iters 10)
(define array1-iters 1)
(define cat-iters 1)
(define string-iters 10)
(define sum1-iters 10)
(define sumloop-iters 10)
(define tail-iters 1)
(define wc-iters 1)
; C benchmarks
(define fft-iters 2000)
(define fib-iters 5)
(define fibfp-iters 2)
(define mbrot-iters 100)
(define nucleic-iters 5)
(define pnpoly-iters 100000)
(define sum-iters 20000)
(define sumfp-iters 20000)
(define tfib-iters 20)
; Other benchmarks
(define conform-iters 40)
(define dynamic-iters 20)
(define earley-iters 200)
(define fibc-iters 500)
(define graphs-iters 300)
(define lattice-iters 1)
(define matrix-iters 400)
(define maze-iters 4000)
(define mazefun-iters 1000)
(define nqueens-iters 2000)
(define paraffins-iters 1000)
(define peval-iters 200)
(define pi-iters 2)
(define primes-iters 100000)
(define ray-iters 5)
(define scheme-iters 20000)
(define simplex-iters 100000)
(define slatex-iters 20)
(define perm9-iters 10)
(define nboyer-iters 100)
(define sboyer-iters 100)
(define gcbench-iters 1)
(define compiler-iters 300)
(define nbody-iters 1)
(define fftrad4-iters 4)
;;; PNPOLY - Test if a point is contained in a 2D polygon.
(define (pt-in-poly2 xp yp x y)
(let loop ((c #f) (i (- (FLOATvector-length xp) 1)) (j 0))
(if (< i 0)
c
(if (or (and (or (FLOAT> (FLOATvector-ref yp i) y)
(FLOAT>= y (FLOATvector-ref yp j)))
(or (FLOAT> (FLOATvector-ref yp j) y)
(FLOAT>= y (FLOATvector-ref yp i))))
(FLOAT>= x
(FLOAT+ (FLOATvector-ref xp i)
(FLOAT/ (FLOAT*
(FLOAT- (FLOATvector-ref xp j)
(FLOATvector-ref xp i))
(FLOAT- y (FLOATvector-ref yp i)))
(FLOAT- (FLOATvector-ref yp j)
(FLOATvector-ref yp i))))))
(loop c (- i 1) i)
(loop (not c) (- i 1) i)))))
(define (run)
(let ((count 0)
(xp (FLOATvector-const 0. 1. 1. 0. 0. 1. -.5 -1. -1. -2. -2.5
-2. -1.5 -.5 1. 1. 0. -.5 -1. -.5))
(yp (FLOATvector-const 0. 0. 1. 1. 2. 3. 2. 3. 0. -.5 -1.
-1.5 -2. -2. -1.5 -1. -.5 -1. -1. -.5)))
(if (pt-in-poly2 xp yp .5 .5) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp .5 1.5) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp -.5 1.5) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp .75 2.25) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp 0. 2.01) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp -.5 2.5) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp -1. -.5) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp -1.5 .5) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp -2.25 -1.) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp .5 -.25) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp .5 -1.25) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp -.5 -2.5) (set! count (+ count 1)))
count))
(define (main . args)
(run-benchmark
"pnpoly"
pnpoly-iters
(lambda (result)
(and (number? result) (= result 6)))
(lambda () (lambda () (run)))))
(main)
| null | https://raw.githubusercontent.com/bsaleil/lc/ee7867fd2bdbbe88924300e10b14ea717ee6434b/tools/benchtimes/resultVMIL-lc-gsc-lc/LCf64naive/pnpoly.scm.scm | scheme | ------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Gabriel benchmarks
C benchmarks
Other benchmarks
PNPOLY - Test if a point is contained in a 2D polygon. | Macros
(##define-macro (def-macro form . body)
`(##define-macro ,form (let () ,@body)))
(def-macro (FLOATvector-const . lst) `',(list->f64vector lst))
(def-macro (FLOATvector? x) `(f64vector? ,x))
(def-macro (FLOATvector . lst) `(f64vector ,@lst))
(def-macro (FLOATmake-vector n . init) `(make-f64vector ,n ,@init))
(def-macro (FLOATvector-ref v i) `(f64vector-ref ,v ,i))
(def-macro (FLOATvector-set! v i x) `(f64vector-set! ,v ,i ,x))
(def-macro (FLOATvector-length v) `(f64vector-length ,v))
(def-macro (nuc-const . lst)
`',(list->vector
(map (lambda (x)
(if (vector? x)
(list->f64vector (vector->list x))
x))
lst)))
(def-macro (FLOAT+ . lst) `(+ ,@lst))
(def-macro (FLOAT- . lst) `(- ,@lst))
(def-macro (FLOAT* . lst) `(* ,@lst))
(def-macro (FLOAT/ . lst) `(/ ,@lst))
(def-macro (FLOAT= . lst) `(= ,@lst))
(def-macro (FLOAT< . lst) `(< ,@lst))
(def-macro (FLOAT<= . lst) `(<= ,@lst))
(def-macro (FLOAT> . lst) `(> ,@lst))
(def-macro (FLOAT>= . lst) `(>= ,@lst))
(def-macro (FLOATnegative? . lst) `(negative? ,@lst))
(def-macro (FLOATpositive? . lst) `(positive? ,@lst))
(def-macro (FLOATzero? . lst) `(zero? ,@lst))
(def-macro (FLOATabs . lst) `(abs ,@lst))
(def-macro (FLOATsin . lst) `(sin ,@lst))
(def-macro (FLOATcos . lst) `(cos ,@lst))
(def-macro (FLOATatan . lst) `(atan ,@lst))
(def-macro (FLOATsqrt . lst) `(sqrt ,@lst))
(def-macro (FLOATmin . lst) `(min ,@lst))
(def-macro (FLOATmax . lst) `(max ,@lst))
(def-macro (FLOATround . lst) `(round ,@lst))
(def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst))
(def-macro (GENERIC+ . lst) `(+ ,@lst))
(def-macro (GENERIC- . lst) `(- ,@lst))
(def-macro (GENERIC* . lst) `(* ,@lst))
(def-macro (GENERIC/ . lst) `(/ ,@lst))
(def-macro (GENERICquotient . lst) `(quotient ,@lst))
(def-macro (GENERICremainder . lst) `(remainder ,@lst))
(def-macro (GENERICmodulo . lst) `(modulo ,@lst))
(def-macro (GENERIC= . lst) `(= ,@lst))
(def-macro (GENERIC< . lst) `(< ,@lst))
(def-macro (GENERIC<= . lst) `(<= ,@lst))
(def-macro (GENERIC> . lst) `(> ,@lst))
(def-macro (GENERIC>= . lst) `(>= ,@lst))
(def-macro (GENERICexpt . lst) `(expt ,@lst))
Functions used by LC to get time info
(def-macro (##lc-time expr)
(let ((sym (gensym)))
`(let ((r (##lc-exec-stats (lambda () ,expr))))
(##print-perm-string "CPU time: ")
(##print-double (+ (cdr (assoc "User time" (cdr r)))
(cdr (assoc "Sys time" (cdr r)))))
(##print-perm-string "\n")
(##print-perm-string "GC CPU time: ")
(##print-double (+ (cdr (assoc "GC user time" (cdr r)))
(cdr (assoc "GC sys time" (cdr r)))))
(##print-perm-string "\n")
(map (lambda (el)
(##print-perm-string (car el))
(##print-perm-string ": ")
(##print-double (cdr el))
(##print-perm-string "\n"))
(cdr r))
r)))
(define (##lc-exec-stats thunk)
(let* ((at-start (##process-statistics))
(result (thunk))
(at-end (##process-statistics)))
(define (get-info msg idx)
(cons msg
(- (f64vector-ref at-end idx)
(f64vector-ref at-start idx))))
(list
result
(get-info "User time" 0)
(get-info "Sys time" 1)
(get-info "Real time" 2)
(get-info "GC user time" 3)
(get-info "GC sys time" 4)
(get-info "GC real time" 5)
(get-info "Nb gcs" 6))))
(define (run-bench name count ok? run)
(let loop ((i count) (result '(undefined)))
(if (< 0 i)
(loop (- i 1) (run))
result)))
(define (run-benchmark name count ok? run-maker . args)
(let ((run (apply run-maker args)))
(let ((result (car (##lc-time (run-bench name count ok? run)))))
(if (not (ok? result))
(begin
(display "*** wrong result ***")
(newline)
(display "*** got: ")
(write result)
(newline))))))
(define boyer-iters 20)
(define browse-iters 600)
(define cpstak-iters 1000)
(define ctak-iters 100)
(define dderiv-iters 2000000)
(define deriv-iters 2000000)
(define destruc-iters 500)
(define diviter-iters 1000000)
(define divrec-iters 1000000)
(define puzzle-iters 100)
(define tak-iters 2000)
(define takl-iters 300)
(define trav1-iters 100)
(define trav2-iters 20)
(define triangl-iters 10)
and benchmarks
(define ack-iters 10)
(define array1-iters 1)
(define cat-iters 1)
(define string-iters 10)
(define sum1-iters 10)
(define sumloop-iters 10)
(define tail-iters 1)
(define wc-iters 1)
(define fft-iters 2000)
(define fib-iters 5)
(define fibfp-iters 2)
(define mbrot-iters 100)
(define nucleic-iters 5)
(define pnpoly-iters 100000)
(define sum-iters 20000)
(define sumfp-iters 20000)
(define tfib-iters 20)
(define conform-iters 40)
(define dynamic-iters 20)
(define earley-iters 200)
(define fibc-iters 500)
(define graphs-iters 300)
(define lattice-iters 1)
(define matrix-iters 400)
(define maze-iters 4000)
(define mazefun-iters 1000)
(define nqueens-iters 2000)
(define paraffins-iters 1000)
(define peval-iters 200)
(define pi-iters 2)
(define primes-iters 100000)
(define ray-iters 5)
(define scheme-iters 20000)
(define simplex-iters 100000)
(define slatex-iters 20)
(define perm9-iters 10)
(define nboyer-iters 100)
(define sboyer-iters 100)
(define gcbench-iters 1)
(define compiler-iters 300)
(define nbody-iters 1)
(define fftrad4-iters 4)
(define (pt-in-poly2 xp yp x y)
(let loop ((c #f) (i (- (FLOATvector-length xp) 1)) (j 0))
(if (< i 0)
c
(if (or (and (or (FLOAT> (FLOATvector-ref yp i) y)
(FLOAT>= y (FLOATvector-ref yp j)))
(or (FLOAT> (FLOATvector-ref yp j) y)
(FLOAT>= y (FLOATvector-ref yp i))))
(FLOAT>= x
(FLOAT+ (FLOATvector-ref xp i)
(FLOAT/ (FLOAT*
(FLOAT- (FLOATvector-ref xp j)
(FLOATvector-ref xp i))
(FLOAT- y (FLOATvector-ref yp i)))
(FLOAT- (FLOATvector-ref yp j)
(FLOATvector-ref yp i))))))
(loop c (- i 1) i)
(loop (not c) (- i 1) i)))))
(define (run)
(let ((count 0)
(xp (FLOATvector-const 0. 1. 1. 0. 0. 1. -.5 -1. -1. -2. -2.5
-2. -1.5 -.5 1. 1. 0. -.5 -1. -.5))
(yp (FLOATvector-const 0. 0. 1. 1. 2. 3. 2. 3. 0. -.5 -1.
-1.5 -2. -2. -1.5 -1. -.5 -1. -1. -.5)))
(if (pt-in-poly2 xp yp .5 .5) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp .5 1.5) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp -.5 1.5) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp .75 2.25) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp 0. 2.01) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp -.5 2.5) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp -1. -.5) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp -1.5 .5) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp -2.25 -1.) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp .5 -.25) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp .5 -1.25) (set! count (+ count 1)))
(if (pt-in-poly2 xp yp -.5 -2.5) (set! count (+ count 1)))
count))
(define (main . args)
(run-benchmark
"pnpoly"
pnpoly-iters
(lambda (result)
(and (number? result) (= result 6)))
(lambda () (lambda () (run)))))
(main)
|
ae38bd8ca6a8cab5d7a6089392c4c02e741eb26c0a90e3f0bca07917387d7cb2 | a-sassmannshausen/guile-config | config.scm | config.scm --- tests for config -*- coding : utf-8 -*-
;;
Copyright ( C ) 2015 < >
;;
Author : < >
Created : 23 November 2016
;;
;; This file is part of Config.
;;
;; Config 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.
;;
;; Config 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 config; if not, contact:
;;
;; Free Software Foundation Voice: +1-617-542-5942
59 Temple Place - Suite 330 Fax : +1 - 617 - 542 - 2652
Boston , MA 02111 - 1307 , USA
;;; Commentary:
;;
;; Unit tests for config.scm.
;;
;; Source-file: config.scm
;;
;;; Code:
(define-module (tests config)
#:use-module (config)
#:use-module (config api)
#:use-module (config parser sexp)
#:use-module (ice-9 match)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-26)
#:use-module (srfi srfi-64)
#:use-module (tests quickcheck)
#:use-module (tests quickcheck-defs))
;;;; Tests
(test-begin "config")
(quickcheck-assert "Configurations?"
configuration? ($configuration))
(quickcheck-assert
"Getopt-Config?"
(lambda (config)
(codex? (getopt-config `(,(symbol->string
(configuration-name config)))
config)))
($configuration))
(quickcheck-assert
"No config files created?"
(lambda (config)
(and (codex? (getopt-config `(,(symbol->string
(configuration-name config)))
config))
(not (file-exists?
(path-given (configuration-directory config))))))
($configuration #:keywords (list $secret $switch) #:parser sexp-parser))
(quickcheck-assert
"Config files created?"
(lambda (config)
(and (codex? (getopt-config `(,(symbol->string
(configuration-name config)))
config))
(cond ((null? (configuration-keywords config)) #t)
((file-exists? (path-given (configuration-directory config))) #t)
(else #f))))
($configuration #:keywords (list $setting) #:parser sexp-parser))
(quickcheck-assert
"Multi config files created?"
(lambda (config)
(and (codex? (getopt-config `(,(symbol->string
(configuration-name config)))
config))
(or (null? (configuration-keywords config))
(every file-exists?
(map path-given (configuration-directory config))))))
($configuration #:keywords (list $setting) #:parser sexp-parser
#:directories
(($short-list
(lambda _
(path (given (string-append (tmpnam)
file-name-separator-string))
(eager? #t)))))))
(system "rm -r /tmp/file*")
(test-end "config")
| null | https://raw.githubusercontent.com/a-sassmannshausen/guile-config/b05957743ee8ab8d111683697a56e46a82429b6f/tests/config.scm | scheme |
This file is part of Config.
Config is free software; you can redistribute it and/or modify it under the
either version 3 of the License , or ( at your option ) any later
version.
Config 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.
with config; if not, contact:
Free Software Foundation Voice: +1-617-542-5942
Commentary:
Unit tests for config.scm.
Source-file: config.scm
Code:
Tests | config.scm --- tests for config -*- coding : utf-8 -*-
Copyright ( C ) 2015 < >
Author : < >
Created : 23 November 2016
terms of the GNU General Public License as published by the Free Software
You should have received a copy of the GNU General Public License along
59 Temple Place - Suite 330 Fax : +1 - 617 - 542 - 2652
Boston , MA 02111 - 1307 , USA
(define-module (tests config)
#:use-module (config)
#:use-module (config api)
#:use-module (config parser sexp)
#:use-module (ice-9 match)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-26)
#:use-module (srfi srfi-64)
#:use-module (tests quickcheck)
#:use-module (tests quickcheck-defs))
(test-begin "config")
(quickcheck-assert "Configurations?"
configuration? ($configuration))
(quickcheck-assert
"Getopt-Config?"
(lambda (config)
(codex? (getopt-config `(,(symbol->string
(configuration-name config)))
config)))
($configuration))
(quickcheck-assert
"No config files created?"
(lambda (config)
(and (codex? (getopt-config `(,(symbol->string
(configuration-name config)))
config))
(not (file-exists?
(path-given (configuration-directory config))))))
($configuration #:keywords (list $secret $switch) #:parser sexp-parser))
(quickcheck-assert
"Config files created?"
(lambda (config)
(and (codex? (getopt-config `(,(symbol->string
(configuration-name config)))
config))
(cond ((null? (configuration-keywords config)) #t)
((file-exists? (path-given (configuration-directory config))) #t)
(else #f))))
($configuration #:keywords (list $setting) #:parser sexp-parser))
(quickcheck-assert
"Multi config files created?"
(lambda (config)
(and (codex? (getopt-config `(,(symbol->string
(configuration-name config)))
config))
(or (null? (configuration-keywords config))
(every file-exists?
(map path-given (configuration-directory config))))))
($configuration #:keywords (list $setting) #:parser sexp-parser
#:directories
(($short-list
(lambda _
(path (given (string-append (tmpnam)
file-name-separator-string))
(eager? #t)))))))
(system "rm -r /tmp/file*")
(test-end "config")
|
58a89a548b77edbc3ca3c17207bed3519f1c7de5907c7649a1ecb627c377fa4e | domenkozar/paddle | SubscriptionUsersUpdate.hs | -- -reference/subscription-api/subscription-users/updateuser
module Paddle.Client.SubscriptionUsersUpdate where
import Data.Aeson (ToJSON, toJSON, genericToJSON)
import Protolude
import Prelude ()
import Paddle.FieldModifier (customJSONOptions)
data SubscriptionUsersUpdate = SubscriptionUsersUpdate
{ vendorId :: Int
, vendorAuthCode :: Text
, subscriptionId :: Integer
, planId :: Maybe Integer
, prorate :: Maybe Bool
, billImmediately :: Maybe Bool
} deriving (Show, Generic)
instance ToJSON SubscriptionUsersUpdate where
toJSON = genericToJSON customJSONOptions
| null | https://raw.githubusercontent.com/domenkozar/paddle/4f20a7b3cebe72d68f18d7dd72ef802f4b1821c4/src/Paddle/Client/SubscriptionUsersUpdate.hs | haskell | -reference/subscription-api/subscription-users/updateuser | module Paddle.Client.SubscriptionUsersUpdate where
import Data.Aeson (ToJSON, toJSON, genericToJSON)
import Protolude
import Prelude ()
import Paddle.FieldModifier (customJSONOptions)
data SubscriptionUsersUpdate = SubscriptionUsersUpdate
{ vendorId :: Int
, vendorAuthCode :: Text
, subscriptionId :: Integer
, planId :: Maybe Integer
, prorate :: Maybe Bool
, billImmediately :: Maybe Bool
} deriving (Show, Generic)
instance ToJSON SubscriptionUsersUpdate where
toJSON = genericToJSON customJSONOptions
|
92f3573146ae956224194d25227fe88c868d06a0a9d4cfaa3bc657680d438e81 | facebook/duckling | Tests.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.Email.Tests
( tests
) where
import Data.String
import Prelude
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Email.Corpus
import Duckling.Testing.Asserts
import qualified Duckling.Email.DE.Tests as DE
import qualified Duckling.Email.EN.Tests as EN
import qualified Duckling.Email.FR.Tests as FR
import qualified Duckling.Email.IS.Tests as IS
import qualified Duckling.Email.IT.Tests as IT
tests :: TestTree
tests = testGroup "Email Tests"
[ makeCorpusTest [Seal Email] corpus
, makeNegativeCorpusTest [Seal Email] negativeCorpus
, DE.tests
, EN.tests
, FR.tests
, IS.tests
, IT.tests
]
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/tests/Duckling/Email/Tests.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. | Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.Email.Tests
( tests
) where
import Data.String
import Prelude
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Email.Corpus
import Duckling.Testing.Asserts
import qualified Duckling.Email.DE.Tests as DE
import qualified Duckling.Email.EN.Tests as EN
import qualified Duckling.Email.FR.Tests as FR
import qualified Duckling.Email.IS.Tests as IS
import qualified Duckling.Email.IT.Tests as IT
tests :: TestTree
tests = testGroup "Email Tests"
[ makeCorpusTest [Seal Email] corpus
, makeNegativeCorpusTest [Seal Email] negativeCorpus
, DE.tests
, EN.tests
, FR.tests
, IS.tests
, IT.tests
]
|
5a0a3a1c6822786c0b8c22f92be8ba0e987682ea93b881b890d6bc57142ccafb | IagoAbal/haskell-z3 | ParserInterface.hs | | Parse AST from SMTLIB string
module Example.Monad.ParserInterface
( run )
where
import Z3.Monad
run :: IO ()
run = evalZ3 script >>= print
-- Toy example SMTLIB string
smtStr1 :: String
smtStr1 = "(declare-const x Int)\n(assert (< x 5))"
smtStr2 :: String
smtStr2 = "(declare-const x Int)\n(assert (> x 5))"
script :: Z3 Result
script = do
[l] <- parseSMTLib2String smtStr1 [] [] [] []
[r] <- parseSMTLib2String smtStr2 [] [] [] []
eq <- mkEq l r
assert l
assert r
assert eq
check
| null | https://raw.githubusercontent.com/IagoAbal/haskell-z3/247dac33c82b52f6ca568c1cdb3ec5153351394d/examples/Example/Monad/ParserInterface.hs | haskell | Toy example SMTLIB string | | Parse AST from SMTLIB string
module Example.Monad.ParserInterface
( run )
where
import Z3.Monad
run :: IO ()
run = evalZ3 script >>= print
smtStr1 :: String
smtStr1 = "(declare-const x Int)\n(assert (< x 5))"
smtStr2 :: String
smtStr2 = "(declare-const x Int)\n(assert (> x 5))"
script :: Z3 Result
script = do
[l] <- parseSMTLib2String smtStr1 [] [] [] []
[r] <- parseSMTLib2String smtStr2 [] [] [] []
eq <- mkEq l r
assert l
assert r
assert eq
check
|
1edadc92f0cdf39257e6ce4e82258d49b7d3c9633fb3882057ab92e53ee66f70 | ixmatus/prizm | Types.hs | # LANGUAGE FlexibleInstances #
{-# LANGUAGE TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Prizm.Color.RGB.Types
Copyright : ( C ) 2017 Parnell Springmeyer
-- License : BSD3
Maintainer : Parnell Springmeyer < >
-- Stability : stable
-----------------------------------------------------------------------------
module Data.Prizm.Color.RGB.Types where
import Data.Prizm.Types
import Data.Word
| Clamp a ' Word8 ' with an upper - bound of 255 and a lower - bound of
-- 0.
clamp :: Integral a => a -> a
clamp i = max (min i 255) 0
| A color in the 256 - cubed @RGB@ color space .
newtype RGB = RGB {unRGB :: ColorCoord Word8 }
deriving (Eq, Ord, Show)
| Produce a 256 - cubed ' RGB ' color .
--
NB : this function clamps each argument to the 0 - 255 range .
mkRGB :: Int -- ^ Red color channel
-> Int -- ^ Green color channel
-> Int -- ^ Blue color channel
-> RGB
mkRGB r g b = RGB ((fromIntegral . clamp) <$> ColorCoord (r,g,b))
| null | https://raw.githubusercontent.com/ixmatus/prizm/8baceff70b44a14bc67bac9efdd5270620567cec/src/Data/Prizm/Color/RGB/Types.hs | haskell | # LANGUAGE TypeFamilies #
---------------------------------------------------------------------------
|
Module : Data.Prizm.Color.RGB.Types
License : BSD3
Stability : stable
---------------------------------------------------------------------------
0.
^ Red color channel
^ Green color channel
^ Blue color channel | # LANGUAGE FlexibleInstances #
Copyright : ( C ) 2017 Parnell Springmeyer
Maintainer : Parnell Springmeyer < >
module Data.Prizm.Color.RGB.Types where
import Data.Prizm.Types
import Data.Word
| Clamp a ' Word8 ' with an upper - bound of 255 and a lower - bound of
clamp :: Integral a => a -> a
clamp i = max (min i 255) 0
| A color in the 256 - cubed @RGB@ color space .
newtype RGB = RGB {unRGB :: ColorCoord Word8 }
deriving (Eq, Ord, Show)
| Produce a 256 - cubed ' RGB ' color .
NB : this function clamps each argument to the 0 - 255 range .
-> RGB
mkRGB r g b = RGB ((fromIntegral . clamp) <$> ColorCoord (r,g,b))
|
e1ab545159f438ee2dad2fc1310def96ab5c1f78781df73271e8e28ad73c6237 | input-output-hk/project-icarus-importer | Context.hs | | Whole in - memory state of UpdateSystem .
module Pos.Update.Context
( UpdateContext(..)
, mkUpdateContext
) where
import Universum
import Pos.Core (HasProtocolConstants)
import Pos.DB.Class (MonadDBRead)
import Pos.Slotting (MonadSlots)
import Pos.Update.MemState.Types (MemVar, newMemVar)
import Pos.Update.Poll.Types (ConfirmedProposalState)
data UpdateContext = UpdateContext
{
-- | A semaphore which is unlocked when update data is downloaded and
-- ready to apply.
ucDownloadedUpdate :: !(MVar ConfirmedProposalState)
| A lock which allows only one thread to download an update .
, ucDownloadLock :: !(MVar ())
-- | In-memory state of update-system-as-block-component.
, ucMemState :: !MemVar
}
| Create initial ' UpdateContext ' .
mkUpdateContext
:: forall ctx m.
( HasProtocolConstants
, MonadIO m
, MonadDBRead m
, MonadSlots ctx m
)
=> m UpdateContext
mkUpdateContext = UpdateContext <$> newEmptyMVar <*> newMVar () <*> newMemVar
| null | https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/update/Pos/Update/Context.hs | haskell | | A semaphore which is unlocked when update data is downloaded and
ready to apply.
| In-memory state of update-system-as-block-component. | | Whole in - memory state of UpdateSystem .
module Pos.Update.Context
( UpdateContext(..)
, mkUpdateContext
) where
import Universum
import Pos.Core (HasProtocolConstants)
import Pos.DB.Class (MonadDBRead)
import Pos.Slotting (MonadSlots)
import Pos.Update.MemState.Types (MemVar, newMemVar)
import Pos.Update.Poll.Types (ConfirmedProposalState)
data UpdateContext = UpdateContext
{
ucDownloadedUpdate :: !(MVar ConfirmedProposalState)
| A lock which allows only one thread to download an update .
, ucDownloadLock :: !(MVar ())
, ucMemState :: !MemVar
}
| Create initial ' UpdateContext ' .
mkUpdateContext
:: forall ctx m.
( HasProtocolConstants
, MonadIO m
, MonadDBRead m
, MonadSlots ctx m
)
=> m UpdateContext
mkUpdateContext = UpdateContext <$> newEmptyMVar <*> newMVar () <*> newMemVar
|
bb0598459a911080d40fb86e5acf552a48a76bdd1822bd8a7fa77ce6a87b75b0 | dalaing/little-languages | Rules.hs | {-# LANGUAGE GADTs #-}
module Rules where
import Control.Applicative
import Data.Foldable
import Data.List (partition)
import Data.Maybe (fromMaybe)
import Data.Profunctor
import Test.QuickCheck
- Rules should have a Gen t that matches the rule
- We could use a GADT to make the matching prism available
-
- Would be nice to be able to combine Gen 's in the same way that we
- combine prisms - ie have an applicative / alternative for Matchers
-
- Want to check that
- this gen matches with this matcher
- this gen matches none of the other rules
- Possibly split into axiom / step
-
- the precondition being able to step / the term not being a value should
- be required for Steps
-
- We want to check that the rule survives inside eval
-
- We want these for values as well , so that we can get the right gens and
- printers
-
- Rules should have a Gen t that matches the rule
- We could use a GADT to make the matching prism available
-
- Would be nice to be able to combine Gen's in the same way that we
- combine prisms - ie have an applicative / alternative for Matchers
-
- Want to check that
- this gen matches with this matcher
- this gen matches none of the other rules
- Possibly split into axiom / step
-
- the precondition being able to step / the term not being a value should
- be required for Steps
-
- We want to check that the rule survives inside eval
-
- We want these for values as well, so that we can get the right gens and
- printers
- -}
-- for app
-- data R t a = R { s :: t -> t , a :: Rule t a }
-- for alt
-- data R t a = R { s :: t -> t , a :: [Rule t a] }
--
lift this one into Step rather than Axiom
-- step :: R (t -> t)
data R t a b = R { s :: t -> Maybe t, rules :: a -> [Maybe b] }
data Matcher a where
Matcher :: String -> Gen a -> ((a -> Maybe a) -> a -> Maybe t) -> (t -> a) -> Matcher a
matcherStep :: Matcher a -> (a -> Maybe a) -> a -> Maybe a
matcherStep (Matcher _ _ f g) step a = fmap g (f step a)
matcherEval :: [Matcher a] -> a -> Maybe a
matcherEval ms =
let
step x = asum . map (\m -> matcherStep m step x) $ ms
in
step
data Rs a b = Rs (a -> [Maybe b])
instance Functor (Rs a) where
fmap f (Rs g) = Rs (fmap (fmap (fmap f)) g)
instance Applicative (Rs a) where
pure = Rs . pure . pure . pure
Rs af <*> Rs ax = Rs $ liftA2 (liftA2 (<*>)) af ax
instance Alternative (Rs a) where
empty = Rs $ const empty
Rs af <|> Rs ax = Rs $ \a -> af a <|> ax a
-- would be nice to have a combinator to access the step function, which
-- pushes something from an axiom to a rule
data Rule t a = Axiom (t -> Maybe a) | Step ((t -> Maybe t) -> t -> Maybe a)
instance Functor (Rule t) where
fmap f (Axiom g) = Axiom $ fmap (fmap f) g
fmap f (Step g) = Step $ fmap (fmap (fmap f)) g
instance Applicative (Rule t) where
pure = Axiom . pure . pure
-- do we want to use alternative here ?
Axiom f <*> Axiom x = Axiom $ liftA2 (<*>) f x
Axiom f <*> Step x = Step $ liftA2 (liftA2 (<*>)) (pure f) x
Step f <*> Axiom x = Step $ liftA2 (liftA2 (<*>)) f (pure x)
Step f <*> Step x = Step $ liftA2 (liftA2 (<*>)) f x
data Rules t a = Rules [Rule t a]
makeEval :: Rules a a -> a -> Maybe a
makeEval (Rules rs) =
let
isAxiom (Axiom _) = True
isAxiom _ = False
(as, ss) = partition isAxiom rs
step x = asum (fmap (\(Axiom f) -> f x) as) <|> asum (fmap (\(Step f) -> f step x) ss)
in
step
TODO fix point of step function , optionally with history
| null | https://raw.githubusercontent.com/dalaing/little-languages/9f089f646a5344b8f7178700455a36a755d29b1f/code/old/prototypes/arith/src/Rules.hs | haskell | # LANGUAGE GADTs #
for app
data R t a = R { s :: t -> t , a :: Rule t a }
for alt
data R t a = R { s :: t -> t , a :: [Rule t a] }
step :: R (t -> t)
would be nice to have a combinator to access the step function, which
pushes something from an axiom to a rule
do we want to use alternative here ? | module Rules where
import Control.Applicative
import Data.Foldable
import Data.List (partition)
import Data.Maybe (fromMaybe)
import Data.Profunctor
import Test.QuickCheck
- Rules should have a Gen t that matches the rule
- We could use a GADT to make the matching prism available
-
- Would be nice to be able to combine Gen 's in the same way that we
- combine prisms - ie have an applicative / alternative for Matchers
-
- Want to check that
- this gen matches with this matcher
- this gen matches none of the other rules
- Possibly split into axiom / step
-
- the precondition being able to step / the term not being a value should
- be required for Steps
-
- We want to check that the rule survives inside eval
-
- We want these for values as well , so that we can get the right gens and
- printers
-
- Rules should have a Gen t that matches the rule
- We could use a GADT to make the matching prism available
-
- Would be nice to be able to combine Gen's in the same way that we
- combine prisms - ie have an applicative / alternative for Matchers
-
- Want to check that
- this gen matches with this matcher
- this gen matches none of the other rules
- Possibly split into axiom / step
-
- the precondition being able to step / the term not being a value should
- be required for Steps
-
- We want to check that the rule survives inside eval
-
- We want these for values as well, so that we can get the right gens and
- printers
- -}
lift this one into Step rather than Axiom
data R t a b = R { s :: t -> Maybe t, rules :: a -> [Maybe b] }
data Matcher a where
Matcher :: String -> Gen a -> ((a -> Maybe a) -> a -> Maybe t) -> (t -> a) -> Matcher a
matcherStep :: Matcher a -> (a -> Maybe a) -> a -> Maybe a
matcherStep (Matcher _ _ f g) step a = fmap g (f step a)
matcherEval :: [Matcher a] -> a -> Maybe a
matcherEval ms =
let
step x = asum . map (\m -> matcherStep m step x) $ ms
in
step
data Rs a b = Rs (a -> [Maybe b])
instance Functor (Rs a) where
fmap f (Rs g) = Rs (fmap (fmap (fmap f)) g)
instance Applicative (Rs a) where
pure = Rs . pure . pure . pure
Rs af <*> Rs ax = Rs $ liftA2 (liftA2 (<*>)) af ax
instance Alternative (Rs a) where
empty = Rs $ const empty
Rs af <|> Rs ax = Rs $ \a -> af a <|> ax a
data Rule t a = Axiom (t -> Maybe a) | Step ((t -> Maybe t) -> t -> Maybe a)
instance Functor (Rule t) where
fmap f (Axiom g) = Axiom $ fmap (fmap f) g
fmap f (Step g) = Step $ fmap (fmap (fmap f)) g
instance Applicative (Rule t) where
pure = Axiom . pure . pure
Axiom f <*> Axiom x = Axiom $ liftA2 (<*>) f x
Axiom f <*> Step x = Step $ liftA2 (liftA2 (<*>)) (pure f) x
Step f <*> Axiom x = Step $ liftA2 (liftA2 (<*>)) f (pure x)
Step f <*> Step x = Step $ liftA2 (liftA2 (<*>)) f x
data Rules t a = Rules [Rule t a]
makeEval :: Rules a a -> a -> Maybe a
makeEval (Rules rs) =
let
isAxiom (Axiom _) = True
isAxiom _ = False
(as, ss) = partition isAxiom rs
step x = asum (fmap (\(Axiom f) -> f x) as) <|> asum (fmap (\(Step f) -> f step x) ss)
in
step
TODO fix point of step function , optionally with history
|
0ad843216e1bd5bc01061ee91b12684a65f6c41563b5276100746e72550f46e6 | haskell/aeson | Internal.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE CPP #
# LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
#if __GLASGOW_HASKELL__ <= 800 && __GLASGOW_HASKELL__ >= 706
-- Work around a compiler bug
{-# OPTIONS_GHC -fsimpl-tick-factor=300 #-}
#endif
-- |
Module : Data . Aeson . . Internal
Copyright : ( c ) 2011 - 2016
( c ) 2011 MailRank , Inc.
License : BSD3
Maintainer : < >
-- Stability: experimental
-- Portability: portable
--
-- Efficiently and correctly parse a JSON string. The string must be
encoded as UTF-8 .
module Data.Aeson.Parser.Internal
(
-- * Lazy parsers
json, jsonEOF
, jsonWith
, jsonLast
, jsonAccum
, jsonNoDup
, value
, jstring
, jstring_
, scientific
-- * Strict parsers
, json', jsonEOF'
, jsonWith'
, jsonLast'
, jsonAccum'
, jsonNoDup'
, value'
-- * Helpers
, decodeWith
, decodeStrictWith
, eitherDecodeWith
, eitherDecodeStrictWith
-- ** Handling objects with duplicate keys
, fromListAccum
, parseListNoDup
-- * Text literal unescaping
, unescapeText
) where
import Prelude.Compat
import Control.Applicative ((<|>))
import Control.Monad (void, when)
import Data.Aeson.Types.Internal (IResult(..), JSONPath, Object, Result(..), Value(..), Key)
import qualified Data.Aeson.KeyMap as KM
import qualified Data.Aeson.Key as Key
import Data.Attoparsec.ByteString.Char8 (Parser, char, decimal, endOfInput, isDigit_w8, signed, string)
import Data.Function (fix)
import Data.Functor.Compat (($>))
import Data.Scientific (Scientific)
import Data.Text (Text)
import Data.Vector (Vector)
import qualified Data.Vector as Vector (empty, fromList, fromListN, reverse)
import qualified Data.Attoparsec.ByteString as A
import qualified Data.Attoparsec.Lazy as L
import qualified Data.ByteString as B
import qualified Data.ByteString.Unsafe as B
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Lazy.Char8 as C
import qualified Data.ByteString.Builder as B
import qualified Data.Scientific as Sci
import Data.Aeson.Parser.Unescape (unescapeText)
import Data.Aeson.Internal.Integer
import Data.Aeson.Internal.Text
import Data.Aeson.Internal.Word8
-- $setup
-- >>> :set -XOverloadedStrings
> > > import Data . Aeson . Types
-------------------------------------------------------------------------------
Parsers
-------------------------------------------------------------------------------
-- | Parse any JSON value.
--
The conversion of a parsed value to a value is deferred
until the value is needed . This may improve performance if
-- only a subset of the results of conversions are needed, but at a
-- cost in thunk allocation.
--
This function is an alias for ' value ' . In aeson 0.8 and earlier , it
-- parsed only object or array types, in conformance with the
now - obsolete RFC 4627 .
--
-- ==== Warning
--
If an object contains duplicate keys , only the first one will be kept .
-- For a more flexible alternative, see 'jsonWith'.
json :: Parser Value
json = value
-- | Parse any JSON value.
--
-- This is a strict version of 'json' which avoids building up thunks
-- during parsing; it performs all conversions immediately. Prefer
-- this version if most of the JSON data needs to be accessed.
--
This function is an alias for ' value '' . In aeson 0.8 and earlier , it
-- parsed only object or array types, in conformance with the
now - obsolete RFC 4627 .
--
-- ==== Warning
--
If an object contains duplicate keys , only the first one will be kept .
-- For a more flexible alternative, see 'jsonWith''.
json' :: Parser Value
json' = value'
-- Open recursion: object_, object_', array_, array_' are parameterized by the
-- toplevel Value parser to be called recursively, to keep the parameter
-- mkObject outside of the recursive loop for proper inlining.
object_ :: ([(Key, Value)] -> Either String Object) -> Parser Value -> Parser Value
object_ mkObject val = Object <$> objectValues mkObject key val
{-# INLINE object_ #-}
object_' :: ([(Key, Value)] -> Either String Object) -> Parser Value -> Parser Value
object_' mkObject val' = do
!vals <- objectValues mkObject key' val'
return (Object vals)
where
key' = do
!s <- key
return s
{-# INLINE object_' #-}
objectValues :: ([(Key, Value)] -> Either String Object)
-> Parser Key -> Parser Value -> Parser (KM.KeyMap Value)
objectValues mkObject str val = do
skipSpace
w <- A.peekWord8'
if w == W8_CLOSE_CURLY
then A.anyWord8 >> return KM.empty
else loop []
where
Why use acc pattern here , you may ask ? because then the underlying ' KM.fromList '
-- implementation can make use of mutation when constructing a map. For example,
' ` uses ' unsafeInsert ' and it 's much faster because it 's doing in place
update to the ' ' !
loop acc = do
k <- (str A.<?> "object key") <* skipSpace <* (char ':' A.<?> "':'")
v <- (val A.<?> "object value") <* skipSpace
ch <- A.satisfy (\w -> w == W8_COMMA || w == W8_CLOSE_CURLY) A.<?> "',' or '}'"
let acc' = (k, v) : acc
if ch == W8_COMMA
then skipSpace >> loop acc'
else case mkObject acc' of
Left err -> fail err
Right obj -> pure obj
# INLINE objectValues #
array_ :: Parser Value -> Parser Value
array_ val = Array <$> arrayValues val
{-# INLINE array_ #-}
array_' :: Parser Value -> Parser Value
array_' val = do
!vals <- arrayValues val
return (Array vals)
{-# INLINE array_' #-}
arrayValues :: Parser Value -> Parser (Vector Value)
arrayValues val = do
skipSpace
w <- A.peekWord8'
if w == W8_CLOSE_SQUARE
then A.anyWord8 >> return Vector.empty
else loop [] 1
where
loop acc !len = do
v <- (val A.<?> "json list value") <* skipSpace
ch <- A.satisfy (\w -> w == W8_COMMA || w == W8_CLOSE_SQUARE) A.<?> "',' or ']'"
if ch == W8_COMMA
then skipSpace >> loop (v:acc) (len+1)
else return (Vector.reverse (Vector.fromListN len (v:acc)))
# INLINE arrayValues #
-- | Parse any JSON value. Synonym of 'json'.
value :: Parser Value
value = jsonWith (pure . KM.fromList)
-- | Parse any JSON value.
--
-- This parser is parameterized by a function to construct an 'Object'
-- from a raw list of key-value pairs, where duplicates are preserved.
-- The pairs appear in __reverse order__ from the source.
--
-- ==== __Examples__
--
' json ' keeps only the first occurrence of each key , using ' Data . Aeson . KeyMap.fromList ' .
--
-- @
-- 'json' = 'jsonWith' ('Right' '.' 'H.fromList')
-- @
--
-- 'jsonLast' keeps the last occurrence of each key, using
. ' ( ' const ' ' id')@.
--
-- @
' jsonLast ' = ' jsonWith ' ( ' Right ' ' . ' ' . ' ( ' const ' ' i d ' ) )
-- @
--
' ' keeps wraps all values in arrays to keep duplicates , using
-- 'fromListAccum'.
--
-- @
' ' = ' jsonWith ' ( ' Right ' . ' fromListAccum ' )
-- @
--
-- 'jsonNoDup' fails if any object contains duplicate keys, using 'parseListNoDup'.
--
-- @
-- 'jsonNoDup' = 'jsonWith' 'parseListNoDup'
-- @
jsonWith :: ([(Key, Value)] -> Either String Object) -> Parser Value
jsonWith mkObject = fix $ \value_ -> do
skipSpace
w <- A.peekWord8'
case w of
W8_DOUBLE_QUOTE -> A.anyWord8 *> (String <$> jstring_)
W8_OPEN_CURLY -> A.anyWord8 *> object_ mkObject value_
W8_OPEN_SQUARE -> A.anyWord8 *> array_ value_
W8_f -> string "false" $> Bool False
W8_t -> string "true" $> Bool True
W8_n -> string "null" $> Null
_ | w >= W8_0 && w <= W8_9 || w == W8_MINUS
-> Number <$> scientific
| otherwise -> fail "not a valid json value"
{-# INLINE jsonWith #-}
-- | Variant of 'json' which keeps only the last occurrence of every key.
jsonLast :: Parser Value
jsonLast = jsonWith (Right . KM.fromListWith (const id))
-- | Variant of 'json' wrapping all object mappings in 'Array' to preserve
-- key-value pairs with the same keys.
jsonAccum :: Parser Value
jsonAccum = jsonWith (Right . fromListAccum)
-- | Variant of 'json' which fails if any object contains duplicate keys.
jsonNoDup :: Parser Value
jsonNoDup = jsonWith parseListNoDup
-- | @'fromListAccum' kvs@ is an object mapping keys to arrays containing all
-- associated values from the original list @kvs@.
--
> > > fromListAccum [ ( " apple " , ) , ( " apple " , ) , ( " orange " , ) ]
fromList [ ( " apple",Array [ Bool False , ] ) ]
fromListAccum :: [(Key, Value)] -> Object
fromListAccum =
fmap (Array . Vector.fromList . ($ [])) . KM.fromListWith (.) . (fmap . fmap) (:)
-- | @'fromListNoDup' kvs@ fails if @kvs@ contains duplicate keys.
parseListNoDup :: [(Key, Value)] -> Either String Object
parseListNoDup =
KM.traverseWithKey unwrap . KM.fromListWith (\_ _ -> Nothing) . (fmap . fmap) Just
where
unwrap k Nothing = Left $ "found duplicate key: " ++ show k
unwrap _ (Just v) = Right v
-- | Strict version of 'value'. Synonym of 'json''.
value' :: Parser Value
value' = jsonWith' (pure . KM.fromList)
-- | Strict version of 'jsonWith'.
jsonWith' :: ([(Key, Value)] -> Either String Object) -> Parser Value
jsonWith' mkObject = fix $ \value_ -> do
skipSpace
w <- A.peekWord8'
case w of
W8_DOUBLE_QUOTE -> do
!s <- A.anyWord8 *> jstring_
return (String s)
W8_OPEN_CURLY -> A.anyWord8 *> object_' mkObject value_
W8_OPEN_SQUARE -> A.anyWord8 *> array_' value_
W8_f -> string "false" $> Bool False
W8_t -> string "true" $> Bool True
W8_n -> string "null" $> Null
_ | w >= W8_0 && w <= W8_9 || w == W8_MINUS
-> do
!n <- scientific
return (Number n)
| otherwise -> fail "not a valid json value"
{-# INLINE jsonWith' #-}
-- | Variant of 'json'' which keeps only the last occurrence of every key.
jsonLast' :: Parser Value
jsonLast' = jsonWith' (pure . KM.fromListWith (const id))
-- | Variant of 'json'' wrapping all object mappings in 'Array' to preserve
-- key-value pairs with the same keys.
jsonAccum' :: Parser Value
jsonAccum' = jsonWith' (pure . fromListAccum)
-- | Variant of 'json'' which fails if any object contains duplicate keys.
jsonNoDup' :: Parser Value
jsonNoDup' = jsonWith' parseListNoDup
-- | Parse a quoted JSON string.
jstring :: Parser Text
jstring = A.word8 W8_DOUBLE_QUOTE *> jstring_
-- | Parse a JSON Key
key :: Parser Key
key = Key.fromText <$> jstring
-- | Parse a string without a leading quote.
jstring_ :: Parser Text
{-# INLINE jstring_ #-}
jstring_ = do
s <- A.takeWhile (\w -> w /= W8_DOUBLE_QUOTE && w /= W8_BACKSLASH && w >= 0x20 && w < 0x80)
mw <- A.peekWord8
case mw of
Nothing -> fail "string without end"
Just W8_DOUBLE_QUOTE -> A.anyWord8 $> unsafeDecodeASCII s
Just w | w < 0x20 -> fail "unescaped control character"
_ -> jstringSlow s
jstringSlow :: B.ByteString -> Parser Text
# INLINE jstringSlow #
jstringSlow s' = do
s <- A.scan startState go <* A.anyWord8
case unescapeText (B.append s' s) of
Right r -> return r
Left err -> fail $ show err
where
startState = False
go a c
| a = Just False
| c == W8_DOUBLE_QUOTE = Nothing
| otherwise = let a' = c == W8_BACKSLASH
in Just a'
decodeWith :: Parser Value -> (Value -> Result a) -> L.ByteString -> Maybe a
decodeWith p to s =
case L.parse p s of
L.Done _ v -> case to v of
Success a -> Just a
_ -> Nothing
_ -> Nothing
# INLINE decodeWith #
decodeStrictWith :: Parser Value -> (Value -> Result a) -> B.ByteString
-> Maybe a
decodeStrictWith p to s =
case either Error to (A.parseOnly p s) of
Success a -> Just a
_ -> Nothing
# INLINE decodeStrictWith #
eitherDecodeWith :: Parser Value -> (Value -> IResult a) -> L.ByteString
-> Either (JSONPath, String) a
eitherDecodeWith p to s =
case L.parse p s of
L.Done _ v -> case to v of
ISuccess a -> Right a
IError path msg -> Left (path, msg)
L.Fail notparsed ctx msg -> Left ([], buildMsg notparsed ctx msg)
where
buildMsg :: L.ByteString -> [String] -> String -> String
buildMsg notYetParsed [] msg = msg ++ formatErrorLine notYetParsed
buildMsg notYetParsed (expectation:_) msg =
msg ++ ". Expecting " ++ expectation ++ formatErrorLine notYetParsed
{-# INLINE eitherDecodeWith #-}
| Grab the first 100 bytes from the non parsed portion and
-- format to get nicer error messages
formatErrorLine :: L.ByteString -> String
formatErrorLine bs =
C.unpack .
if formatting results in empty ByteString just return that
-- otherwise construct the error message with the bytestring builder
(\bs' ->
if BSL.null bs'
then BSL.empty
else
B.toLazyByteString $
B.stringUtf8 " at '" <> B.lazyByteString bs' <> B.stringUtf8 "'"
) .
-- if newline is present cut at that position
BSL.takeWhile (10 /=) .
remove spaces , CR 's , tabs , backslashes and quotes characters
BSL.filter (`notElem` [9, 13, 32, 34, 47, 92]) .
take 100 bytes
BSL.take 100 $ bs
eitherDecodeStrictWith :: Parser Value -> (Value -> IResult a) -> B.ByteString
-> Either (JSONPath, String) a
eitherDecodeStrictWith p to s =
case either (IError []) to (A.parseOnly p s) of
ISuccess a -> Right a
IError path msg -> Left (path, msg)
# INLINE eitherDecodeStrictWith #
-- $lazy
--
-- The 'json' and 'value' parsers decouple identification from
-- conversion. Identification occurs immediately (so that an invalid
-- JSON document can be rejected as early as possible), but conversion
to a value is deferred until that value is needed .
--
-- This decoupling can be time-efficient if only a smallish subset of
-- elements in a JSON value need to be inspected, since the cost of
conversion is zero for uninspected elements . The trade off is an
-- increase in memory usage, due to allocation of thunks for values
-- that have not yet been converted.
-- $strict
--
-- The 'json'' and 'value'' parsers combine identification with
-- conversion. They consume more CPU cycles up front, but have a
-- smaller memory footprint.
-- | Parse a top-level JSON value followed by optional whitespace and
-- end-of-input. See also: 'json'.
jsonEOF :: Parser Value
jsonEOF = json <* skipSpace <* endOfInput
-- | Parse a top-level JSON value followed by optional whitespace and
-- end-of-input. See also: 'json''.
jsonEOF' :: Parser Value
jsonEOF' = json' <* skipSpace <* endOfInput
-- | The only valid whitespace in a JSON document is space, newline,
-- carriage return, and tab.
skipSpace :: Parser ()
skipSpace = A.skipWhile $ \w -> w == W8_SPACE || w == W8_NL || w == W8_CR || w == W8_TAB
# INLINE skipSpace #
---------------- Copy - pasted and adapted from attoparsec ------------------
-- A strict pair
data SP = SP !Integer {-# UNPACK #-}!Int
decimal0 :: Parser Integer
decimal0 = do
digits <- A.takeWhile1 isDigit_w8
if B.length digits > 1 && B.unsafeHead digits == W8_0
then fail "leading zero"
else return (bsToInteger digits)
-- | Parse a JSON number.
scientific :: Parser Scientific
scientific = do
sign <- A.peekWord8'
let !positive = not (sign == W8_MINUS)
when (sign == W8_PLUS || sign == W8_MINUS) $
void A.anyWord8
n <- decimal0
let f fracDigits = SP (B.foldl' step n fracDigits)
(negate $ B.length fracDigits)
step a w = a * 10 + fromIntegral (w - W8_0)
dotty <- A.peekWord8
SP c e <- case dotty of
Just W8_DOT -> A.anyWord8 *> (f <$> A.takeWhile1 isDigit_w8)
_ -> pure (SP n 0)
let !signedCoeff | positive = c
| otherwise = -c
(A.satisfy (\ex -> case ex of W8_e -> True; W8_E -> True; _ -> False) *>
fmap (Sci.scientific signedCoeff . (e +)) (signed decimal)) <|>
return (Sci.scientific signedCoeff e)
# INLINE scientific #
| null | https://raw.githubusercontent.com/haskell/aeson/78c2338c20d31ba5dd46036d10d6c4815c12185d/src/Data/Aeson/Parser/Internal.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE OverloadedStrings #
Work around a compiler bug
# OPTIONS_GHC -fsimpl-tick-factor=300 #
|
Stability: experimental
Portability: portable
Efficiently and correctly parse a JSON string. The string must be
* Lazy parsers
* Strict parsers
* Helpers
** Handling objects with duplicate keys
* Text literal unescaping
$setup
>>> :set -XOverloadedStrings
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| Parse any JSON value.
only a subset of the results of conversions are needed, but at a
cost in thunk allocation.
parsed only object or array types, in conformance with the
==== Warning
For a more flexible alternative, see 'jsonWith'.
| Parse any JSON value.
This is a strict version of 'json' which avoids building up thunks
during parsing; it performs all conversions immediately. Prefer
this version if most of the JSON data needs to be accessed.
parsed only object or array types, in conformance with the
==== Warning
For a more flexible alternative, see 'jsonWith''.
Open recursion: object_, object_', array_, array_' are parameterized by the
toplevel Value parser to be called recursively, to keep the parameter
mkObject outside of the recursive loop for proper inlining.
# INLINE object_ #
# INLINE object_' #
implementation can make use of mutation when constructing a map. For example,
# INLINE array_ #
# INLINE array_' #
| Parse any JSON value. Synonym of 'json'.
| Parse any JSON value.
This parser is parameterized by a function to construct an 'Object'
from a raw list of key-value pairs, where duplicates are preserved.
The pairs appear in __reverse order__ from the source.
==== __Examples__
@
'json' = 'jsonWith' ('Right' '.' 'H.fromList')
@
'jsonLast' keeps the last occurrence of each key, using
@
@
'fromListAccum'.
@
@
'jsonNoDup' fails if any object contains duplicate keys, using 'parseListNoDup'.
@
'jsonNoDup' = 'jsonWith' 'parseListNoDup'
@
# INLINE jsonWith #
| Variant of 'json' which keeps only the last occurrence of every key.
| Variant of 'json' wrapping all object mappings in 'Array' to preserve
key-value pairs with the same keys.
| Variant of 'json' which fails if any object contains duplicate keys.
| @'fromListAccum' kvs@ is an object mapping keys to arrays containing all
associated values from the original list @kvs@.
| @'fromListNoDup' kvs@ fails if @kvs@ contains duplicate keys.
| Strict version of 'value'. Synonym of 'json''.
| Strict version of 'jsonWith'.
# INLINE jsonWith' #
| Variant of 'json'' which keeps only the last occurrence of every key.
| Variant of 'json'' wrapping all object mappings in 'Array' to preserve
key-value pairs with the same keys.
| Variant of 'json'' which fails if any object contains duplicate keys.
| Parse a quoted JSON string.
| Parse a JSON Key
| Parse a string without a leading quote.
# INLINE jstring_ #
# INLINE eitherDecodeWith #
format to get nicer error messages
otherwise construct the error message with the bytestring builder
if newline is present cut at that position
$lazy
The 'json' and 'value' parsers decouple identification from
conversion. Identification occurs immediately (so that an invalid
JSON document can be rejected as early as possible), but conversion
This decoupling can be time-efficient if only a smallish subset of
elements in a JSON value need to be inspected, since the cost of
increase in memory usage, due to allocation of thunks for values
that have not yet been converted.
$strict
The 'json'' and 'value'' parsers combine identification with
conversion. They consume more CPU cycles up front, but have a
smaller memory footprint.
| Parse a top-level JSON value followed by optional whitespace and
end-of-input. See also: 'json'.
| Parse a top-level JSON value followed by optional whitespace and
end-of-input. See also: 'json''.
| The only valid whitespace in a JSON document is space, newline,
carriage return, and tab.
-------------- Copy - pasted and adapted from attoparsec ------------------
A strict pair
# UNPACK #
| Parse a JSON number. | # LANGUAGE CPP #
# LANGUAGE NoImplicitPrelude #
#if __GLASGOW_HASKELL__ <= 800 && __GLASGOW_HASKELL__ >= 706
#endif
Module : Data . Aeson . . Internal
Copyright : ( c ) 2011 - 2016
( c ) 2011 MailRank , Inc.
License : BSD3
Maintainer : < >
encoded as UTF-8 .
module Data.Aeson.Parser.Internal
(
json, jsonEOF
, jsonWith
, jsonLast
, jsonAccum
, jsonNoDup
, value
, jstring
, jstring_
, scientific
, json', jsonEOF'
, jsonWith'
, jsonLast'
, jsonAccum'
, jsonNoDup'
, value'
, decodeWith
, decodeStrictWith
, eitherDecodeWith
, eitherDecodeStrictWith
, fromListAccum
, parseListNoDup
, unescapeText
) where
import Prelude.Compat
import Control.Applicative ((<|>))
import Control.Monad (void, when)
import Data.Aeson.Types.Internal (IResult(..), JSONPath, Object, Result(..), Value(..), Key)
import qualified Data.Aeson.KeyMap as KM
import qualified Data.Aeson.Key as Key
import Data.Attoparsec.ByteString.Char8 (Parser, char, decimal, endOfInput, isDigit_w8, signed, string)
import Data.Function (fix)
import Data.Functor.Compat (($>))
import Data.Scientific (Scientific)
import Data.Text (Text)
import Data.Vector (Vector)
import qualified Data.Vector as Vector (empty, fromList, fromListN, reverse)
import qualified Data.Attoparsec.ByteString as A
import qualified Data.Attoparsec.Lazy as L
import qualified Data.ByteString as B
import qualified Data.ByteString.Unsafe as B
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Lazy.Char8 as C
import qualified Data.ByteString.Builder as B
import qualified Data.Scientific as Sci
import Data.Aeson.Parser.Unescape (unescapeText)
import Data.Aeson.Internal.Integer
import Data.Aeson.Internal.Text
import Data.Aeson.Internal.Word8
> > > import Data . Aeson . Types
Parsers
The conversion of a parsed value to a value is deferred
until the value is needed . This may improve performance if
This function is an alias for ' value ' . In aeson 0.8 and earlier , it
now - obsolete RFC 4627 .
If an object contains duplicate keys , only the first one will be kept .
json :: Parser Value
json = value
This function is an alias for ' value '' . In aeson 0.8 and earlier , it
now - obsolete RFC 4627 .
If an object contains duplicate keys , only the first one will be kept .
json' :: Parser Value
json' = value'
object_ :: ([(Key, Value)] -> Either String Object) -> Parser Value -> Parser Value
object_ mkObject val = Object <$> objectValues mkObject key val
object_' :: ([(Key, Value)] -> Either String Object) -> Parser Value -> Parser Value
object_' mkObject val' = do
!vals <- objectValues mkObject key' val'
return (Object vals)
where
key' = do
!s <- key
return s
objectValues :: ([(Key, Value)] -> Either String Object)
-> Parser Key -> Parser Value -> Parser (KM.KeyMap Value)
objectValues mkObject str val = do
skipSpace
w <- A.peekWord8'
if w == W8_CLOSE_CURLY
then A.anyWord8 >> return KM.empty
else loop []
where
Why use acc pattern here , you may ask ? because then the underlying ' KM.fromList '
' ` uses ' unsafeInsert ' and it 's much faster because it 's doing in place
update to the ' ' !
loop acc = do
k <- (str A.<?> "object key") <* skipSpace <* (char ':' A.<?> "':'")
v <- (val A.<?> "object value") <* skipSpace
ch <- A.satisfy (\w -> w == W8_COMMA || w == W8_CLOSE_CURLY) A.<?> "',' or '}'"
let acc' = (k, v) : acc
if ch == W8_COMMA
then skipSpace >> loop acc'
else case mkObject acc' of
Left err -> fail err
Right obj -> pure obj
# INLINE objectValues #
array_ :: Parser Value -> Parser Value
array_ val = Array <$> arrayValues val
array_' :: Parser Value -> Parser Value
array_' val = do
!vals <- arrayValues val
return (Array vals)
arrayValues :: Parser Value -> Parser (Vector Value)
arrayValues val = do
skipSpace
w <- A.peekWord8'
if w == W8_CLOSE_SQUARE
then A.anyWord8 >> return Vector.empty
else loop [] 1
where
loop acc !len = do
v <- (val A.<?> "json list value") <* skipSpace
ch <- A.satisfy (\w -> w == W8_COMMA || w == W8_CLOSE_SQUARE) A.<?> "',' or ']'"
if ch == W8_COMMA
then skipSpace >> loop (v:acc) (len+1)
else return (Vector.reverse (Vector.fromListN len (v:acc)))
# INLINE arrayValues #
value :: Parser Value
value = jsonWith (pure . KM.fromList)
' json ' keeps only the first occurrence of each key , using ' Data . Aeson . KeyMap.fromList ' .
. ' ( ' const ' ' id')@.
' jsonLast ' = ' jsonWith ' ( ' Right ' ' . ' ' . ' ( ' const ' ' i d ' ) )
' ' keeps wraps all values in arrays to keep duplicates , using
' ' = ' jsonWith ' ( ' Right ' . ' fromListAccum ' )
jsonWith :: ([(Key, Value)] -> Either String Object) -> Parser Value
jsonWith mkObject = fix $ \value_ -> do
skipSpace
w <- A.peekWord8'
case w of
W8_DOUBLE_QUOTE -> A.anyWord8 *> (String <$> jstring_)
W8_OPEN_CURLY -> A.anyWord8 *> object_ mkObject value_
W8_OPEN_SQUARE -> A.anyWord8 *> array_ value_
W8_f -> string "false" $> Bool False
W8_t -> string "true" $> Bool True
W8_n -> string "null" $> Null
_ | w >= W8_0 && w <= W8_9 || w == W8_MINUS
-> Number <$> scientific
| otherwise -> fail "not a valid json value"
jsonLast :: Parser Value
jsonLast = jsonWith (Right . KM.fromListWith (const id))
jsonAccum :: Parser Value
jsonAccum = jsonWith (Right . fromListAccum)
jsonNoDup :: Parser Value
jsonNoDup = jsonWith parseListNoDup
> > > fromListAccum [ ( " apple " , ) , ( " apple " , ) , ( " orange " , ) ]
fromList [ ( " apple",Array [ Bool False , ] ) ]
fromListAccum :: [(Key, Value)] -> Object
fromListAccum =
fmap (Array . Vector.fromList . ($ [])) . KM.fromListWith (.) . (fmap . fmap) (:)
parseListNoDup :: [(Key, Value)] -> Either String Object
parseListNoDup =
KM.traverseWithKey unwrap . KM.fromListWith (\_ _ -> Nothing) . (fmap . fmap) Just
where
unwrap k Nothing = Left $ "found duplicate key: " ++ show k
unwrap _ (Just v) = Right v
value' :: Parser Value
value' = jsonWith' (pure . KM.fromList)
jsonWith' :: ([(Key, Value)] -> Either String Object) -> Parser Value
jsonWith' mkObject = fix $ \value_ -> do
skipSpace
w <- A.peekWord8'
case w of
W8_DOUBLE_QUOTE -> do
!s <- A.anyWord8 *> jstring_
return (String s)
W8_OPEN_CURLY -> A.anyWord8 *> object_' mkObject value_
W8_OPEN_SQUARE -> A.anyWord8 *> array_' value_
W8_f -> string "false" $> Bool False
W8_t -> string "true" $> Bool True
W8_n -> string "null" $> Null
_ | w >= W8_0 && w <= W8_9 || w == W8_MINUS
-> do
!n <- scientific
return (Number n)
| otherwise -> fail "not a valid json value"
jsonLast' :: Parser Value
jsonLast' = jsonWith' (pure . KM.fromListWith (const id))
jsonAccum' :: Parser Value
jsonAccum' = jsonWith' (pure . fromListAccum)
jsonNoDup' :: Parser Value
jsonNoDup' = jsonWith' parseListNoDup
jstring :: Parser Text
jstring = A.word8 W8_DOUBLE_QUOTE *> jstring_
key :: Parser Key
key = Key.fromText <$> jstring
jstring_ :: Parser Text
jstring_ = do
s <- A.takeWhile (\w -> w /= W8_DOUBLE_QUOTE && w /= W8_BACKSLASH && w >= 0x20 && w < 0x80)
mw <- A.peekWord8
case mw of
Nothing -> fail "string without end"
Just W8_DOUBLE_QUOTE -> A.anyWord8 $> unsafeDecodeASCII s
Just w | w < 0x20 -> fail "unescaped control character"
_ -> jstringSlow s
jstringSlow :: B.ByteString -> Parser Text
# INLINE jstringSlow #
jstringSlow s' = do
s <- A.scan startState go <* A.anyWord8
case unescapeText (B.append s' s) of
Right r -> return r
Left err -> fail $ show err
where
startState = False
go a c
| a = Just False
| c == W8_DOUBLE_QUOTE = Nothing
| otherwise = let a' = c == W8_BACKSLASH
in Just a'
decodeWith :: Parser Value -> (Value -> Result a) -> L.ByteString -> Maybe a
decodeWith p to s =
case L.parse p s of
L.Done _ v -> case to v of
Success a -> Just a
_ -> Nothing
_ -> Nothing
# INLINE decodeWith #
decodeStrictWith :: Parser Value -> (Value -> Result a) -> B.ByteString
-> Maybe a
decodeStrictWith p to s =
case either Error to (A.parseOnly p s) of
Success a -> Just a
_ -> Nothing
# INLINE decodeStrictWith #
eitherDecodeWith :: Parser Value -> (Value -> IResult a) -> L.ByteString
-> Either (JSONPath, String) a
eitherDecodeWith p to s =
case L.parse p s of
L.Done _ v -> case to v of
ISuccess a -> Right a
IError path msg -> Left (path, msg)
L.Fail notparsed ctx msg -> Left ([], buildMsg notparsed ctx msg)
where
buildMsg :: L.ByteString -> [String] -> String -> String
buildMsg notYetParsed [] msg = msg ++ formatErrorLine notYetParsed
buildMsg notYetParsed (expectation:_) msg =
msg ++ ". Expecting " ++ expectation ++ formatErrorLine notYetParsed
| Grab the first 100 bytes from the non parsed portion and
formatErrorLine :: L.ByteString -> String
formatErrorLine bs =
C.unpack .
if formatting results in empty ByteString just return that
(\bs' ->
if BSL.null bs'
then BSL.empty
else
B.toLazyByteString $
B.stringUtf8 " at '" <> B.lazyByteString bs' <> B.stringUtf8 "'"
) .
BSL.takeWhile (10 /=) .
remove spaces , CR 's , tabs , backslashes and quotes characters
BSL.filter (`notElem` [9, 13, 32, 34, 47, 92]) .
take 100 bytes
BSL.take 100 $ bs
eitherDecodeStrictWith :: Parser Value -> (Value -> IResult a) -> B.ByteString
-> Either (JSONPath, String) a
eitherDecodeStrictWith p to s =
case either (IError []) to (A.parseOnly p s) of
ISuccess a -> Right a
IError path msg -> Left (path, msg)
# INLINE eitherDecodeStrictWith #
to a value is deferred until that value is needed .
conversion is zero for uninspected elements . The trade off is an
jsonEOF :: Parser Value
jsonEOF = json <* skipSpace <* endOfInput
jsonEOF' :: Parser Value
jsonEOF' = json' <* skipSpace <* endOfInput
skipSpace :: Parser ()
skipSpace = A.skipWhile $ \w -> w == W8_SPACE || w == W8_NL || w == W8_CR || w == W8_TAB
# INLINE skipSpace #
decimal0 :: Parser Integer
decimal0 = do
digits <- A.takeWhile1 isDigit_w8
if B.length digits > 1 && B.unsafeHead digits == W8_0
then fail "leading zero"
else return (bsToInteger digits)
scientific :: Parser Scientific
scientific = do
sign <- A.peekWord8'
let !positive = not (sign == W8_MINUS)
when (sign == W8_PLUS || sign == W8_MINUS) $
void A.anyWord8
n <- decimal0
let f fracDigits = SP (B.foldl' step n fracDigits)
(negate $ B.length fracDigits)
step a w = a * 10 + fromIntegral (w - W8_0)
dotty <- A.peekWord8
SP c e <- case dotty of
Just W8_DOT -> A.anyWord8 *> (f <$> A.takeWhile1 isDigit_w8)
_ -> pure (SP n 0)
let !signedCoeff | positive = c
| otherwise = -c
(A.satisfy (\ex -> case ex of W8_e -> True; W8_E -> True; _ -> False) *>
fmap (Sci.scientific signedCoeff . (e +)) (signed decimal)) <|>
return (Sci.scientific signedCoeff e)
# INLINE scientific #
|
c7e0076a1312d3781cb8d1716596f864a7a268290e19ad739b92add37725edd6 | Andromedans/andromeda | desugar.ml | * Conversion from sugared to desugared input syntax . The responsibilities of
this phase is to :
* resolve all names to levels and indices
* check arities of constructors and operations
Note that we do not check arities of derivations here because those are first - class
and are not bound to specific identifiers , and so we have no way of computing them
in the desugaring phase .
We could consider moving arity checking of all entitites to typechecking , but then
we need to worry about separate namespaces in which they might leave , and it would
just induce some pointless code refactoring .
this phase is to:
* resolve all names to levels and indices
* check arities of constructors and operations
Note that we do not check arities of derivations here because those are first-class
and are not bound to specific identifiers, and so we have no way of computing them
in the desugaring phase.
We could consider moving arity checking of all entitites to typechecking, but then
we need to worry about separate namespaces in which they might leave, and it would
just induce some pointless code refactoring.
*)
* Association tables with de Bruijn levels .
module Assoc :
sig
type 'a t
val empty : 'a t
val add : Name.t -> 'a -> 'a t -> 'a t
val last : 'a t -> int
val find : Name.t -> 'a t -> 'a option
val include' : (Name.t -> unit) -> 'a t -> 'a t -> 'a t
val open' : (Name.t -> unit) -> 'a t -> 'a t -> 'a t
val export : 'a t -> 'a t
end =
struct
type export = Exported | NotExported
type 'a t =
{ last : int ; assoc : ('a * export) Name.map }
let empty = { last = 0 ; assoc = Name.map_empty }
let add x y {last; assoc} =
{ last = last + 1 ; assoc = Name.map_add x (y, Exported) assoc }
let redirect expo check_fresh {last; assoc} {assoc=assoc';_} =
{ last ;
assoc = Name.map_fold (fun k (v,_) assoc -> check_fresh k ; Name.map_add k (v, expo) assoc) assoc' assoc
}
let include' check_fresh asc asc' = redirect Exported check_fresh asc asc'
let open' check_fresh asc asc' = redirect NotExported check_fresh asc asc'
let export {last; assoc} =
{ last ;
assoc = Name.map_fold
(fun k ve assoc ->
match snd ve with
| Exported -> Name.map_add k ve assoc
| NotExported -> assoc)
assoc Name.map_empty
}
let last {last; _} = last
let find x {assoc; _} =
try
Some (fst (Name.map_find x assoc))
with
Not_found -> None
end
* Arity of a TT constructor
type tt_arity = int
* Arity of an ML constructor or opertation
type ml_arity = int
(** Arity of an ML exception *)
type exception_arity = Nullary | Unary
A module has three name spaces , one for ML modules , one for ML types and the other for
everything else . However , we keep operations , , TT constructors , and
values in separate lists because we need to compute their indices . All entities are
accessed by levels .
everything else. However, we keep operations, ML constructos, TT constructors, and
values in separate lists because we need to compute their indices. All entities are
accessed by de Bruijn levels. *)
type ml_module = {
ml_modules : (Path.t * ml_module) Assoc.t;
ml_types : (Path.t * ml_arity) Assoc.t;
ml_constructors : ((Path.t * Path.level) * ml_arity) Assoc.t;
ml_operations : (Path.t * ml_arity) Assoc.t;
ml_exceptions : (Path.t * exception_arity) Assoc.t;
tt_constructors : (Path.t * tt_arity) Assoc.t;
ml_values : Path.t Assoc.t
}
let empty_module = {
ml_modules = Assoc.empty;
ml_types = Assoc.empty;
ml_constructors = Assoc.empty;
ml_operations = Assoc.empty;
ml_exceptions = Assoc.empty;
tt_constructors = Assoc.empty;
ml_values = Assoc.empty
}
(** Information about names *)
type info =
| Bound of Path.index
| Value of Path.t
| TTConstructor of Path.t * tt_arity
| MLConstructor of Path.ml_constructor * ml_arity
| Operation of Path.t * ml_arity
| Exception of Path.t * exception_arity
let print_info info ppf = match info with
| Bound _ | Value _ -> Format.fprintf ppf "a value"
| TTConstructor _ -> Format.fprintf ppf "a constructor"
| MLConstructor _ -> Format.fprintf ppf "an ML constructor"
| Operation _ -> Format.fprintf ppf "an operation"
| Exception _ -> Format.fprintf ppf "an exception"
type error =
| UnknownPath of Name.path
| UnknownType of Name.path
| UnknownModule of Name.path
| NameAlreadyDeclared of Name.t * info
| MLTypeAlreadyDeclared of Name.t
| MLModuleAlreadyDeclared of Name.t
| OperationExpected : Name.path * info -> error
| InvalidPatternVariable : Name.t -> error
| InvalidPatternName : Name.path * info -> error
| InvalidAppliedPatternName : Name.path * info -> error
| NonlinearPattern : Name.t -> error
| ArityMismatch of Name.path * int * int
| ParallelShadowing of Name.t
| AppliedTyParam
| RequiredModuleMissing of Name.t * string list
| CircularRequire of Name.t list
let print_error err ppf = match err with
| UnknownPath pth ->
Format.fprintf ppf "unknown name %t"
(Name.print_path pth)
| UnknownType pth ->
Format.fprintf ppf "unknown type %t"
(Name.print_path pth)
| UnknownModule pth ->
Format.fprintf ppf "unknown ML module %t"
(Name.print_path pth)
| NameAlreadyDeclared (x, info) ->
Format.fprintf ppf
"%t is already declared as %t"
(Name.print x)
(print_info info)
| MLTypeAlreadyDeclared x ->
Format.fprintf ppf
"%t is already a defined ML type"
(Name.print x)
| MLModuleAlreadyDeclared x ->
Format.fprintf ppf
"%t is already a defind ML module"
(Name.print x)
| OperationExpected (pth, info) ->
Format.fprintf ppf "%t should be an operation but is %t"
(Name.print_path pth)
(print_info info)
| InvalidPatternName (pth, info) ->
Format.fprintf ppf "%t cannot be used in a pattern as it is %t"
(Name.print_path pth)
(print_info info)
| InvalidPatternVariable x ->
Format.fprintf ppf "%t is an invalid pattern variable, perhaps you meant ?%t"
(Name.print x)
(Name.print x)
| InvalidAppliedPatternName (pth, info) ->
Format.fprintf ppf "%t cannot be applied in a pattern as it is %t"
(Name.print_path pth)
(print_info info)
| NonlinearPattern x ->
Format.fprintf ppf "pattern variable %t appears more than once"
(Name.print x)
| ArityMismatch (pth, used, expected) ->
Format.fprintf ppf "%t expects %d arguments but is used with %d"
(Name.print_path pth)
expected
used
| ParallelShadowing x ->
Format.fprintf ppf "%t is bound more than once"
(Name.print x)
| AppliedTyParam ->
Format.fprintf ppf "an ML type parameter cannot be applied"
| RequiredModuleMissing (mdl_name, files) ->
Format.fprintf ppf "required module %t could not be found, looked in:@\n@[<hv>%t@]"
(Name.print mdl_name)
(Print.sequence (fun fn ppf -> Format.fprintf ppf "%s" fn) "," files)
| CircularRequire mdls ->
Format.fprintf ppf "circuar module dependency (@[<hov -2>%t@])"
(Print.sequence (Name.print ~parentheses:false) "," mdls)
exception Error of error Location.located
let error ~at err = Stdlib.raise (Error (Location.mark ~at err))
module Ctx = struct
type t = {
(* Partially evaluated nested modules *)
current_modules : (Path.t option * ml_module) list ;
ml_bound : Name.t list ; (* the locally bound values, referred to by indices *)
}
let empty = {
current_modules = [(None, empty_module)] ;
ml_bound = [];
}
let current_module {current_modules;_} =
match current_modules with
| [] -> assert false (* There should always be at least the top module *)
| (_, mdl) :: _ -> mdl
let update_current ctx update =
let mk_path optpath x lvl =
match optpath with
| None -> Path.Direct (Path.Level (x, lvl))
| Some p -> Path.Module (p, Path.Level (x, lvl))
in
match ctx.current_modules with
| [] -> assert false
| (optpath, mdl) :: mdls ->
let pth, mdl = update (mk_path optpath) mdl in
pth, { ctx with current_modules = (optpath, mdl) :: mdls }
(* Convert a context to a module. *)
let export_ml_module {ml_modules; ml_types; ml_constructors; ml_operations; ml_exceptions; tt_constructors; ml_values} =
{
ml_modules = Assoc.export ml_modules;
ml_types = Assoc.export ml_types;
ml_constructors = Assoc.export ml_constructors;
ml_operations = Assoc.export ml_operations;
ml_exceptions = Assoc.export ml_exceptions;
tt_constructors = Assoc.export tt_constructors;
ml_values = Assoc.export ml_values;
}
let push_module mdl_name ctx =
match ctx.current_modules with
| [] -> assert false
| ((pth_opt, mdl) :: _) as mdls ->
let mdl_lvl = Assoc.last mdl.ml_modules in
let pth =
match pth_opt with
| None -> Path.Direct (Path.Level (mdl_name, mdl_lvl))
| Some pth -> Path.Module (pth, Path.Level (mdl_name, mdl_lvl))
in
{ ctx with current_modules = (Some pth, empty_module) :: mdls }
let pop_module ctx =
match ctx.current_modules with
| [] | [_] -> assert false
| (_, mdl) :: mdls ->
let mdl = export_ml_module mdl in
{ ctx with current_modules = mdls }, mdl
(* Lookup functions named [find_XYZ] return optional results,
while those named [get_XYZ] require a location and either return
a result or trigger an error. *)
(* Find information about the given name in the given module. *)
let find_name_in_module x mdl =
match Assoc.find x mdl.ml_values with
| Some pth -> Some (Value pth)
| None ->
begin match Assoc.find x mdl.tt_constructors with
| Some (pth, arity) -> Some (TTConstructor (pth, arity))
| None ->
begin match Assoc.find x mdl.ml_operations with
| Some (pth, arity) -> Some (Operation (pth, arity))
| None ->
begin match Assoc.find x mdl.ml_constructors with
| Some (pth, arity) -> Some (MLConstructor (pth, arity))
| None ->
begin match Assoc.find x mdl.ml_exceptions with
| Some (pth, arity) -> Some (Exception (pth, arity))
| None -> None
end
end
end
end
let find_type_in_module t mdl = Assoc.find t mdl.ml_types
let find_module_in_module m mdl = Assoc.find m mdl.ml_modules
(* Find information about the given name in the current context. *)
let rec find_path
: 'a . find:(Name.t -> ml_module -> 'a option) -> Name.path -> t -> 'a option
= fun ~find pth ctx ->
match pth with
| Name.PName x ->
find_direct ~find x ctx
| Name.PModule (pth, x) ->
begin match find_ml_module pth ctx with
| Some (pth, mdl) -> find x mdl
| None -> None
end
and find_direct
: 'a . find:(Name.t -> ml_module -> 'a option) -> Name.t -> t -> 'a option
= fun ~find x ctx ->
let rec search = function
| [] -> None
| (_, mdl) :: mdls ->
begin match find x mdl with
| Some _ as info -> info
| None -> search mdls
end
in
search ctx.current_modules
and find_ml_module pth ctx = find_path ~find:find_module_in_module pth ctx
let find_name pth ctx = find_path ~find:find_name_in_module pth ctx
let find_ml_type pth ctx = find_path ~find:find_type_in_module pth ctx
(* Check that the name is not bound already *)
let check_is_fresh_name ~at x ctx =
match find_name_in_module x (current_module ctx) with
| None -> ()
| Some info -> error ~at (NameAlreadyDeclared (x, info))
(* Check that the type is not bound already *)
let check_is_fresh_type ~at t ctx =
match find_type_in_module t (current_module ctx) with
| None -> ()
| Some info -> error ~at (MLTypeAlreadyDeclared t)
(* Check that the module is not bound already *)
let check_is_fresh_module ~at m ctx =
match find_module_in_module m (current_module ctx) with
| None -> ()
| Some _ -> error ~at (MLModuleAlreadyDeclared m)
Get information about the given ML constructor .
let get_ml_constructor pth ctx =
match find_name pth ctx with
| Some (MLConstructor (pth, arity)) -> pth, arity
| None |Some (Bound _ | Value _ | TTConstructor _ | Operation _ | Exception _) ->
assert false
Get information about the given ML operation .
let get_ml_operation op ctx =
match find_name op ctx with
| Some (Operation (pth, arity)) -> pth, arity
| None | Some (Bound _ | Value _ | TTConstructor _ | MLConstructor _ | Exception _) ->
assert false
Get information about the given ML operation .
let get_ml_exception exc ctx =
match find_name exc ctx with
| Some (Exception (pth, arity)) -> pth, arity
| None | Some (Bound _ | Value _ | TTConstructor _ | MLConstructor _ | Operation _) ->
assert false
(* This will be needed if and when there is a builtin global ML value that has to be looked up. *)
let get_ml_value x ctx =
* match find_name x ctx with
* | Some ( Value v ) - > v
* | None | Some ( Bound _ | TTConstructor _ _ | Operation _ ) - >
* assert false
* match find_name x ctx with
* | Some (Value v) -> v
* | None | Some (Bound _ | TTConstructor _ | MLConstructor _ | Operation _) ->
* assert false *)
Get information about the given ML module .
let get_ml_module ~at pth ctx =
match find_ml_module pth ctx with
| Some (pth, mdl) -> pth, mdl
| None -> error ~at (UnknownModule pth)
(* Get the info about a path, or fail *)
let get_name ~at pth ctx =
match pth with
| Name.PName x ->
(* check whether it is locally bound *)
let find_index x lst =
let rec search i = function
| [] -> None
| x' :: lst -> if Name.equal x x' then Some i else search (i+1) lst
in
search 0 lst
in
begin match find_index x ctx.ml_bound with
| Some i -> Bound (Path.Index (x, i))
| None ->
begin match find_name pth ctx with
| Some info -> info
| None -> error ~at (UnknownPath pth)
end
end
| Name.PModule _ ->
begin match find_name pth ctx with
| Some info -> info
| None -> error ~at (UnknownPath pth)
end
(* Get information about the list empty list constructor *)
let get_path_nil ctx =
get_ml_constructor Name.Builtin.nil ctx
let get_path_cons ctx =
get_ml_constructor Name.Builtin.cons ctx
(* Get the path and the arity of type named [t] *)
let get_ml_type ~at pth ctx =
match find_ml_type pth ctx with
| None -> error ~at (UnknownType pth)
| Some info ->
info
(* Add a module to the current module. *)
let add_ml_module ~at m mdl ctx =
check_is_fresh_module ~at m ctx ;
let (), ctx =
update_current ctx
(fun mk_path current ->
let lvl = Assoc.last current.ml_modules in
let pth = mk_path m lvl in
(), { current with ml_modules = Assoc.add m (pth, mdl) current.ml_modules } )
in
ctx
let include_ml_module ~at mdl ctx =
let (), ctx =
update_current ctx
(fun _ {ml_modules; ml_types; ml_constructors; ml_operations; ml_exceptions; tt_constructors; ml_values} ->
(), { ml_modules = Assoc.include' (fun m -> check_is_fresh_module ~at m ctx) ml_modules mdl.ml_modules;
ml_types = Assoc.include' (fun t -> check_is_fresh_type ~at t ctx) ml_types mdl.ml_types;
ml_constructors = Assoc.include' (fun x -> check_is_fresh_name ~at x ctx) ml_constructors mdl.ml_constructors;
ml_operations = Assoc.include' (fun x -> check_is_fresh_name ~at x ctx) ml_operations mdl.ml_operations;
ml_exceptions = Assoc.include' (fun x -> check_is_fresh_name ~at x ctx) ml_exceptions mdl.ml_exceptions;
tt_constructors = Assoc.include' (fun x -> check_is_fresh_name ~at x ctx) tt_constructors mdl.tt_constructors;
ml_values = Assoc.include' (fun x -> check_is_fresh_name ~at x ctx) ml_values mdl.ml_values;
})
in
ctx
let open_ml_module ~at mdl ctx =
let (), ctx =
update_current ctx
(fun _ {ml_modules; ml_types; ml_constructors; ml_operations; ml_exceptions; tt_constructors; ml_values} ->
(), { ml_modules = Assoc.open' (fun m -> check_is_fresh_module ~at m ctx) ml_modules mdl.ml_modules;
ml_types = Assoc.open' (fun t -> check_is_fresh_type ~at t ctx) ml_types mdl.ml_types;
ml_constructors = Assoc.open' (fun x -> check_is_fresh_name ~at x ctx) ml_constructors mdl.ml_constructors;
ml_operations = Assoc.open' (fun x -> check_is_fresh_name ~at x ctx) ml_operations mdl.ml_operations;
ml_exceptions = Assoc.open' (fun x -> check_is_fresh_name ~at x ctx) ml_exceptions mdl.ml_exceptions;
tt_constructors = Assoc.open' (fun x -> check_is_fresh_name ~at x ctx) tt_constructors mdl.tt_constructors;
ml_values = Assoc.open' (fun x -> check_is_fresh_name ~at x ctx) ml_values mdl.ml_values;
})
in
ctx
Add an ML values to the current module .
let add_ml_value ~at x ctx =
check_is_fresh_name ~at x ctx ;
let (), ctx =
update_current ctx
(fun mk_path current ->
let lvl = Assoc.last current.ml_values in
let pth = mk_path x lvl in
(), { current with ml_values = Assoc.add x pth current.ml_values } )
in
ctx
(* Add a local bound value. *)
let add_bound x ctx =
{ ctx with ml_bound = x :: ctx.ml_bound }
Add a TT constructor of given arity
let add_tt_constructor ~at c arity ctx =
check_is_fresh_name ~at c ctx ;
update_current ctx
(fun mk_path current ->
let lvl = Assoc.last current.tt_constructors in
let pth = mk_path c lvl in
pth, { current with tt_constructors = Assoc.add c (pth, arity) current.tt_constructors } )
(* Add an operation of given arity *)
let add_operation ~at op arity ctx =
check_is_fresh_name ~at op ctx ;
update_current ctx
(fun mk_path current ->
let lvl = Assoc.last current.ml_operations in
let pth = mk_path op lvl in
pth, { current with ml_operations = Assoc.add op (pth, arity) current.ml_operations } )
(* Add an exception of given arity *)
let add_exception ~at exc arity ctx =
check_is_fresh_name ~at exc ctx ;
update_current ctx
(fun mk_path current ->
let lvl = Assoc.last current.ml_exceptions in
let pth = mk_path exc lvl in
pth, { current with ml_exceptions = Assoc.add exc (pth, arity) current.ml_exceptions } )
Add a ML constructor of given arity
let add_ml_constructor ~at c info ctx =
check_is_fresh_name ~at c ctx ;
let (), ctx =
update_current ctx
(fun mk_path current ->
(), { current with ml_constructors = Assoc.add c info current.ml_constructors } )
in
ctx
(* Add to the context the fact that [t] is a type constructor with given constructors and arities. *)
let add_ml_type ~at t (arity, cs_opt) ctx =
check_is_fresh_type ~at t ctx ;
let t_pth, ctx =
update_current ctx
(fun mk_path current ->
let lvl = Assoc.last current.ml_types in
let pth = mk_path t lvl in
pth, { current with ml_types = Assoc.add t (pth, arity) current.ml_types })
in
match cs_opt with
| None -> t_pth, ctx
| Some cs ->
begin match find_type_in_module t (current_module ctx) with
| None -> assert false
| Some (t_pth, _) ->
let _, ctx =
List.fold_left
(fun (lvl, ctx) (c, arity) ->
let ctx = add_ml_constructor ~at c ((t_pth, Path.Level (c, lvl)), arity) ctx in
(lvl+1, ctx))
(0, ctx)
cs
in
t_pth, ctx
end
module
(* Check that the arity is the expected one. *)
let check_ml_arity ~at pth used expected =
if used <> expected then
error ~at (ArityMismatch (pth, used, expected))
(* Check that the arity is the expected one. *)
let check_exception_arity ~at pth used expected =
let card = function Nullary -> 0 | Unary -> 1 in
if used <> card expected then
error ~at (ArityMismatch (pth, used, card expected))
Compute the arity of a TT constructor , given the premises of its rule .
let tt_arity prems = List.length prems
Compute the arity of a ML constructor .
let ml_arity = List.length
Compute the arity of an ML exception .
let ml_exception_arity = function
| None -> Nullary
| Some _ -> Unary
(* Check that the arity is the expected one. *)
let check_tt_arity ~at pth used expected =
if used <> expected then
error ~at (ArityMismatch (pth, used, expected))
an ML type , with the given list of known type parameters
let mlty ctx params ty =
let rec mlty ({Location.it=ty';at}) =
let ty' =
begin match ty' with
| Sugared.ML_Arrow (ty1, ty2) ->
let ty1 = mlty ty1
and ty2 = mlty ty2 in
Desugared.ML_Arrow (ty1, ty2)
| Sugared.ML_Handler (ty1, ty2) ->
let ty1 = mlty ty1
and ty2 = mlty ty2 in
Desugared.ML_Handler (ty1, ty2)
| Sugared.ML_Ref t ->
let t = mlty t in
Desugared.ML_Ref t
| Sugared.ML_Exn ->
Desugared.ML_Exn
| Sugared.ML_Prod tys ->
let tys = List.map mlty tys in
Desugared.ML_Prod tys
| Sugared.ML_TyApply (pth, args) ->
begin match pth with
| Name.PModule _ ->
let (t_pth, expected) = Ctx.get_ml_type ~at pth ctx in
check_ml_arity ~at pth (List.length args) expected ;
let args = List.map mlty args in
Desugared.ML_Apply (t_pth, args)
| Name.PName x ->
(* It could be one of the bound type parameters *)
let rec search k = function
| [] ->
(* It's a type name *)
begin
let (t_pth, expected) = Ctx.get_ml_type ~at pth ctx in
check_ml_arity ~at pth (List.length args) expected ;
let args = List.map mlty args in
Desugared.ML_Apply (t_pth, args)
end
| None :: params -> search k params
| Some y :: params ->
if Name.equal x y then
(* It's a type parameter *)
begin match args with
| [] -> Desugared.ML_Bound (Path.Index (x, k))
| _::_ -> error ~at AppliedTyParam
end
else search (k+1) params
in
search 0 params
end
| Sugared.ML_Anonymous ->
Desugared.ML_Anonymous
| Sugared.ML_Judgement ->
Desugared.ML_Judgement
| Sugared.ML_Boundary ->
Desugared.ML_Boundary
| Sugared.ML_Derivation ->
Desugared.ML_Derivation
| Sugared.ML_String -> Desugared.ML_String
end
in
Location.mark ~at ty'
in
mlty ty
TODO improve locs
let mk_abstract ~at ys c =
List.fold_left
(fun c (y,u) -> Location.mark ~at (Desugared.Abstract (y,u,c)))
c ys
let rec pattern ~toplevel ctx {Location.it=p; at} =
let locate x = Location.mark ~at x in
match p with
| Sugared.Patt_Anonymous ->
ctx, locate Desugared.Patt_Anonymous
| Sugared.Patt_Var x ->
let add = if toplevel then Ctx.add_ml_value ~at else Ctx.add_bound in
let ctx = add x ctx in
ctx, locate (Desugared.Patt_Var x)
| Sugared.Patt_Path pth ->
begin match pth with
| Name.PName x ->
begin match Ctx.find_name pth ctx with
| None ->
error ~at (InvalidPatternVariable x)
| Some (MLConstructor (pth, arity)) ->
check_ml_arity ~at (Name.PName x) 0 arity ;
ctx, locate (Desugared.Patt_MLConstructor (pth, []))
| Some (TTConstructor (pth, arity)) ->
check_tt_arity ~at (Name.PName x) 0 arity ;
ctx, locate (Desugared.Patt_TTConstructor (pth, []))
| Some (Exception (pth, arity)) ->
check_exception_arity ~at (Name.PName x) 0 arity ;
ctx, locate (Desugared.Patt_MLException (pth, None))
| Some ((Operation _ | Bound _ | Value _) as info) ->
error ~at (InvalidPatternName (pth, info))
end
| Name.PModule _ ->
begin match Ctx.get_name ~at pth ctx with
| MLConstructor (c_pth, arity) ->
check_ml_arity ~at pth 0 arity ;
ctx, locate (Desugared.Patt_MLConstructor (c_pth, []))
| TTConstructor (c_pth, arity) ->
check_tt_arity ~at pth 0 arity ;
ctx, locate (Desugared.Patt_TTConstructor (c_pth, []))
| (Value _ | Operation _ | Exception _) as info ->
error ~at (InvalidPatternName (pth, info))
| Bound _ -> assert false
end
end
| Sugared.Patt_MLAscribe (p, t) ->
let ctx, p = pattern ~toplevel ctx p in
let t = mlty ctx [] t in
ctx, locate (Desugared.Patt_MLAscribe (p, t))
| Sugared.Patt_As (p1, p2) ->
let ctx, p1 = pattern ~toplevel ctx p1 in
let ctx, p2 = pattern ~toplevel ctx p2 in
ctx, locate (Desugared.Patt_As (p1, p2))
| Sugared.Patt_Constructor (c, ps) ->
begin match Ctx.get_name ~at c ctx with
| MLConstructor (pth, arity) ->
check_ml_arity ~at c (List.length ps) arity ;
let ctx, ps = patterns ~at ~toplevel ctx ps in
ctx, locate (Desugared.Patt_MLConstructor (pth, ps))
| Exception (exc, arity) ->
check_exception_arity ~at c (List.length ps) arity ;
begin match arity, ps with
| Nullary, [] -> ctx, locate (Desugared.Patt_MLException (exc, None))
| Unary, [p] ->
let ctx, p = pattern ~toplevel ctx p in
ctx, locate (Desugared.Patt_MLException (exc, Some p))
| Nullary, _::_ -> error ~at (ArityMismatch (c, List.length ps, 0))
| Unary, ([] | _::_::_) -> error ~at (ArityMismatch (c, List.length ps, 1))
end
| TTConstructor (pth, arity) ->
check_tt_arity ~at c (List.length ps) arity ;
let ctx, ps = patterns ~at ~toplevel ctx ps in
ctx, locate (Desugared.Patt_TTConstructor (pth, ps))
| (Bound _ | Value _ | Operation _) as info ->
error ~at (InvalidAppliedPatternName (c, info))
end
| Sugared.Patt_GenAtom p ->
let ctx, p = pattern ~toplevel ctx p in
ctx, locate (Desugared.Patt_GenAtom p)
| Sugared.Patt_IsType p ->
let ctx, p = pattern ~toplevel ctx p in
ctx, locate (Desugared.Patt_IsType p)
| Sugared.Patt_IsTerm (p1, p2) ->
let ctx, p1 = pattern ~toplevel ctx p1 in
let ctx, p2 = pattern ~toplevel ctx p2 in
ctx, locate (Desugared.Patt_IsTerm (p1, p2))
| Sugared.Patt_EqType (p1, p2) ->
let ctx, p1 = pattern ~toplevel ctx p1 in
let ctx, p2 = pattern ~toplevel ctx p2 in
ctx, locate (Desugared.Patt_EqType (p1, p2))
| Sugared.Patt_EqTerm (p1, p2, p3) ->
let ctx, p1 = pattern ~toplevel ctx p1 in
let ctx, p2 = pattern ~toplevel ctx p2 in
let ctx, p3 = pattern ~toplevel ctx p3 in
ctx, locate (Desugared.Patt_EqTerm (p1, p2, p3))
| Sugared.Patt_BoundaryIsType ->
ctx, locate (Desugared.Patt_BoundaryIsType)
| Sugared.Patt_BoundaryIsTerm p ->
let ctx, p = pattern ~toplevel ctx p in
ctx, locate (Desugared.Patt_BoundaryIsTerm p)
| Sugared.Patt_BoundaryEqType (p1, p2) ->
let ctx, p1 = pattern ~toplevel ctx p1 in
let ctx, p2 = pattern ~toplevel ctx p2 in
ctx, locate (Desugared.Patt_BoundaryEqType (p1, p2))
| Sugared.Patt_BoundaryEqTerm (p1, p2, p3) ->
let ctx, p1 = pattern ~toplevel ctx p1 in
let ctx, p2 = pattern ~toplevel ctx p2 in
let ctx, p3 = pattern ~toplevel ctx p3 in
ctx, locate (Desugared.Patt_BoundaryEqTerm (p1, p2, p3))
| Sugared.Patt_Abstraction (abstr, p0) ->
let rec fold ctx = function
| [] -> pattern ~toplevel ctx p0
| (xopt, popt) :: abstr ->
let ctx, popt =
match popt with
| None -> ctx, locate Desugared.Patt_Anonymous
| Some p ->
let ctx, p = pattern ~toplevel ctx p in
ctx, p
in
let ctx, xopt =
begin
match xopt with
| Some x ->
let ctx = Ctx.add_bound x ctx in
ctx, Some x
| None -> ctx, None
end
in
let ctx, p = fold ctx abstr in
ctx, locate (Desugared.Patt_Abstraction (xopt, popt, p))
in
fold ctx abstr
| Sugared.Patt_List ps ->
let nil_path, _ = Ctx.get_path_nil ctx
and cons_path, _ = Ctx.get_path_cons ctx in
let rec fold ~at ctx = function
| [] -> ctx, locate (Desugared.Patt_MLConstructor (nil_path, []))
| p :: ps ->
let ctx, p = pattern ~toplevel ctx p in
let ctx, ps = fold ~at:(p.Location.at) ctx ps in
ctx, locate (Desugared.Patt_MLConstructor (cons_path, [p ; ps]))
in
fold ~at ctx ps
| Sugared.Patt_Tuple ps ->
let ctx, ps = patterns ~at ~toplevel ctx ps in
ctx, locate (Desugared.Patt_Tuple ps)
| Sugared.Patt_String s ->
ctx, locate (Desugared.Patt_String s)
and patterns ~at ~toplevel ctx ps =
let rec fold ctx ps_out = function
| [] ->
ctx, List.rev ps_out
| p :: ps ->
let ctx, p_out = pattern ~toplevel ctx p in
fold ctx (p_out :: ps_out) ps
in
fold ctx [] ps
(** Verify that a pattern is linear and that it does not bind anything
in the given set of forbidden names. Return the set of forbidden names
extended with the names that this pattern binds. *)
let check_linear_pattern_variable ~at ~forbidden x =
if Name.set_mem x forbidden then
error ~at (NonlinearPattern x)
else
Name.set_add x forbidden
let rec check_linear ?(forbidden=Name.set_empty) {Location.it=p';at} =
match p' with
| Sugared.Patt_Anonymous | Sugared.Patt_Path _ | Sugared.Patt_String _ ->
forbidden
| Sugared.Patt_Var x ->
check_linear_pattern_variable ~at ~forbidden x
| Sugared.Patt_MLAscribe (p, _) ->
check_linear ~forbidden p
| Sugared.Patt_As (p1, p2) ->
let forbidden = check_linear ~forbidden p1 in
check_linear ~forbidden p2
| Sugared.Patt_GenAtom p ->
check_linear ~forbidden p
| Sugared.Patt_IsType p ->
check_linear ~forbidden p
| Sugared.Patt_IsTerm (p1, p2) ->
let forbidden = check_linear ~forbidden p1 in
check_linear ~forbidden p2
| Sugared.Patt_EqType (p1, p2) ->
let forbidden = check_linear ~forbidden p1 in
check_linear ~forbidden p2
| Sugared.Patt_EqTerm (p1, p2, p3) ->
let forbidden = check_linear ~forbidden p1 in
let forbidden = check_linear ~forbidden p2 in
check_linear ~forbidden p3
| Sugared.Patt_BoundaryIsType ->
forbidden
| Sugared.Patt_BoundaryIsTerm p ->
check_linear ~forbidden p
| Sugared.Patt_BoundaryEqType (p1, p2) ->
let forbidden = check_linear ~forbidden p1 in
check_linear ~forbidden p2
| Sugared.Patt_BoundaryEqTerm (p1, p2, p3) ->
let forbidden = check_linear ~forbidden p1 in
let forbidden = check_linear ~forbidden p2 in
check_linear ~forbidden p3
| Sugared.Patt_Abstraction (args, p) ->
let forbidden = check_linear_abstraction ~at ~forbidden args in
check_linear ~forbidden p
| Sugared.Patt_Constructor (_, ps)
| Sugared.Patt_List ps
| Sugared.Patt_Tuple ps ->
check_linear_list ~forbidden ps
and check_linear_list ~forbidden = function
| [] -> forbidden
| p :: ps ->
let forbidden = check_linear ~forbidden p in
check_linear_list ~forbidden ps
and check_linear_abstraction ~at ~forbidden = function
| [] -> forbidden
| (xopt, popt) :: args ->
let forbidden =
match xopt with
| None -> forbidden
| Some x -> check_linear_pattern_variable ~at ~forbidden x
in
let forbidden =
match popt with
| None -> forbidden
| Some p -> check_linear ~forbidden p
in
check_linear_abstraction ~at ~forbidden args
let rec comp ctx {Location.it=c';at} =
let locate x = Location.mark ~at x in
match c' with
| Sugared.Try (c, hcs) ->
let c = comp ctx c
and h = handler ~at ctx hcs in
locate (Desugared.With (h, c))
| Sugared.With (c1, c2) ->
let c1 = comp ctx c1
and c2 = comp ctx c2 in
locate (Desugared.With (c1, c2))
| Sugared.Raise c ->
let c = comp ctx c in
locate (Desugared.Raise c)
| Sugared.Let (lst, c) ->
let ctx, lst = let_clauses ~at ~toplevel:false ctx lst in
let c = comp ctx c in
locate (Desugared.Let (lst, c))
| Sugared.LetRec (lst, c) ->
let ctx, lst = letrec_clauses ~at ~toplevel:false ctx lst in
let c = comp ctx c in
locate (Desugared.LetRec (lst, c))
| Sugared.MLAscribe (c, sch) ->
let c = comp ctx c in
let sch = ml_schema ctx sch in
locate (Desugared.MLAscribe (c, sch))
| Sugared.Lookup c ->
let c = comp ctx c in
locate (Desugared.Lookup c)
| Sugared.Ref c ->
let c = comp ctx c in
locate (Desugared.Ref c)
| Sugared.Update (c1, c2) ->
let c1 = comp ctx c1
and c2 = comp ctx c2 in
locate (Desugared.Update (c1, c2))
| Sugared.Sequence (c1, c2) ->
let c1 = comp ctx c1
and c2 = comp ctx c2 in
locate (Desugared.Sequence (c1, c2))
| Sugared.Fresh (xopt, c) ->
let c = comp ctx c in
locate (Desugared.Fresh (xopt, c))
| Sugared.Meta xopt ->
locate (Desugared.Meta xopt)
| Sugared.AbstractAtom (c1,c2) ->
let c1 = comp ctx c1
and c2 = comp ctx c2 in
locate (Desugared.AbstractAtom (c1,c2))
| Sugared.Match (c, cases) ->
let c = comp ctx c
and cases = List.map (match_case ctx) cases in
locate (Desugared.Match (c, cases))
| Sugared.BoundaryAscribe (c, bdry) ->
let bdry = comp ctx bdry
and c = comp ctx c in
locate (Desugared.BoundaryAscribe (c, bdry))
| Sugared.TypeAscribe (c, t) ->
let t = comp ctx t
and c = comp ctx c in
locate (Desugared.TypeAscribe (c, t))
| Sugared.EqTypeAscribe (t1, t2, c) ->
let t1 = comp ctx t1
and t2 = comp ctx t2
and c = comp ctx c in
locate (Desugared.EqTypeAscribe (t1, t2, c))
| Sugared.EqTermAscribe (e1, e2, t, c) ->
let e1 = comp ctx e1
and e2 = comp ctx e2
and t = comp ctx t
and c = comp ctx c in
locate (Desugared.EqTermAscribe (e1, e2, t, c))
| Sugared.Abstract (xs, c) ->
let rec fold ctx ys = function
| [] ->
let c = comp ctx c in
mk_abstract ~at ys c
| (x, None) :: xs ->
let ctx = Ctx.add_bound x ctx
and ys = (x, None) :: ys in
fold ctx ys xs
| (x, Some t) :: xs ->
let ys = (let t = comp ctx t in (x, Some t) :: ys)
and ctx = Ctx.add_bound x ctx in
fold ctx ys xs
in
fold ctx [] xs
| Sugared.Substitute (e, cs) ->
let e = comp ctx e in
List.fold_left
(fun e c ->
let c = comp ctx c
and at = Location.from_to at c.Location.at in
Location.mark ~at (Desugared.Substitute (e, c)))
e cs
| Sugared.Derive (prems, c) ->
let c, prems = premises ctx prems (fun ctx -> comp ctx c) in
locate (Desugared.Derive (prems, c))
| Sugared.RuleApply (c, cs) ->
let c = comp ctx c in
let cs = List.map (comp ctx) cs in
locate (Desugared.RuleApply (c, cs))
| Sugared.Spine (e, cs) ->
spine ~at ctx e cs
| Sugared.Name x ->
begin match Ctx.get_name ~at x ctx with
| Bound i -> locate (Desugared.Bound i)
| Value pth -> locate (Desugared.Value pth)
| TTConstructor (pth, arity) ->
if arity = 0 then
locate (Desugared.TTConstructor (pth, []))
else
locate (Desugared.AsDerivation pth)
| MLConstructor (pth, arity) ->
check_ml_arity ~at x 0 arity ;
locate (Desugared.MLConstructor (pth, []))
| Operation (pth, arity) ->
check_ml_arity ~at x 0 arity ;
locate (Desugared.Operation (pth, []))
| Exception (pth, arity) ->
check_exception_arity ~at x 0 arity ;
locate (Desugared.MLException (pth, None))
end
| Sugared.Function (ps, c) ->
let rec fold ctx = function
| [] -> comp ctx c
| p :: ps ->
let ctx, p = pattern ~toplevel:false ctx p in
let c = fold ctx ps in
locate (Desugared.(Function (p, c)))
in
fold ctx ps
| Sugared.Handler hcs ->
handler ~at ctx hcs
| Sugared.List cs ->
let nil_path, _ = Ctx.get_path_nil ctx
and cons_path, _ = Ctx.get_path_cons ctx in
let rec fold ~at = function
| [] -> locate (Desugared.MLConstructor (nil_path, []))
| c :: cs ->
let c = comp ctx c in
let cs = fold ~at:(c.Location.at) cs in
locate (Desugared.MLConstructor (cons_path, [c ; cs]))
in
fold ~at cs
| Sugared.Tuple cs ->
let lst = List.map (comp ctx) cs in
locate (Desugared.Tuple lst)
| Sugared.String s ->
locate (Desugared.String s)
| Sugared.Congruence (c1, c2, cs) ->
let c1 = comp ctx c1
and c2 = comp ctx c2
and cs = List.map (comp ctx) cs in
locate (Desugared.Congruence (c1, c2, cs))
| Sugared.Rewrite (c, cs) ->
let c = comp ctx c
and cs = List.map (comp ctx) cs in
locate (Desugared.Rewrite (c, cs))
| Sugared.Context c ->
let c = comp ctx c in
locate (Desugared.Context c)
| Sugared.Occurs (c1,c2) ->
let c1 = comp ctx c1
and c2 = comp ctx c2 in
locate (Desugared.Occurs (c1,c2))
| Sugared.Convert (c1,c2) ->
let c1 = comp ctx c1
and c2 = comp ctx c2 in
locate (Desugared.Convert (c1,c2))
| Sugared.Natural c ->
let c = comp ctx c in
locate (Desugared.Natural c)
| Sugared.MLBoundaryIsType ->
locate Desugared.(MLBoundary BoundaryIsType)
| Sugared.MLBoundaryIsTerm c ->
let c = comp ctx c in
locate Desugared.(MLBoundary (BoundaryIsTerm c))
| Sugared.MLBoundaryEqType (c1, c2) ->
let c1 = comp ctx c1
and c2 = comp ctx c2 in
locate Desugared.(MLBoundary (BoundaryEqType (c1, c2)))
| Sugared.MLBoundaryEqTerm (c1, c2, c3) ->
let c1 = comp ctx c1
and c2 = comp ctx c2
and c3 = comp ctx c3 in
locate Desugared.(MLBoundary (BoundaryEqTerm (c1, c2, c3)))
and let_clauses ~at ~toplevel ctx lst =
let locate x = Location.mark ~at x in
let add = if toplevel then Ctx.add_ml_value ~at else Ctx.add_bound in
let rec fold ctx' lst' = function
| [] ->
let lst' = List.rev lst' in
ctx', lst'
| Sugared.Let_clause_ML (xys_opt, sch, c) :: clauses ->
let ys = (match xys_opt with None -> [] | Some (_, ys) -> ys) in
let c = let_clause ~at ctx ys c in
let sch = let_annotation ctx sch in
let x, ctx' =
begin match xys_opt with
| None -> locate Desugared.Patt_Anonymous, ctx'
(* XXX if x carried its location, we would use it here *)
| Some (x, _) -> locate (Desugared.Patt_Var x), add x ctx'
end
in
let lst' = Desugared.Let_clause (x, sch, c) :: lst' in
fold ctx' lst' clauses
| Sugared.Let_clause_tt (xopt, t, c) :: clauses ->
let c = let_clause_tt ctx c t in
let sch = Desugared.Let_annot_none in
let x, ctx' =
begin match xopt with
| None -> locate Desugared.Patt_Anonymous, ctx'
(* XXX if x carried its location, we would use it here *)
| Some x -> locate (Desugared.Patt_Var x), add x ctx'
end
in
let lst' = Desugared.Let_clause (x, sch, c) :: lst' in
fold ctx' lst' clauses
| Sugared.Let_clause_patt (pt, sch, c) :: clauses ->
let c = comp ctx c in
let sch = let_annotation ctx sch in
let ctx', pt = pattern ~toplevel ctx' pt in
let lst' = Desugared.Let_clause (pt, sch, c) :: lst' in
fold ctx' lst' clauses
in
let rec check_unique forbidden = function
| [] -> ()
| Sugared.Let_clause_ML (Some (x, _), _, _) :: lst
| Sugared.Let_clause_tt (Some x, _, _) :: lst ->
if Name.set_mem x forbidden
then error ~at (ParallelShadowing x)
else check_unique (Name.set_add x forbidden) lst
| Sugared.Let_clause_ML (None, _, _) :: lst
| Sugared.Let_clause_tt (None, _, _) :: lst ->
check_unique forbidden lst
| Sugared.Let_clause_patt (pt, _, _) :: lst ->
let forbidden = check_linear ~forbidden pt in
check_unique forbidden lst
in
check_unique Name.set_empty lst ;
fold ctx [] lst
and letrec_clauses ~at ~toplevel ctx lst =
let add = if toplevel then Ctx.add_ml_value ~at else Ctx.add_bound in
let ctx =
List.fold_left (fun ctx (f, _, _, _, _) -> add f ctx) ctx lst
in
let rec fold lst' = function
| [] ->
let lst' = List.rev lst' in
ctx, lst'
| (f, p, ps, sch, c) :: xcs ->
if List.exists (fun (g, _, _, _, _) -> Name.equal f g) xcs
then
error ~at (ParallelShadowing f)
else
let p, c = letrec_clause ~at ctx p ps c in
let sch = let_annotation ctx sch in
let lst' = Desugared.Letrec_clause (f, p, sch, c) :: lst' in
fold lst' xcs
in
fold [] lst
and let_clause ~at ctx ps c =
let rec fold ctx = function
| [] ->
comp ctx c
| p :: ps ->
let ctx, p = pattern ~toplevel:false ctx p in
let c = fold ctx ps in
Location.mark ~at:c.Location.at (Desugared.(Function (p, c))) (* XXX improve location *)
in
fold ctx ps
and let_clause_tt ctx c t =
let c = comp ctx c
and t = comp ctx t in
Location.mark ~at:c.Location.at (Desugared.BoundaryAscribe (c, t))
and letrec_clause ~at ctx p ps c =
let ctx, p = pattern ~toplevel:false ctx p in
let c = let_clause ~at ctx ps c in
p, c
and ml_schema ctx {Location.it=Sugared.ML_Forall (params, t); at} =
Location.mark ~at (Desugared.ML_Forall (params, mlty ctx params t))
and let_annotation ctx = function
| Sugared.Let_annot_none ->
Desugared.Let_annot_none
| Sugared.Let_annot_schema sch ->
let sch = ml_schema ctx sch in
Desugared.Let_annot_schema sch
(* To desugar a spine [c c1 c2 ... cN], we check if [c] is an identifier, in which
case we break the spine according to the arity of [c]. *)
and spine ~at ctx ({Location.it=c'; at=c_at} as c) cs =
Auxiliary function which splits a list into two parts with k
elements in the first part .
elements in the first part. *)
let split_at constr arity lst =
let rec split acc m lst =
if m = 0 then
List.rev acc,
(match lst with [] -> None | _::_ -> Some lst)
else
match lst with
| [] -> error ~at (ArityMismatch (constr, List.length acc, arity))
| x :: lst -> split (x :: acc) (m - 1) lst
in
split [] arity lst
in
let head, cs =
match c' with
| Sugared.Name x ->
begin match Ctx.get_name ~at x ctx with
| Bound i ->
Location.mark ~at:c_at (Desugared.Bound i), Some cs
| Value pth ->
Location.mark ~at:c_at (Desugared.Value pth), Some cs
| TTConstructor (pth, arity) ->
check_tt_arity ~at x (List.length cs) arity ;
let cs', cs = split_at x arity cs in
tt_constructor ~at ctx pth cs', cs
| MLConstructor (pth, arity) ->
check_ml_arity ~at x (List.length cs) arity ;
let cs', cs = split_at x arity cs in
ml_constructor ~at ctx pth cs', cs
| Operation (pth, arity) ->
(* We allow more arguments than the arity of the operation. *)
let cs', cs = split_at x arity cs in
operation ~at ctx pth cs', cs
| Exception (pth, arity) ->
begin match arity, cs with
| Nullary, [] -> ml_exception ~at ctx pth None, None
| Unary, [c] -> ml_exception ~at ctx pth (Some c), None
| Nullary, _::_ -> error ~at (ArityMismatch (x, List.length cs, 0))
| Unary, ([] | _::_::_) -> error ~at (ArityMismatch (x, List.length cs, 1))
end
end
| _ -> comp ctx c, Some cs
in
match cs with
| None -> head
| Some cs ->
let cs = List.map (comp ctx) cs in
Location.mark ~at (Desugared.Spine (head, cs))
handler cases .
and handler ~at ctx hcs =
(* for every case | op p => c we do op binder => match binder with | p => c end *)
let rec fold val_cases op_cases exc_cases = function
| [] ->
List.rev val_cases,
List.map (fun (op, cs) -> (op, List.rev cs)) op_cases,
List.rev exc_cases
| Sugared.CaseVal c :: hcs ->
let case = match_case ctx c in
fold (case::val_cases) op_cases exc_cases hcs
| Sugared.CaseOp (op, case) :: hcs ->
let (pth, case) = match_op_case ~at ctx op case in
let my_cases = match List.assoc_opt pth op_cases with Some lst -> lst | None -> [] in
let my_cases = case::my_cases in
fold val_cases ((pth, my_cases) :: op_cases) exc_cases hcs
| Sugared.CaseExc c :: hcs ->
let case = match_case ctx c in
fold val_cases op_cases (case :: exc_cases) hcs
in
let handler_val, handler_ops, handler_exc = fold [] [] [] hcs in
Location.mark ~at Desugared.(Handler {handler_val ; handler_ops; handler_exc })
a match case
and match_case ctx (p, g, c) =
ignore (check_linear p) ;
let ctx, p = pattern ~toplevel:false ctx p in
let g = when_guard ctx g
and c = comp ctx c in
(p, g, c)
and when_guard ctx = function
| None -> None
| Some c ->
let c = comp ctx c in
Some c
and match_op_case ~at ctx op (ps, pt, c) =
match Ctx.get_name ~at op ctx with
| (Bound _ | Value _ | Exception _ | TTConstructor _ | MLConstructor _) as info ->
error ~at (OperationExpected (op, info))
| Operation (pth, arity) ->
check_ml_arity ~at op (List.length ps) arity ;
let rec fold ctx qs = function
| [] ->
let qs = List.rev qs in
let ctx, pt =
begin match pt with
| None -> ctx, None
| Some p ->
ignore (check_linear p) ;
let ctx, p = pattern ~toplevel:false ctx p in
ctx, Some p
end
in
let c = comp ctx c in
pth, (qs, pt, c)
| p :: ps ->
let ctx, q = pattern ~toplevel:false ctx p in
fold ctx (q :: qs) ps
in
fold ctx [] ps
and ml_constructor ~at ctx x cs =
let cs = List.map (comp ctx) cs in
Location.mark ~at (Desugared.MLConstructor (x, cs))
and tt_constructor ~at ctx pth cs =
let cs = List.map (comp ctx) cs in
Location.mark ~at (Desugared.TTConstructor (pth, cs))
and operation ~at ctx x cs =
let cs = List.map (comp ctx) cs in
Location.mark ~at (Desugared.Operation (x, cs))
and ml_exception ~at ctx x copt =
let c = match copt with None -> None | Some c -> Some (comp ctx c) in
Location.mark ~at (Desugared.MLException (x, c))
and local_context :
'a . Ctx.t -> Sugared.local_context -> (Ctx.t -> 'a) -> 'a * Desugared.local_context
= fun ctx xcs m ->
let rec fold ctx xcs_out = function
| [] ->
let xcs_out = List.rev xcs_out in
let v = m ctx in
v, xcs_out
| (x, c) :: xcs ->
let c = comp ctx c in
let ctx = Ctx.add_bound x ctx in
fold ctx ((x,c) :: xcs_out) xcs
in
fold ctx [] xcs
and premise ctx {Location.it=prem;at} =
let locate x = Location.mark ~at x in
let Sugared.Premise (mvar, local_ctx, c) = prem in
let bdry, local_ctx = local_context ctx local_ctx (fun ctx -> comp ctx c) in
let mvar = (match mvar with Some mvar -> mvar | None -> Name.anonymous ()) in
let ctx = Ctx.add_bound mvar ctx in
ctx, locate (Desugared.Premise (mvar, local_ctx, bdry))
and premises :
'a . Ctx.t -> Sugared.premise list -> (Ctx.t -> 'a) -> 'a * Desugared.premise list
= fun ctx prems m ->
let rec fold ctx prems_out = function
| [] ->
let v = m ctx in
let prems_out = List.rev prems_out in
v, prems_out
| prem :: prems ->
let ctx, prem = premise ctx prem in
fold ctx (prem :: prems_out) prems
in
fold ctx [] prems
let decl_operation ~at ctx args res =
let args = List.map (mlty ctx []) args
and res = mlty ctx [] res in
args, res
let mlty_constructor ~at ctx params (c, args) =
(c, List.map (mlty ctx params) args)
let mlty_def ~at ctx params = function
| Sugared.ML_Alias ty ->
let ty = mlty ctx params ty in
Desugared.ML_Alias ty
| Sugared.ML_Sum lst ->
let lst = List.map (mlty_constructor ~at ctx params) lst in
Desugared.ML_Sum lst
let mlty_info params = function
| Sugared.ML_Alias _ -> (ml_arity params), None
| Sugared.ML_Sum lst ->
let cs = List.map (fun (c, args) -> (c, ml_arity args)) lst in
(ml_arity params),
Some cs
let mlty_defs ~at ctx defs =
let rec fold defs_out ctx = function
| [] -> ctx, List.rev defs_out
| (t, (params, def)) :: defs_in ->
let def_out = mlty_def ~at ctx params def in
let t_pth, ctx = Ctx.add_ml_type ~at t (mlty_info params def) ctx in
fold ((t_pth, (params, def_out)) :: defs_out) ctx defs_in
in
fold [] ctx defs
let mlty_rec_defs ~at ctx defs =
(* first change the context *)
let defs_out, ctx =
List.fold_left
(fun (defs_out, ctx) (t, (params, def)) ->
let t_pth, ctx = Ctx.add_ml_type ~at t (mlty_info params def) ctx in
((t_pth, (params, def)) :: defs_out, ctx))
([], ctx) defs
in
let defs_out = List.rev defs_out in
(* check for parallel shadowing *)
let check_shadow = function
| [] -> ()
| (t, _) :: defs ->
if List.exists (fun (t', _) -> Name.equal t t') defs then
error ~at (ParallelShadowing t)
in
check_shadow defs ;
let defs_out =
List.map (fun (t, (params, def)) -> (t, (params, mlty_def ~at ctx params def))) defs_out in
ctx, defs_out
let rec toplevel' ctx {Location.it=cmd; at} =
let locate1 cmd = [Location.mark ~at cmd] in
match cmd with
| Sugared.Rule (rname, prems, c) ->
let arity = tt_arity prems in
let bdry, prems =
premises
ctx prems
(fun ctx -> comp ctx c)
in
let pth, ctx = Ctx.add_tt_constructor ~at rname arity ctx in
(ctx, locate1 (Desugared.Rule (pth, prems, bdry)))
| Sugared.DeclOperation (op, (args, res)) ->
let args, res = decl_operation ~at ctx args res in
let pth, ctx = Ctx.add_operation ~at op (ml_arity args) ctx in
(ctx, locate1 (Desugared.DeclOperation (pth, (args, res))))
| Sugared.DeclException (exc, tyopt) ->
let arity, tyopt =
match tyopt with
| None -> Nullary, None
| Some ty -> Unary,Some (mlty ctx [] ty)
in
let pth, ctx = Ctx.add_exception ~at exc (ml_exception_arity tyopt) ctx in
(ctx, locate1 (Desugared.DeclException (pth, tyopt)))
| Sugared.DefMLTypeAbstract (t, params) ->
let t_pth, ctx = Ctx.add_ml_type ~at t (List.length params, None) ctx in
(ctx, locate1 (Desugared.DefMLTypeAbstract (t_pth, params)))
| Sugared.DefMLType defs ->
let ctx, defs = mlty_defs ~at ctx defs in
(ctx, locate1 (Desugared.DefMLType defs))
| Sugared.DefMLTypeRec defs ->
let ctx, defs = mlty_rec_defs ~at ctx defs in
(ctx, locate1 (Desugared.DefMLTypeRec defs))
| Sugared.DeclExternal (x, sch, s) ->
let sch = ml_schema ctx sch in
let ctx = Ctx.add_ml_value ~at x ctx in
(ctx, locate1 (Desugared.DeclExternal (x, sch, s)))
| Sugared.TopLet lst ->
let ctx, lst = let_clauses ~at ~toplevel:true ctx lst in
(ctx, locate1 (Desugared.TopLet lst))
| Sugared.TopLetRec lst ->
let ctx, lst = letrec_clauses ~at ~toplevel:true ctx lst in
(ctx, locate1 (Desugared.TopLetRec lst))
| Sugared.TopWith lst ->
let lst = List.map (fun (op, case) -> match_op_case ~at ctx op case) lst in
(ctx, locate1 (Desugared.TopWith lst))
| Sugared.TopComputation c ->
let c = comp ctx c in
(ctx, locate1 (Desugared.TopComputation c))
| Sugared.Verbosity n ->
(ctx, locate1 (Desugared.Verbosity n))
| Sugared.Require mdl_names ->
(* requires are preprocessed, skip them in later stages *)
(ctx, [])
| Sugared.Include mdl_path ->
let _, mdl = Ctx.get_ml_module ~at mdl_path ctx in
let ctx = Ctx.include_ml_module ~at mdl ctx in
(ctx, [])
| Sugared.Open mdl_path ->
let pth, mdl = Ctx.get_ml_module ~at mdl_path ctx in
let ctx = Ctx.open_ml_module ~at mdl ctx in
(ctx, locate1 (Desugared.Open pth))
| Sugared.TopModule (x, cmds) ->
let ctx, cmd = ml_module ~at ctx x cmds in
(ctx, [cmd])
a list of top - level commands in the current context . Return the new context and
the desugared commands . Assume all required modules have been loaded .
the desugared commands. Assume all required modules have been loaded. *)
and toplevels ctx cmds =
let ctx, cmds =
List.fold_left
(fun (ctx,cmds) cmd ->
let ctx, cmds' = toplevel' ctx cmd in
(ctx, cmds' @ cmds))
(ctx, [])
cmds
in
let cmds = List.rev cmds in
ctx, cmds
(* Desugare the given commands as the definition of a module [m]. Return the new context,
and the desugared module definition. Assume all required modules have been loaded. *)
and ml_module ~at ctx m cmds =
let ctx = Ctx.push_module m ctx in
let ctx, cmds = toplevels ctx cmds in
let ctx, mdl = Ctx.pop_module ctx in
let ctx = Ctx.add_ml_module ~at m mdl ctx in
ctx, Location.mark ~at (Desugared.MLModule (m, cmds))
(* Load the modules required by the given commands, recursively. Return the new context,
and the loaded modules. *)
let rec load_requires ~basedir ~loading ctx cmds =
let require ~at ~loading ctx mdl_name =
match Ctx.find_ml_module (Name.PName mdl_name) ctx with
| Some _ ->
(* already loaded *)
ctx, []
| None ->
(* not loaded yet *)
if List.exists (Name.equal mdl_name) loading then
(* We are in the process of loading this module, circular dependency *)
error ~at (CircularRequire (List.rev (mdl_name :: loading)))
else
let rec unique xs = function
| [] -> List.rev xs
| y :: ys ->
if List.mem y xs then unique xs ys else unique (y::xs) ys
in
let basename = Name.module_filename mdl_name in
let fns =
unique []
(List.map
(fun dirname -> Filename.concat dirname basename)
(basedir :: (!Config.require_dirs))
)
in
match List.find_opt Sys.file_exists fns with
| None ->
error ~at (RequiredModuleMissing (mdl_name, fns))
| Some fn ->
let loading = mdl_name :: loading in
let cmds = Lexer.read_file ?line_limit:None Parser.file fn in
let ctx, mdls = load_requires ~loading ~basedir ctx cmds in
let ctx, mdl = ml_module ~at ctx mdl_name cmds in
ctx, (mdls @ [mdl])
in
let rec fold ~loading ctx = function
| [] -> ctx, []
| Location.{it=cmd; at} :: cmds ->
begin match cmd with
| Sugared.Require mdl_names ->
let ctx, mdls_required =
List.fold_left
(fun (ctx, mdls) mdl_name ->
let ctx, mdls' = require ~loading ~at ctx mdl_name in
(ctx, mdls @ mdls'))
(ctx, [])
mdl_names
in
let ctx, mdls = fold ~loading ctx cmds in
ctx, mdls_required @ mdls
| Sugared.TopModule (_, cmds') ->
let ctx, mdls' = fold ~loading ctx cmds' in
let ctx, mdls = fold ~loading ctx cmds in
ctx, mdls' @ mdls
| Sugared.(Rule _ | DefMLTypeAbstract _ |
DefMLType _ | DefMLTypeRec _ | DeclOperation _ | DeclException _ | DeclExternal _ |
TopLet _ | TopLetRec _ | TopWith _ | TopComputation _ |
Include _ | Verbosity _ | Open _) ->
fold ~loading ctx cmds
end
in
fold ~loading ctx cmds
commands , after loading the required modules
let commands ~loading ~basedir ctx cmds =
let ctx, mdls = load_requires ~loading:[] ~basedir ctx cmds in
let ctx, cmds = toplevels ctx cmds in
ctx, (mdls @ cmds)
let toplevel ~basedir ctx cmd =
commands ~loading:[] ~basedir ctx [cmd]
(** Load a file, return the list of desugared commands, including required modules. *)
let use_file ctx fn =
let cmds = Lexer.read_file ?line_limit:None Parser.file fn in
let basedir = Filename.dirname fn in
commands ~loading:[] ~basedir ctx cmds
and load_ml_module ctx fn =
let basename = Filename.basename fn in
let dirname = Filename.dirname fn in
let mdl_name = Name.mk_name (Filename.remove_extension basename) in
let cmds = Lexer.read_file ?line_limit:None Parser.file fn in
let ctx, mdls = load_requires ~loading:[mdl_name] ~basedir:dirname ctx cmds in
let ctx, cmd = ml_module ~at:Location.unknown ctx mdl_name cmds in
ctx, (mdls @ [cmd])
let initial_context, initial_commands =
try
commands ~loading:[] ~basedir:Filename.current_dir_name Ctx.empty Builtin.initial
with
| Error {Location.it=err;_} ->
Print.error "Error in built-in code:@ %t.@." (print_error err) ;
Stdlib.exit 1
module Builtin =
struct
let bool = fst (Ctx.get_ml_type ~at:Location.unknown Name.Builtin.bool initial_context)
let mlfalse = fst (Ctx.get_ml_constructor Name.Builtin.mlfalse initial_context)
let mltrue = fst (Ctx.get_ml_constructor Name.Builtin.mltrue initial_context)
let list = fst (Ctx.get_ml_type ~at:Location.unknown Name.Builtin.list initial_context)
let nil = fst (Ctx.get_ml_constructor Name.Builtin.nil initial_context)
let cons = fst (Ctx.get_ml_constructor Name.Builtin.cons initial_context)
let option = fst (Ctx.get_ml_type ~at:Location.unknown Name.Builtin.option initial_context)
let none = fst (Ctx.get_ml_constructor Name.Builtin.none initial_context)
let some = fst (Ctx.get_ml_constructor Name.Builtin.some initial_context)
let mlless = fst (Ctx.get_ml_constructor Name.Builtin.mlless initial_context)
let mlequal = fst (Ctx.get_ml_constructor Name.Builtin.mlequal initial_context)
let mlgreater = fst (Ctx.get_ml_constructor Name.Builtin.mlgreater initial_context)
let equal_type = fst (Ctx.get_ml_operation Name.Builtin.equal_type initial_context)
let coerce = fst (Ctx.get_ml_operation Name.Builtin.coerce initial_context)
let eqchk_excs = fst (Ctx.get_ml_exception Name.Builtin.eqchk_excs initial_context)
end
| null | https://raw.githubusercontent.com/Andromedans/andromeda/a5c678450e6c6d4a7cd5eee1196bde558541b994/src/parser/desugar.ml | ocaml | * Arity of an ML exception
* Information about names
Partially evaluated nested modules
the locally bound values, referred to by indices
There should always be at least the top module
Convert a context to a module.
Lookup functions named [find_XYZ] return optional results,
while those named [get_XYZ] require a location and either return
a result or trigger an error.
Find information about the given name in the given module.
Find information about the given name in the current context.
Check that the name is not bound already
Check that the type is not bound already
Check that the module is not bound already
This will be needed if and when there is a builtin global ML value that has to be looked up.
Get the info about a path, or fail
check whether it is locally bound
Get information about the list empty list constructor
Get the path and the arity of type named [t]
Add a module to the current module.
Add a local bound value.
Add an operation of given arity
Add an exception of given arity
Add to the context the fact that [t] is a type constructor with given constructors and arities.
Check that the arity is the expected one.
Check that the arity is the expected one.
Check that the arity is the expected one.
It could be one of the bound type parameters
It's a type name
It's a type parameter
* Verify that a pattern is linear and that it does not bind anything
in the given set of forbidden names. Return the set of forbidden names
extended with the names that this pattern binds.
XXX if x carried its location, we would use it here
XXX if x carried its location, we would use it here
XXX improve location
To desugar a spine [c c1 c2 ... cN], we check if [c] is an identifier, in which
case we break the spine according to the arity of [c].
We allow more arguments than the arity of the operation.
for every case | op p => c we do op binder => match binder with | p => c end
first change the context
check for parallel shadowing
requires are preprocessed, skip them in later stages
Desugare the given commands as the definition of a module [m]. Return the new context,
and the desugared module definition. Assume all required modules have been loaded.
Load the modules required by the given commands, recursively. Return the new context,
and the loaded modules.
already loaded
not loaded yet
We are in the process of loading this module, circular dependency
* Load a file, return the list of desugared commands, including required modules. | * Conversion from sugared to desugared input syntax . The responsibilities of
this phase is to :
* resolve all names to levels and indices
* check arities of constructors and operations
Note that we do not check arities of derivations here because those are first - class
and are not bound to specific identifiers , and so we have no way of computing them
in the desugaring phase .
We could consider moving arity checking of all entitites to typechecking , but then
we need to worry about separate namespaces in which they might leave , and it would
just induce some pointless code refactoring .
this phase is to:
* resolve all names to levels and indices
* check arities of constructors and operations
Note that we do not check arities of derivations here because those are first-class
and are not bound to specific identifiers, and so we have no way of computing them
in the desugaring phase.
We could consider moving arity checking of all entitites to typechecking, but then
we need to worry about separate namespaces in which they might leave, and it would
just induce some pointless code refactoring.
*)
* Association tables with de Bruijn levels .
module Assoc :
sig
type 'a t
val empty : 'a t
val add : Name.t -> 'a -> 'a t -> 'a t
val last : 'a t -> int
val find : Name.t -> 'a t -> 'a option
val include' : (Name.t -> unit) -> 'a t -> 'a t -> 'a t
val open' : (Name.t -> unit) -> 'a t -> 'a t -> 'a t
val export : 'a t -> 'a t
end =
struct
type export = Exported | NotExported
type 'a t =
{ last : int ; assoc : ('a * export) Name.map }
let empty = { last = 0 ; assoc = Name.map_empty }
let add x y {last; assoc} =
{ last = last + 1 ; assoc = Name.map_add x (y, Exported) assoc }
let redirect expo check_fresh {last; assoc} {assoc=assoc';_} =
{ last ;
assoc = Name.map_fold (fun k (v,_) assoc -> check_fresh k ; Name.map_add k (v, expo) assoc) assoc' assoc
}
let include' check_fresh asc asc' = redirect Exported check_fresh asc asc'
let open' check_fresh asc asc' = redirect NotExported check_fresh asc asc'
let export {last; assoc} =
{ last ;
assoc = Name.map_fold
(fun k ve assoc ->
match snd ve with
| Exported -> Name.map_add k ve assoc
| NotExported -> assoc)
assoc Name.map_empty
}
let last {last; _} = last
let find x {assoc; _} =
try
Some (fst (Name.map_find x assoc))
with
Not_found -> None
end
* Arity of a TT constructor
type tt_arity = int
* Arity of an ML constructor or opertation
type ml_arity = int
type exception_arity = Nullary | Unary
A module has three name spaces , one for ML modules , one for ML types and the other for
everything else . However , we keep operations , , TT constructors , and
values in separate lists because we need to compute their indices . All entities are
accessed by levels .
everything else. However, we keep operations, ML constructos, TT constructors, and
values in separate lists because we need to compute their indices. All entities are
accessed by de Bruijn levels. *)
type ml_module = {
ml_modules : (Path.t * ml_module) Assoc.t;
ml_types : (Path.t * ml_arity) Assoc.t;
ml_constructors : ((Path.t * Path.level) * ml_arity) Assoc.t;
ml_operations : (Path.t * ml_arity) Assoc.t;
ml_exceptions : (Path.t * exception_arity) Assoc.t;
tt_constructors : (Path.t * tt_arity) Assoc.t;
ml_values : Path.t Assoc.t
}
let empty_module = {
ml_modules = Assoc.empty;
ml_types = Assoc.empty;
ml_constructors = Assoc.empty;
ml_operations = Assoc.empty;
ml_exceptions = Assoc.empty;
tt_constructors = Assoc.empty;
ml_values = Assoc.empty
}
type info =
| Bound of Path.index
| Value of Path.t
| TTConstructor of Path.t * tt_arity
| MLConstructor of Path.ml_constructor * ml_arity
| Operation of Path.t * ml_arity
| Exception of Path.t * exception_arity
let print_info info ppf = match info with
| Bound _ | Value _ -> Format.fprintf ppf "a value"
| TTConstructor _ -> Format.fprintf ppf "a constructor"
| MLConstructor _ -> Format.fprintf ppf "an ML constructor"
| Operation _ -> Format.fprintf ppf "an operation"
| Exception _ -> Format.fprintf ppf "an exception"
type error =
| UnknownPath of Name.path
| UnknownType of Name.path
| UnknownModule of Name.path
| NameAlreadyDeclared of Name.t * info
| MLTypeAlreadyDeclared of Name.t
| MLModuleAlreadyDeclared of Name.t
| OperationExpected : Name.path * info -> error
| InvalidPatternVariable : Name.t -> error
| InvalidPatternName : Name.path * info -> error
| InvalidAppliedPatternName : Name.path * info -> error
| NonlinearPattern : Name.t -> error
| ArityMismatch of Name.path * int * int
| ParallelShadowing of Name.t
| AppliedTyParam
| RequiredModuleMissing of Name.t * string list
| CircularRequire of Name.t list
let print_error err ppf = match err with
| UnknownPath pth ->
Format.fprintf ppf "unknown name %t"
(Name.print_path pth)
| UnknownType pth ->
Format.fprintf ppf "unknown type %t"
(Name.print_path pth)
| UnknownModule pth ->
Format.fprintf ppf "unknown ML module %t"
(Name.print_path pth)
| NameAlreadyDeclared (x, info) ->
Format.fprintf ppf
"%t is already declared as %t"
(Name.print x)
(print_info info)
| MLTypeAlreadyDeclared x ->
Format.fprintf ppf
"%t is already a defined ML type"
(Name.print x)
| MLModuleAlreadyDeclared x ->
Format.fprintf ppf
"%t is already a defind ML module"
(Name.print x)
| OperationExpected (pth, info) ->
Format.fprintf ppf "%t should be an operation but is %t"
(Name.print_path pth)
(print_info info)
| InvalidPatternName (pth, info) ->
Format.fprintf ppf "%t cannot be used in a pattern as it is %t"
(Name.print_path pth)
(print_info info)
| InvalidPatternVariable x ->
Format.fprintf ppf "%t is an invalid pattern variable, perhaps you meant ?%t"
(Name.print x)
(Name.print x)
| InvalidAppliedPatternName (pth, info) ->
Format.fprintf ppf "%t cannot be applied in a pattern as it is %t"
(Name.print_path pth)
(print_info info)
| NonlinearPattern x ->
Format.fprintf ppf "pattern variable %t appears more than once"
(Name.print x)
| ArityMismatch (pth, used, expected) ->
Format.fprintf ppf "%t expects %d arguments but is used with %d"
(Name.print_path pth)
expected
used
| ParallelShadowing x ->
Format.fprintf ppf "%t is bound more than once"
(Name.print x)
| AppliedTyParam ->
Format.fprintf ppf "an ML type parameter cannot be applied"
| RequiredModuleMissing (mdl_name, files) ->
Format.fprintf ppf "required module %t could not be found, looked in:@\n@[<hv>%t@]"
(Name.print mdl_name)
(Print.sequence (fun fn ppf -> Format.fprintf ppf "%s" fn) "," files)
| CircularRequire mdls ->
Format.fprintf ppf "circuar module dependency (@[<hov -2>%t@])"
(Print.sequence (Name.print ~parentheses:false) "," mdls)
exception Error of error Location.located
let error ~at err = Stdlib.raise (Error (Location.mark ~at err))
module Ctx = struct
type t = {
current_modules : (Path.t option * ml_module) list ;
}
let empty = {
current_modules = [(None, empty_module)] ;
ml_bound = [];
}
let current_module {current_modules;_} =
match current_modules with
| (_, mdl) :: _ -> mdl
let update_current ctx update =
let mk_path optpath x lvl =
match optpath with
| None -> Path.Direct (Path.Level (x, lvl))
| Some p -> Path.Module (p, Path.Level (x, lvl))
in
match ctx.current_modules with
| [] -> assert false
| (optpath, mdl) :: mdls ->
let pth, mdl = update (mk_path optpath) mdl in
pth, { ctx with current_modules = (optpath, mdl) :: mdls }
let export_ml_module {ml_modules; ml_types; ml_constructors; ml_operations; ml_exceptions; tt_constructors; ml_values} =
{
ml_modules = Assoc.export ml_modules;
ml_types = Assoc.export ml_types;
ml_constructors = Assoc.export ml_constructors;
ml_operations = Assoc.export ml_operations;
ml_exceptions = Assoc.export ml_exceptions;
tt_constructors = Assoc.export tt_constructors;
ml_values = Assoc.export ml_values;
}
let push_module mdl_name ctx =
match ctx.current_modules with
| [] -> assert false
| ((pth_opt, mdl) :: _) as mdls ->
let mdl_lvl = Assoc.last mdl.ml_modules in
let pth =
match pth_opt with
| None -> Path.Direct (Path.Level (mdl_name, mdl_lvl))
| Some pth -> Path.Module (pth, Path.Level (mdl_name, mdl_lvl))
in
{ ctx with current_modules = (Some pth, empty_module) :: mdls }
let pop_module ctx =
match ctx.current_modules with
| [] | [_] -> assert false
| (_, mdl) :: mdls ->
let mdl = export_ml_module mdl in
{ ctx with current_modules = mdls }, mdl
let find_name_in_module x mdl =
match Assoc.find x mdl.ml_values with
| Some pth -> Some (Value pth)
| None ->
begin match Assoc.find x mdl.tt_constructors with
| Some (pth, arity) -> Some (TTConstructor (pth, arity))
| None ->
begin match Assoc.find x mdl.ml_operations with
| Some (pth, arity) -> Some (Operation (pth, arity))
| None ->
begin match Assoc.find x mdl.ml_constructors with
| Some (pth, arity) -> Some (MLConstructor (pth, arity))
| None ->
begin match Assoc.find x mdl.ml_exceptions with
| Some (pth, arity) -> Some (Exception (pth, arity))
| None -> None
end
end
end
end
let find_type_in_module t mdl = Assoc.find t mdl.ml_types
let find_module_in_module m mdl = Assoc.find m mdl.ml_modules
let rec find_path
: 'a . find:(Name.t -> ml_module -> 'a option) -> Name.path -> t -> 'a option
= fun ~find pth ctx ->
match pth with
| Name.PName x ->
find_direct ~find x ctx
| Name.PModule (pth, x) ->
begin match find_ml_module pth ctx with
| Some (pth, mdl) -> find x mdl
| None -> None
end
and find_direct
: 'a . find:(Name.t -> ml_module -> 'a option) -> Name.t -> t -> 'a option
= fun ~find x ctx ->
let rec search = function
| [] -> None
| (_, mdl) :: mdls ->
begin match find x mdl with
| Some _ as info -> info
| None -> search mdls
end
in
search ctx.current_modules
and find_ml_module pth ctx = find_path ~find:find_module_in_module pth ctx
let find_name pth ctx = find_path ~find:find_name_in_module pth ctx
let find_ml_type pth ctx = find_path ~find:find_type_in_module pth ctx
let check_is_fresh_name ~at x ctx =
match find_name_in_module x (current_module ctx) with
| None -> ()
| Some info -> error ~at (NameAlreadyDeclared (x, info))
let check_is_fresh_type ~at t ctx =
match find_type_in_module t (current_module ctx) with
| None -> ()
| Some info -> error ~at (MLTypeAlreadyDeclared t)
let check_is_fresh_module ~at m ctx =
match find_module_in_module m (current_module ctx) with
| None -> ()
| Some _ -> error ~at (MLModuleAlreadyDeclared m)
Get information about the given ML constructor .
let get_ml_constructor pth ctx =
match find_name pth ctx with
| Some (MLConstructor (pth, arity)) -> pth, arity
| None |Some (Bound _ | Value _ | TTConstructor _ | Operation _ | Exception _) ->
assert false
Get information about the given ML operation .
let get_ml_operation op ctx =
match find_name op ctx with
| Some (Operation (pth, arity)) -> pth, arity
| None | Some (Bound _ | Value _ | TTConstructor _ | MLConstructor _ | Exception _) ->
assert false
Get information about the given ML operation .
let get_ml_exception exc ctx =
match find_name exc ctx with
| Some (Exception (pth, arity)) -> pth, arity
| None | Some (Bound _ | Value _ | TTConstructor _ | MLConstructor _ | Operation _) ->
assert false
let get_ml_value x ctx =
* match find_name x ctx with
* | Some ( Value v ) - > v
* | None | Some ( Bound _ | TTConstructor _ _ | Operation _ ) - >
* assert false
* match find_name x ctx with
* | Some (Value v) -> v
* | None | Some (Bound _ | TTConstructor _ | MLConstructor _ | Operation _) ->
* assert false *)
Get information about the given ML module .
let get_ml_module ~at pth ctx =
match find_ml_module pth ctx with
| Some (pth, mdl) -> pth, mdl
| None -> error ~at (UnknownModule pth)
let get_name ~at pth ctx =
match pth with
| Name.PName x ->
let find_index x lst =
let rec search i = function
| [] -> None
| x' :: lst -> if Name.equal x x' then Some i else search (i+1) lst
in
search 0 lst
in
begin match find_index x ctx.ml_bound with
| Some i -> Bound (Path.Index (x, i))
| None ->
begin match find_name pth ctx with
| Some info -> info
| None -> error ~at (UnknownPath pth)
end
end
| Name.PModule _ ->
begin match find_name pth ctx with
| Some info -> info
| None -> error ~at (UnknownPath pth)
end
let get_path_nil ctx =
get_ml_constructor Name.Builtin.nil ctx
let get_path_cons ctx =
get_ml_constructor Name.Builtin.cons ctx
let get_ml_type ~at pth ctx =
match find_ml_type pth ctx with
| None -> error ~at (UnknownType pth)
| Some info ->
info
let add_ml_module ~at m mdl ctx =
check_is_fresh_module ~at m ctx ;
let (), ctx =
update_current ctx
(fun mk_path current ->
let lvl = Assoc.last current.ml_modules in
let pth = mk_path m lvl in
(), { current with ml_modules = Assoc.add m (pth, mdl) current.ml_modules } )
in
ctx
let include_ml_module ~at mdl ctx =
let (), ctx =
update_current ctx
(fun _ {ml_modules; ml_types; ml_constructors; ml_operations; ml_exceptions; tt_constructors; ml_values} ->
(), { ml_modules = Assoc.include' (fun m -> check_is_fresh_module ~at m ctx) ml_modules mdl.ml_modules;
ml_types = Assoc.include' (fun t -> check_is_fresh_type ~at t ctx) ml_types mdl.ml_types;
ml_constructors = Assoc.include' (fun x -> check_is_fresh_name ~at x ctx) ml_constructors mdl.ml_constructors;
ml_operations = Assoc.include' (fun x -> check_is_fresh_name ~at x ctx) ml_operations mdl.ml_operations;
ml_exceptions = Assoc.include' (fun x -> check_is_fresh_name ~at x ctx) ml_exceptions mdl.ml_exceptions;
tt_constructors = Assoc.include' (fun x -> check_is_fresh_name ~at x ctx) tt_constructors mdl.tt_constructors;
ml_values = Assoc.include' (fun x -> check_is_fresh_name ~at x ctx) ml_values mdl.ml_values;
})
in
ctx
let open_ml_module ~at mdl ctx =
let (), ctx =
update_current ctx
(fun _ {ml_modules; ml_types; ml_constructors; ml_operations; ml_exceptions; tt_constructors; ml_values} ->
(), { ml_modules = Assoc.open' (fun m -> check_is_fresh_module ~at m ctx) ml_modules mdl.ml_modules;
ml_types = Assoc.open' (fun t -> check_is_fresh_type ~at t ctx) ml_types mdl.ml_types;
ml_constructors = Assoc.open' (fun x -> check_is_fresh_name ~at x ctx) ml_constructors mdl.ml_constructors;
ml_operations = Assoc.open' (fun x -> check_is_fresh_name ~at x ctx) ml_operations mdl.ml_operations;
ml_exceptions = Assoc.open' (fun x -> check_is_fresh_name ~at x ctx) ml_exceptions mdl.ml_exceptions;
tt_constructors = Assoc.open' (fun x -> check_is_fresh_name ~at x ctx) tt_constructors mdl.tt_constructors;
ml_values = Assoc.open' (fun x -> check_is_fresh_name ~at x ctx) ml_values mdl.ml_values;
})
in
ctx
Add an ML values to the current module .
let add_ml_value ~at x ctx =
check_is_fresh_name ~at x ctx ;
let (), ctx =
update_current ctx
(fun mk_path current ->
let lvl = Assoc.last current.ml_values in
let pth = mk_path x lvl in
(), { current with ml_values = Assoc.add x pth current.ml_values } )
in
ctx
let add_bound x ctx =
{ ctx with ml_bound = x :: ctx.ml_bound }
Add a TT constructor of given arity
let add_tt_constructor ~at c arity ctx =
check_is_fresh_name ~at c ctx ;
update_current ctx
(fun mk_path current ->
let lvl = Assoc.last current.tt_constructors in
let pth = mk_path c lvl in
pth, { current with tt_constructors = Assoc.add c (pth, arity) current.tt_constructors } )
let add_operation ~at op arity ctx =
check_is_fresh_name ~at op ctx ;
update_current ctx
(fun mk_path current ->
let lvl = Assoc.last current.ml_operations in
let pth = mk_path op lvl in
pth, { current with ml_operations = Assoc.add op (pth, arity) current.ml_operations } )
let add_exception ~at exc arity ctx =
check_is_fresh_name ~at exc ctx ;
update_current ctx
(fun mk_path current ->
let lvl = Assoc.last current.ml_exceptions in
let pth = mk_path exc lvl in
pth, { current with ml_exceptions = Assoc.add exc (pth, arity) current.ml_exceptions } )
Add a ML constructor of given arity
let add_ml_constructor ~at c info ctx =
check_is_fresh_name ~at c ctx ;
let (), ctx =
update_current ctx
(fun mk_path current ->
(), { current with ml_constructors = Assoc.add c info current.ml_constructors } )
in
ctx
let add_ml_type ~at t (arity, cs_opt) ctx =
check_is_fresh_type ~at t ctx ;
let t_pth, ctx =
update_current ctx
(fun mk_path current ->
let lvl = Assoc.last current.ml_types in
let pth = mk_path t lvl in
pth, { current with ml_types = Assoc.add t (pth, arity) current.ml_types })
in
match cs_opt with
| None -> t_pth, ctx
| Some cs ->
begin match find_type_in_module t (current_module ctx) with
| None -> assert false
| Some (t_pth, _) ->
let _, ctx =
List.fold_left
(fun (lvl, ctx) (c, arity) ->
let ctx = add_ml_constructor ~at c ((t_pth, Path.Level (c, lvl)), arity) ctx in
(lvl+1, ctx))
(0, ctx)
cs
in
t_pth, ctx
end
module
let check_ml_arity ~at pth used expected =
if used <> expected then
error ~at (ArityMismatch (pth, used, expected))
let check_exception_arity ~at pth used expected =
let card = function Nullary -> 0 | Unary -> 1 in
if used <> card expected then
error ~at (ArityMismatch (pth, used, card expected))
Compute the arity of a TT constructor , given the premises of its rule .
let tt_arity prems = List.length prems
Compute the arity of a ML constructor .
let ml_arity = List.length
Compute the arity of an ML exception .
let ml_exception_arity = function
| None -> Nullary
| Some _ -> Unary
let check_tt_arity ~at pth used expected =
if used <> expected then
error ~at (ArityMismatch (pth, used, expected))
an ML type , with the given list of known type parameters
let mlty ctx params ty =
let rec mlty ({Location.it=ty';at}) =
let ty' =
begin match ty' with
| Sugared.ML_Arrow (ty1, ty2) ->
let ty1 = mlty ty1
and ty2 = mlty ty2 in
Desugared.ML_Arrow (ty1, ty2)
| Sugared.ML_Handler (ty1, ty2) ->
let ty1 = mlty ty1
and ty2 = mlty ty2 in
Desugared.ML_Handler (ty1, ty2)
| Sugared.ML_Ref t ->
let t = mlty t in
Desugared.ML_Ref t
| Sugared.ML_Exn ->
Desugared.ML_Exn
| Sugared.ML_Prod tys ->
let tys = List.map mlty tys in
Desugared.ML_Prod tys
| Sugared.ML_TyApply (pth, args) ->
begin match pth with
| Name.PModule _ ->
let (t_pth, expected) = Ctx.get_ml_type ~at pth ctx in
check_ml_arity ~at pth (List.length args) expected ;
let args = List.map mlty args in
Desugared.ML_Apply (t_pth, args)
| Name.PName x ->
let rec search k = function
| [] ->
begin
let (t_pth, expected) = Ctx.get_ml_type ~at pth ctx in
check_ml_arity ~at pth (List.length args) expected ;
let args = List.map mlty args in
Desugared.ML_Apply (t_pth, args)
end
| None :: params -> search k params
| Some y :: params ->
if Name.equal x y then
begin match args with
| [] -> Desugared.ML_Bound (Path.Index (x, k))
| _::_ -> error ~at AppliedTyParam
end
else search (k+1) params
in
search 0 params
end
| Sugared.ML_Anonymous ->
Desugared.ML_Anonymous
| Sugared.ML_Judgement ->
Desugared.ML_Judgement
| Sugared.ML_Boundary ->
Desugared.ML_Boundary
| Sugared.ML_Derivation ->
Desugared.ML_Derivation
| Sugared.ML_String -> Desugared.ML_String
end
in
Location.mark ~at ty'
in
mlty ty
TODO improve locs
let mk_abstract ~at ys c =
List.fold_left
(fun c (y,u) -> Location.mark ~at (Desugared.Abstract (y,u,c)))
c ys
let rec pattern ~toplevel ctx {Location.it=p; at} =
let locate x = Location.mark ~at x in
match p with
| Sugared.Patt_Anonymous ->
ctx, locate Desugared.Patt_Anonymous
| Sugared.Patt_Var x ->
let add = if toplevel then Ctx.add_ml_value ~at else Ctx.add_bound in
let ctx = add x ctx in
ctx, locate (Desugared.Patt_Var x)
| Sugared.Patt_Path pth ->
begin match pth with
| Name.PName x ->
begin match Ctx.find_name pth ctx with
| None ->
error ~at (InvalidPatternVariable x)
| Some (MLConstructor (pth, arity)) ->
check_ml_arity ~at (Name.PName x) 0 arity ;
ctx, locate (Desugared.Patt_MLConstructor (pth, []))
| Some (TTConstructor (pth, arity)) ->
check_tt_arity ~at (Name.PName x) 0 arity ;
ctx, locate (Desugared.Patt_TTConstructor (pth, []))
| Some (Exception (pth, arity)) ->
check_exception_arity ~at (Name.PName x) 0 arity ;
ctx, locate (Desugared.Patt_MLException (pth, None))
| Some ((Operation _ | Bound _ | Value _) as info) ->
error ~at (InvalidPatternName (pth, info))
end
| Name.PModule _ ->
begin match Ctx.get_name ~at pth ctx with
| MLConstructor (c_pth, arity) ->
check_ml_arity ~at pth 0 arity ;
ctx, locate (Desugared.Patt_MLConstructor (c_pth, []))
| TTConstructor (c_pth, arity) ->
check_tt_arity ~at pth 0 arity ;
ctx, locate (Desugared.Patt_TTConstructor (c_pth, []))
| (Value _ | Operation _ | Exception _) as info ->
error ~at (InvalidPatternName (pth, info))
| Bound _ -> assert false
end
end
| Sugared.Patt_MLAscribe (p, t) ->
let ctx, p = pattern ~toplevel ctx p in
let t = mlty ctx [] t in
ctx, locate (Desugared.Patt_MLAscribe (p, t))
| Sugared.Patt_As (p1, p2) ->
let ctx, p1 = pattern ~toplevel ctx p1 in
let ctx, p2 = pattern ~toplevel ctx p2 in
ctx, locate (Desugared.Patt_As (p1, p2))
| Sugared.Patt_Constructor (c, ps) ->
begin match Ctx.get_name ~at c ctx with
| MLConstructor (pth, arity) ->
check_ml_arity ~at c (List.length ps) arity ;
let ctx, ps = patterns ~at ~toplevel ctx ps in
ctx, locate (Desugared.Patt_MLConstructor (pth, ps))
| Exception (exc, arity) ->
check_exception_arity ~at c (List.length ps) arity ;
begin match arity, ps with
| Nullary, [] -> ctx, locate (Desugared.Patt_MLException (exc, None))
| Unary, [p] ->
let ctx, p = pattern ~toplevel ctx p in
ctx, locate (Desugared.Patt_MLException (exc, Some p))
| Nullary, _::_ -> error ~at (ArityMismatch (c, List.length ps, 0))
| Unary, ([] | _::_::_) -> error ~at (ArityMismatch (c, List.length ps, 1))
end
| TTConstructor (pth, arity) ->
check_tt_arity ~at c (List.length ps) arity ;
let ctx, ps = patterns ~at ~toplevel ctx ps in
ctx, locate (Desugared.Patt_TTConstructor (pth, ps))
| (Bound _ | Value _ | Operation _) as info ->
error ~at (InvalidAppliedPatternName (c, info))
end
| Sugared.Patt_GenAtom p ->
let ctx, p = pattern ~toplevel ctx p in
ctx, locate (Desugared.Patt_GenAtom p)
| Sugared.Patt_IsType p ->
let ctx, p = pattern ~toplevel ctx p in
ctx, locate (Desugared.Patt_IsType p)
| Sugared.Patt_IsTerm (p1, p2) ->
let ctx, p1 = pattern ~toplevel ctx p1 in
let ctx, p2 = pattern ~toplevel ctx p2 in
ctx, locate (Desugared.Patt_IsTerm (p1, p2))
| Sugared.Patt_EqType (p1, p2) ->
let ctx, p1 = pattern ~toplevel ctx p1 in
let ctx, p2 = pattern ~toplevel ctx p2 in
ctx, locate (Desugared.Patt_EqType (p1, p2))
| Sugared.Patt_EqTerm (p1, p2, p3) ->
let ctx, p1 = pattern ~toplevel ctx p1 in
let ctx, p2 = pattern ~toplevel ctx p2 in
let ctx, p3 = pattern ~toplevel ctx p3 in
ctx, locate (Desugared.Patt_EqTerm (p1, p2, p3))
| Sugared.Patt_BoundaryIsType ->
ctx, locate (Desugared.Patt_BoundaryIsType)
| Sugared.Patt_BoundaryIsTerm p ->
let ctx, p = pattern ~toplevel ctx p in
ctx, locate (Desugared.Patt_BoundaryIsTerm p)
| Sugared.Patt_BoundaryEqType (p1, p2) ->
let ctx, p1 = pattern ~toplevel ctx p1 in
let ctx, p2 = pattern ~toplevel ctx p2 in
ctx, locate (Desugared.Patt_BoundaryEqType (p1, p2))
| Sugared.Patt_BoundaryEqTerm (p1, p2, p3) ->
let ctx, p1 = pattern ~toplevel ctx p1 in
let ctx, p2 = pattern ~toplevel ctx p2 in
let ctx, p3 = pattern ~toplevel ctx p3 in
ctx, locate (Desugared.Patt_BoundaryEqTerm (p1, p2, p3))
| Sugared.Patt_Abstraction (abstr, p0) ->
let rec fold ctx = function
| [] -> pattern ~toplevel ctx p0
| (xopt, popt) :: abstr ->
let ctx, popt =
match popt with
| None -> ctx, locate Desugared.Patt_Anonymous
| Some p ->
let ctx, p = pattern ~toplevel ctx p in
ctx, p
in
let ctx, xopt =
begin
match xopt with
| Some x ->
let ctx = Ctx.add_bound x ctx in
ctx, Some x
| None -> ctx, None
end
in
let ctx, p = fold ctx abstr in
ctx, locate (Desugared.Patt_Abstraction (xopt, popt, p))
in
fold ctx abstr
| Sugared.Patt_List ps ->
let nil_path, _ = Ctx.get_path_nil ctx
and cons_path, _ = Ctx.get_path_cons ctx in
let rec fold ~at ctx = function
| [] -> ctx, locate (Desugared.Patt_MLConstructor (nil_path, []))
| p :: ps ->
let ctx, p = pattern ~toplevel ctx p in
let ctx, ps = fold ~at:(p.Location.at) ctx ps in
ctx, locate (Desugared.Patt_MLConstructor (cons_path, [p ; ps]))
in
fold ~at ctx ps
| Sugared.Patt_Tuple ps ->
let ctx, ps = patterns ~at ~toplevel ctx ps in
ctx, locate (Desugared.Patt_Tuple ps)
| Sugared.Patt_String s ->
ctx, locate (Desugared.Patt_String s)
and patterns ~at ~toplevel ctx ps =
let rec fold ctx ps_out = function
| [] ->
ctx, List.rev ps_out
| p :: ps ->
let ctx, p_out = pattern ~toplevel ctx p in
fold ctx (p_out :: ps_out) ps
in
fold ctx [] ps
let check_linear_pattern_variable ~at ~forbidden x =
if Name.set_mem x forbidden then
error ~at (NonlinearPattern x)
else
Name.set_add x forbidden
let rec check_linear ?(forbidden=Name.set_empty) {Location.it=p';at} =
match p' with
| Sugared.Patt_Anonymous | Sugared.Patt_Path _ | Sugared.Patt_String _ ->
forbidden
| Sugared.Patt_Var x ->
check_linear_pattern_variable ~at ~forbidden x
| Sugared.Patt_MLAscribe (p, _) ->
check_linear ~forbidden p
| Sugared.Patt_As (p1, p2) ->
let forbidden = check_linear ~forbidden p1 in
check_linear ~forbidden p2
| Sugared.Patt_GenAtom p ->
check_linear ~forbidden p
| Sugared.Patt_IsType p ->
check_linear ~forbidden p
| Sugared.Patt_IsTerm (p1, p2) ->
let forbidden = check_linear ~forbidden p1 in
check_linear ~forbidden p2
| Sugared.Patt_EqType (p1, p2) ->
let forbidden = check_linear ~forbidden p1 in
check_linear ~forbidden p2
| Sugared.Patt_EqTerm (p1, p2, p3) ->
let forbidden = check_linear ~forbidden p1 in
let forbidden = check_linear ~forbidden p2 in
check_linear ~forbidden p3
| Sugared.Patt_BoundaryIsType ->
forbidden
| Sugared.Patt_BoundaryIsTerm p ->
check_linear ~forbidden p
| Sugared.Patt_BoundaryEqType (p1, p2) ->
let forbidden = check_linear ~forbidden p1 in
check_linear ~forbidden p2
| Sugared.Patt_BoundaryEqTerm (p1, p2, p3) ->
let forbidden = check_linear ~forbidden p1 in
let forbidden = check_linear ~forbidden p2 in
check_linear ~forbidden p3
| Sugared.Patt_Abstraction (args, p) ->
let forbidden = check_linear_abstraction ~at ~forbidden args in
check_linear ~forbidden p
| Sugared.Patt_Constructor (_, ps)
| Sugared.Patt_List ps
| Sugared.Patt_Tuple ps ->
check_linear_list ~forbidden ps
and check_linear_list ~forbidden = function
| [] -> forbidden
| p :: ps ->
let forbidden = check_linear ~forbidden p in
check_linear_list ~forbidden ps
and check_linear_abstraction ~at ~forbidden = function
| [] -> forbidden
| (xopt, popt) :: args ->
let forbidden =
match xopt with
| None -> forbidden
| Some x -> check_linear_pattern_variable ~at ~forbidden x
in
let forbidden =
match popt with
| None -> forbidden
| Some p -> check_linear ~forbidden p
in
check_linear_abstraction ~at ~forbidden args
let rec comp ctx {Location.it=c';at} =
let locate x = Location.mark ~at x in
match c' with
| Sugared.Try (c, hcs) ->
let c = comp ctx c
and h = handler ~at ctx hcs in
locate (Desugared.With (h, c))
| Sugared.With (c1, c2) ->
let c1 = comp ctx c1
and c2 = comp ctx c2 in
locate (Desugared.With (c1, c2))
| Sugared.Raise c ->
let c = comp ctx c in
locate (Desugared.Raise c)
| Sugared.Let (lst, c) ->
let ctx, lst = let_clauses ~at ~toplevel:false ctx lst in
let c = comp ctx c in
locate (Desugared.Let (lst, c))
| Sugared.LetRec (lst, c) ->
let ctx, lst = letrec_clauses ~at ~toplevel:false ctx lst in
let c = comp ctx c in
locate (Desugared.LetRec (lst, c))
| Sugared.MLAscribe (c, sch) ->
let c = comp ctx c in
let sch = ml_schema ctx sch in
locate (Desugared.MLAscribe (c, sch))
| Sugared.Lookup c ->
let c = comp ctx c in
locate (Desugared.Lookup c)
| Sugared.Ref c ->
let c = comp ctx c in
locate (Desugared.Ref c)
| Sugared.Update (c1, c2) ->
let c1 = comp ctx c1
and c2 = comp ctx c2 in
locate (Desugared.Update (c1, c2))
| Sugared.Sequence (c1, c2) ->
let c1 = comp ctx c1
and c2 = comp ctx c2 in
locate (Desugared.Sequence (c1, c2))
| Sugared.Fresh (xopt, c) ->
let c = comp ctx c in
locate (Desugared.Fresh (xopt, c))
| Sugared.Meta xopt ->
locate (Desugared.Meta xopt)
| Sugared.AbstractAtom (c1,c2) ->
let c1 = comp ctx c1
and c2 = comp ctx c2 in
locate (Desugared.AbstractAtom (c1,c2))
| Sugared.Match (c, cases) ->
let c = comp ctx c
and cases = List.map (match_case ctx) cases in
locate (Desugared.Match (c, cases))
| Sugared.BoundaryAscribe (c, bdry) ->
let bdry = comp ctx bdry
and c = comp ctx c in
locate (Desugared.BoundaryAscribe (c, bdry))
| Sugared.TypeAscribe (c, t) ->
let t = comp ctx t
and c = comp ctx c in
locate (Desugared.TypeAscribe (c, t))
| Sugared.EqTypeAscribe (t1, t2, c) ->
let t1 = comp ctx t1
and t2 = comp ctx t2
and c = comp ctx c in
locate (Desugared.EqTypeAscribe (t1, t2, c))
| Sugared.EqTermAscribe (e1, e2, t, c) ->
let e1 = comp ctx e1
and e2 = comp ctx e2
and t = comp ctx t
and c = comp ctx c in
locate (Desugared.EqTermAscribe (e1, e2, t, c))
| Sugared.Abstract (xs, c) ->
let rec fold ctx ys = function
| [] ->
let c = comp ctx c in
mk_abstract ~at ys c
| (x, None) :: xs ->
let ctx = Ctx.add_bound x ctx
and ys = (x, None) :: ys in
fold ctx ys xs
| (x, Some t) :: xs ->
let ys = (let t = comp ctx t in (x, Some t) :: ys)
and ctx = Ctx.add_bound x ctx in
fold ctx ys xs
in
fold ctx [] xs
| Sugared.Substitute (e, cs) ->
let e = comp ctx e in
List.fold_left
(fun e c ->
let c = comp ctx c
and at = Location.from_to at c.Location.at in
Location.mark ~at (Desugared.Substitute (e, c)))
e cs
| Sugared.Derive (prems, c) ->
let c, prems = premises ctx prems (fun ctx -> comp ctx c) in
locate (Desugared.Derive (prems, c))
| Sugared.RuleApply (c, cs) ->
let c = comp ctx c in
let cs = List.map (comp ctx) cs in
locate (Desugared.RuleApply (c, cs))
| Sugared.Spine (e, cs) ->
spine ~at ctx e cs
| Sugared.Name x ->
begin match Ctx.get_name ~at x ctx with
| Bound i -> locate (Desugared.Bound i)
| Value pth -> locate (Desugared.Value pth)
| TTConstructor (pth, arity) ->
if arity = 0 then
locate (Desugared.TTConstructor (pth, []))
else
locate (Desugared.AsDerivation pth)
| MLConstructor (pth, arity) ->
check_ml_arity ~at x 0 arity ;
locate (Desugared.MLConstructor (pth, []))
| Operation (pth, arity) ->
check_ml_arity ~at x 0 arity ;
locate (Desugared.Operation (pth, []))
| Exception (pth, arity) ->
check_exception_arity ~at x 0 arity ;
locate (Desugared.MLException (pth, None))
end
| Sugared.Function (ps, c) ->
let rec fold ctx = function
| [] -> comp ctx c
| p :: ps ->
let ctx, p = pattern ~toplevel:false ctx p in
let c = fold ctx ps in
locate (Desugared.(Function (p, c)))
in
fold ctx ps
| Sugared.Handler hcs ->
handler ~at ctx hcs
| Sugared.List cs ->
let nil_path, _ = Ctx.get_path_nil ctx
and cons_path, _ = Ctx.get_path_cons ctx in
let rec fold ~at = function
| [] -> locate (Desugared.MLConstructor (nil_path, []))
| c :: cs ->
let c = comp ctx c in
let cs = fold ~at:(c.Location.at) cs in
locate (Desugared.MLConstructor (cons_path, [c ; cs]))
in
fold ~at cs
| Sugared.Tuple cs ->
let lst = List.map (comp ctx) cs in
locate (Desugared.Tuple lst)
| Sugared.String s ->
locate (Desugared.String s)
| Sugared.Congruence (c1, c2, cs) ->
let c1 = comp ctx c1
and c2 = comp ctx c2
and cs = List.map (comp ctx) cs in
locate (Desugared.Congruence (c1, c2, cs))
| Sugared.Rewrite (c, cs) ->
let c = comp ctx c
and cs = List.map (comp ctx) cs in
locate (Desugared.Rewrite (c, cs))
| Sugared.Context c ->
let c = comp ctx c in
locate (Desugared.Context c)
| Sugared.Occurs (c1,c2) ->
let c1 = comp ctx c1
and c2 = comp ctx c2 in
locate (Desugared.Occurs (c1,c2))
| Sugared.Convert (c1,c2) ->
let c1 = comp ctx c1
and c2 = comp ctx c2 in
locate (Desugared.Convert (c1,c2))
| Sugared.Natural c ->
let c = comp ctx c in
locate (Desugared.Natural c)
| Sugared.MLBoundaryIsType ->
locate Desugared.(MLBoundary BoundaryIsType)
| Sugared.MLBoundaryIsTerm c ->
let c = comp ctx c in
locate Desugared.(MLBoundary (BoundaryIsTerm c))
| Sugared.MLBoundaryEqType (c1, c2) ->
let c1 = comp ctx c1
and c2 = comp ctx c2 in
locate Desugared.(MLBoundary (BoundaryEqType (c1, c2)))
| Sugared.MLBoundaryEqTerm (c1, c2, c3) ->
let c1 = comp ctx c1
and c2 = comp ctx c2
and c3 = comp ctx c3 in
locate Desugared.(MLBoundary (BoundaryEqTerm (c1, c2, c3)))
and let_clauses ~at ~toplevel ctx lst =
let locate x = Location.mark ~at x in
let add = if toplevel then Ctx.add_ml_value ~at else Ctx.add_bound in
let rec fold ctx' lst' = function
| [] ->
let lst' = List.rev lst' in
ctx', lst'
| Sugared.Let_clause_ML (xys_opt, sch, c) :: clauses ->
let ys = (match xys_opt with None -> [] | Some (_, ys) -> ys) in
let c = let_clause ~at ctx ys c in
let sch = let_annotation ctx sch in
let x, ctx' =
begin match xys_opt with
| None -> locate Desugared.Patt_Anonymous, ctx'
| Some (x, _) -> locate (Desugared.Patt_Var x), add x ctx'
end
in
let lst' = Desugared.Let_clause (x, sch, c) :: lst' in
fold ctx' lst' clauses
| Sugared.Let_clause_tt (xopt, t, c) :: clauses ->
let c = let_clause_tt ctx c t in
let sch = Desugared.Let_annot_none in
let x, ctx' =
begin match xopt with
| None -> locate Desugared.Patt_Anonymous, ctx'
| Some x -> locate (Desugared.Patt_Var x), add x ctx'
end
in
let lst' = Desugared.Let_clause (x, sch, c) :: lst' in
fold ctx' lst' clauses
| Sugared.Let_clause_patt (pt, sch, c) :: clauses ->
let c = comp ctx c in
let sch = let_annotation ctx sch in
let ctx', pt = pattern ~toplevel ctx' pt in
let lst' = Desugared.Let_clause (pt, sch, c) :: lst' in
fold ctx' lst' clauses
in
let rec check_unique forbidden = function
| [] -> ()
| Sugared.Let_clause_ML (Some (x, _), _, _) :: lst
| Sugared.Let_clause_tt (Some x, _, _) :: lst ->
if Name.set_mem x forbidden
then error ~at (ParallelShadowing x)
else check_unique (Name.set_add x forbidden) lst
| Sugared.Let_clause_ML (None, _, _) :: lst
| Sugared.Let_clause_tt (None, _, _) :: lst ->
check_unique forbidden lst
| Sugared.Let_clause_patt (pt, _, _) :: lst ->
let forbidden = check_linear ~forbidden pt in
check_unique forbidden lst
in
check_unique Name.set_empty lst ;
fold ctx [] lst
and letrec_clauses ~at ~toplevel ctx lst =
let add = if toplevel then Ctx.add_ml_value ~at else Ctx.add_bound in
let ctx =
List.fold_left (fun ctx (f, _, _, _, _) -> add f ctx) ctx lst
in
let rec fold lst' = function
| [] ->
let lst' = List.rev lst' in
ctx, lst'
| (f, p, ps, sch, c) :: xcs ->
if List.exists (fun (g, _, _, _, _) -> Name.equal f g) xcs
then
error ~at (ParallelShadowing f)
else
let p, c = letrec_clause ~at ctx p ps c in
let sch = let_annotation ctx sch in
let lst' = Desugared.Letrec_clause (f, p, sch, c) :: lst' in
fold lst' xcs
in
fold [] lst
and let_clause ~at ctx ps c =
let rec fold ctx = function
| [] ->
comp ctx c
| p :: ps ->
let ctx, p = pattern ~toplevel:false ctx p in
let c = fold ctx ps in
in
fold ctx ps
and let_clause_tt ctx c t =
let c = comp ctx c
and t = comp ctx t in
Location.mark ~at:c.Location.at (Desugared.BoundaryAscribe (c, t))
and letrec_clause ~at ctx p ps c =
let ctx, p = pattern ~toplevel:false ctx p in
let c = let_clause ~at ctx ps c in
p, c
and ml_schema ctx {Location.it=Sugared.ML_Forall (params, t); at} =
Location.mark ~at (Desugared.ML_Forall (params, mlty ctx params t))
and let_annotation ctx = function
| Sugared.Let_annot_none ->
Desugared.Let_annot_none
| Sugared.Let_annot_schema sch ->
let sch = ml_schema ctx sch in
Desugared.Let_annot_schema sch
and spine ~at ctx ({Location.it=c'; at=c_at} as c) cs =
Auxiliary function which splits a list into two parts with k
elements in the first part .
elements in the first part. *)
let split_at constr arity lst =
let rec split acc m lst =
if m = 0 then
List.rev acc,
(match lst with [] -> None | _::_ -> Some lst)
else
match lst with
| [] -> error ~at (ArityMismatch (constr, List.length acc, arity))
| x :: lst -> split (x :: acc) (m - 1) lst
in
split [] arity lst
in
let head, cs =
match c' with
| Sugared.Name x ->
begin match Ctx.get_name ~at x ctx with
| Bound i ->
Location.mark ~at:c_at (Desugared.Bound i), Some cs
| Value pth ->
Location.mark ~at:c_at (Desugared.Value pth), Some cs
| TTConstructor (pth, arity) ->
check_tt_arity ~at x (List.length cs) arity ;
let cs', cs = split_at x arity cs in
tt_constructor ~at ctx pth cs', cs
| MLConstructor (pth, arity) ->
check_ml_arity ~at x (List.length cs) arity ;
let cs', cs = split_at x arity cs in
ml_constructor ~at ctx pth cs', cs
| Operation (pth, arity) ->
let cs', cs = split_at x arity cs in
operation ~at ctx pth cs', cs
| Exception (pth, arity) ->
begin match arity, cs with
| Nullary, [] -> ml_exception ~at ctx pth None, None
| Unary, [c] -> ml_exception ~at ctx pth (Some c), None
| Nullary, _::_ -> error ~at (ArityMismatch (x, List.length cs, 0))
| Unary, ([] | _::_::_) -> error ~at (ArityMismatch (x, List.length cs, 1))
end
end
| _ -> comp ctx c, Some cs
in
match cs with
| None -> head
| Some cs ->
let cs = List.map (comp ctx) cs in
Location.mark ~at (Desugared.Spine (head, cs))
handler cases .
and handler ~at ctx hcs =
let rec fold val_cases op_cases exc_cases = function
| [] ->
List.rev val_cases,
List.map (fun (op, cs) -> (op, List.rev cs)) op_cases,
List.rev exc_cases
| Sugared.CaseVal c :: hcs ->
let case = match_case ctx c in
fold (case::val_cases) op_cases exc_cases hcs
| Sugared.CaseOp (op, case) :: hcs ->
let (pth, case) = match_op_case ~at ctx op case in
let my_cases = match List.assoc_opt pth op_cases with Some lst -> lst | None -> [] in
let my_cases = case::my_cases in
fold val_cases ((pth, my_cases) :: op_cases) exc_cases hcs
| Sugared.CaseExc c :: hcs ->
let case = match_case ctx c in
fold val_cases op_cases (case :: exc_cases) hcs
in
let handler_val, handler_ops, handler_exc = fold [] [] [] hcs in
Location.mark ~at Desugared.(Handler {handler_val ; handler_ops; handler_exc })
a match case
and match_case ctx (p, g, c) =
ignore (check_linear p) ;
let ctx, p = pattern ~toplevel:false ctx p in
let g = when_guard ctx g
and c = comp ctx c in
(p, g, c)
and when_guard ctx = function
| None -> None
| Some c ->
let c = comp ctx c in
Some c
and match_op_case ~at ctx op (ps, pt, c) =
match Ctx.get_name ~at op ctx with
| (Bound _ | Value _ | Exception _ | TTConstructor _ | MLConstructor _) as info ->
error ~at (OperationExpected (op, info))
| Operation (pth, arity) ->
check_ml_arity ~at op (List.length ps) arity ;
let rec fold ctx qs = function
| [] ->
let qs = List.rev qs in
let ctx, pt =
begin match pt with
| None -> ctx, None
| Some p ->
ignore (check_linear p) ;
let ctx, p = pattern ~toplevel:false ctx p in
ctx, Some p
end
in
let c = comp ctx c in
pth, (qs, pt, c)
| p :: ps ->
let ctx, q = pattern ~toplevel:false ctx p in
fold ctx (q :: qs) ps
in
fold ctx [] ps
and ml_constructor ~at ctx x cs =
let cs = List.map (comp ctx) cs in
Location.mark ~at (Desugared.MLConstructor (x, cs))
and tt_constructor ~at ctx pth cs =
let cs = List.map (comp ctx) cs in
Location.mark ~at (Desugared.TTConstructor (pth, cs))
and operation ~at ctx x cs =
let cs = List.map (comp ctx) cs in
Location.mark ~at (Desugared.Operation (x, cs))
and ml_exception ~at ctx x copt =
let c = match copt with None -> None | Some c -> Some (comp ctx c) in
Location.mark ~at (Desugared.MLException (x, c))
and local_context :
'a . Ctx.t -> Sugared.local_context -> (Ctx.t -> 'a) -> 'a * Desugared.local_context
= fun ctx xcs m ->
let rec fold ctx xcs_out = function
| [] ->
let xcs_out = List.rev xcs_out in
let v = m ctx in
v, xcs_out
| (x, c) :: xcs ->
let c = comp ctx c in
let ctx = Ctx.add_bound x ctx in
fold ctx ((x,c) :: xcs_out) xcs
in
fold ctx [] xcs
and premise ctx {Location.it=prem;at} =
let locate x = Location.mark ~at x in
let Sugared.Premise (mvar, local_ctx, c) = prem in
let bdry, local_ctx = local_context ctx local_ctx (fun ctx -> comp ctx c) in
let mvar = (match mvar with Some mvar -> mvar | None -> Name.anonymous ()) in
let ctx = Ctx.add_bound mvar ctx in
ctx, locate (Desugared.Premise (mvar, local_ctx, bdry))
and premises :
'a . Ctx.t -> Sugared.premise list -> (Ctx.t -> 'a) -> 'a * Desugared.premise list
= fun ctx prems m ->
let rec fold ctx prems_out = function
| [] ->
let v = m ctx in
let prems_out = List.rev prems_out in
v, prems_out
| prem :: prems ->
let ctx, prem = premise ctx prem in
fold ctx (prem :: prems_out) prems
in
fold ctx [] prems
let decl_operation ~at ctx args res =
let args = List.map (mlty ctx []) args
and res = mlty ctx [] res in
args, res
let mlty_constructor ~at ctx params (c, args) =
(c, List.map (mlty ctx params) args)
let mlty_def ~at ctx params = function
| Sugared.ML_Alias ty ->
let ty = mlty ctx params ty in
Desugared.ML_Alias ty
| Sugared.ML_Sum lst ->
let lst = List.map (mlty_constructor ~at ctx params) lst in
Desugared.ML_Sum lst
let mlty_info params = function
| Sugared.ML_Alias _ -> (ml_arity params), None
| Sugared.ML_Sum lst ->
let cs = List.map (fun (c, args) -> (c, ml_arity args)) lst in
(ml_arity params),
Some cs
let mlty_defs ~at ctx defs =
let rec fold defs_out ctx = function
| [] -> ctx, List.rev defs_out
| (t, (params, def)) :: defs_in ->
let def_out = mlty_def ~at ctx params def in
let t_pth, ctx = Ctx.add_ml_type ~at t (mlty_info params def) ctx in
fold ((t_pth, (params, def_out)) :: defs_out) ctx defs_in
in
fold [] ctx defs
let mlty_rec_defs ~at ctx defs =
let defs_out, ctx =
List.fold_left
(fun (defs_out, ctx) (t, (params, def)) ->
let t_pth, ctx = Ctx.add_ml_type ~at t (mlty_info params def) ctx in
((t_pth, (params, def)) :: defs_out, ctx))
([], ctx) defs
in
let defs_out = List.rev defs_out in
let check_shadow = function
| [] -> ()
| (t, _) :: defs ->
if List.exists (fun (t', _) -> Name.equal t t') defs then
error ~at (ParallelShadowing t)
in
check_shadow defs ;
let defs_out =
List.map (fun (t, (params, def)) -> (t, (params, mlty_def ~at ctx params def))) defs_out in
ctx, defs_out
let rec toplevel' ctx {Location.it=cmd; at} =
let locate1 cmd = [Location.mark ~at cmd] in
match cmd with
| Sugared.Rule (rname, prems, c) ->
let arity = tt_arity prems in
let bdry, prems =
premises
ctx prems
(fun ctx -> comp ctx c)
in
let pth, ctx = Ctx.add_tt_constructor ~at rname arity ctx in
(ctx, locate1 (Desugared.Rule (pth, prems, bdry)))
| Sugared.DeclOperation (op, (args, res)) ->
let args, res = decl_operation ~at ctx args res in
let pth, ctx = Ctx.add_operation ~at op (ml_arity args) ctx in
(ctx, locate1 (Desugared.DeclOperation (pth, (args, res))))
| Sugared.DeclException (exc, tyopt) ->
let arity, tyopt =
match tyopt with
| None -> Nullary, None
| Some ty -> Unary,Some (mlty ctx [] ty)
in
let pth, ctx = Ctx.add_exception ~at exc (ml_exception_arity tyopt) ctx in
(ctx, locate1 (Desugared.DeclException (pth, tyopt)))
| Sugared.DefMLTypeAbstract (t, params) ->
let t_pth, ctx = Ctx.add_ml_type ~at t (List.length params, None) ctx in
(ctx, locate1 (Desugared.DefMLTypeAbstract (t_pth, params)))
| Sugared.DefMLType defs ->
let ctx, defs = mlty_defs ~at ctx defs in
(ctx, locate1 (Desugared.DefMLType defs))
| Sugared.DefMLTypeRec defs ->
let ctx, defs = mlty_rec_defs ~at ctx defs in
(ctx, locate1 (Desugared.DefMLTypeRec defs))
| Sugared.DeclExternal (x, sch, s) ->
let sch = ml_schema ctx sch in
let ctx = Ctx.add_ml_value ~at x ctx in
(ctx, locate1 (Desugared.DeclExternal (x, sch, s)))
| Sugared.TopLet lst ->
let ctx, lst = let_clauses ~at ~toplevel:true ctx lst in
(ctx, locate1 (Desugared.TopLet lst))
| Sugared.TopLetRec lst ->
let ctx, lst = letrec_clauses ~at ~toplevel:true ctx lst in
(ctx, locate1 (Desugared.TopLetRec lst))
| Sugared.TopWith lst ->
let lst = List.map (fun (op, case) -> match_op_case ~at ctx op case) lst in
(ctx, locate1 (Desugared.TopWith lst))
| Sugared.TopComputation c ->
let c = comp ctx c in
(ctx, locate1 (Desugared.TopComputation c))
| Sugared.Verbosity n ->
(ctx, locate1 (Desugared.Verbosity n))
| Sugared.Require mdl_names ->
(ctx, [])
| Sugared.Include mdl_path ->
let _, mdl = Ctx.get_ml_module ~at mdl_path ctx in
let ctx = Ctx.include_ml_module ~at mdl ctx in
(ctx, [])
| Sugared.Open mdl_path ->
let pth, mdl = Ctx.get_ml_module ~at mdl_path ctx in
let ctx = Ctx.open_ml_module ~at mdl ctx in
(ctx, locate1 (Desugared.Open pth))
| Sugared.TopModule (x, cmds) ->
let ctx, cmd = ml_module ~at ctx x cmds in
(ctx, [cmd])
a list of top - level commands in the current context . Return the new context and
the desugared commands . Assume all required modules have been loaded .
the desugared commands. Assume all required modules have been loaded. *)
and toplevels ctx cmds =
let ctx, cmds =
List.fold_left
(fun (ctx,cmds) cmd ->
let ctx, cmds' = toplevel' ctx cmd in
(ctx, cmds' @ cmds))
(ctx, [])
cmds
in
let cmds = List.rev cmds in
ctx, cmds
and ml_module ~at ctx m cmds =
let ctx = Ctx.push_module m ctx in
let ctx, cmds = toplevels ctx cmds in
let ctx, mdl = Ctx.pop_module ctx in
let ctx = Ctx.add_ml_module ~at m mdl ctx in
ctx, Location.mark ~at (Desugared.MLModule (m, cmds))
let rec load_requires ~basedir ~loading ctx cmds =
let require ~at ~loading ctx mdl_name =
match Ctx.find_ml_module (Name.PName mdl_name) ctx with
| Some _ ->
ctx, []
| None ->
if List.exists (Name.equal mdl_name) loading then
error ~at (CircularRequire (List.rev (mdl_name :: loading)))
else
let rec unique xs = function
| [] -> List.rev xs
| y :: ys ->
if List.mem y xs then unique xs ys else unique (y::xs) ys
in
let basename = Name.module_filename mdl_name in
let fns =
unique []
(List.map
(fun dirname -> Filename.concat dirname basename)
(basedir :: (!Config.require_dirs))
)
in
match List.find_opt Sys.file_exists fns with
| None ->
error ~at (RequiredModuleMissing (mdl_name, fns))
| Some fn ->
let loading = mdl_name :: loading in
let cmds = Lexer.read_file ?line_limit:None Parser.file fn in
let ctx, mdls = load_requires ~loading ~basedir ctx cmds in
let ctx, mdl = ml_module ~at ctx mdl_name cmds in
ctx, (mdls @ [mdl])
in
let rec fold ~loading ctx = function
| [] -> ctx, []
| Location.{it=cmd; at} :: cmds ->
begin match cmd with
| Sugared.Require mdl_names ->
let ctx, mdls_required =
List.fold_left
(fun (ctx, mdls) mdl_name ->
let ctx, mdls' = require ~loading ~at ctx mdl_name in
(ctx, mdls @ mdls'))
(ctx, [])
mdl_names
in
let ctx, mdls = fold ~loading ctx cmds in
ctx, mdls_required @ mdls
| Sugared.TopModule (_, cmds') ->
let ctx, mdls' = fold ~loading ctx cmds' in
let ctx, mdls = fold ~loading ctx cmds in
ctx, mdls' @ mdls
| Sugared.(Rule _ | DefMLTypeAbstract _ |
DefMLType _ | DefMLTypeRec _ | DeclOperation _ | DeclException _ | DeclExternal _ |
TopLet _ | TopLetRec _ | TopWith _ | TopComputation _ |
Include _ | Verbosity _ | Open _) ->
fold ~loading ctx cmds
end
in
fold ~loading ctx cmds
commands , after loading the required modules
let commands ~loading ~basedir ctx cmds =
let ctx, mdls = load_requires ~loading:[] ~basedir ctx cmds in
let ctx, cmds = toplevels ctx cmds in
ctx, (mdls @ cmds)
let toplevel ~basedir ctx cmd =
commands ~loading:[] ~basedir ctx [cmd]
let use_file ctx fn =
let cmds = Lexer.read_file ?line_limit:None Parser.file fn in
let basedir = Filename.dirname fn in
commands ~loading:[] ~basedir ctx cmds
and load_ml_module ctx fn =
let basename = Filename.basename fn in
let dirname = Filename.dirname fn in
let mdl_name = Name.mk_name (Filename.remove_extension basename) in
let cmds = Lexer.read_file ?line_limit:None Parser.file fn in
let ctx, mdls = load_requires ~loading:[mdl_name] ~basedir:dirname ctx cmds in
let ctx, cmd = ml_module ~at:Location.unknown ctx mdl_name cmds in
ctx, (mdls @ [cmd])
let initial_context, initial_commands =
try
commands ~loading:[] ~basedir:Filename.current_dir_name Ctx.empty Builtin.initial
with
| Error {Location.it=err;_} ->
Print.error "Error in built-in code:@ %t.@." (print_error err) ;
Stdlib.exit 1
module Builtin =
struct
let bool = fst (Ctx.get_ml_type ~at:Location.unknown Name.Builtin.bool initial_context)
let mlfalse = fst (Ctx.get_ml_constructor Name.Builtin.mlfalse initial_context)
let mltrue = fst (Ctx.get_ml_constructor Name.Builtin.mltrue initial_context)
let list = fst (Ctx.get_ml_type ~at:Location.unknown Name.Builtin.list initial_context)
let nil = fst (Ctx.get_ml_constructor Name.Builtin.nil initial_context)
let cons = fst (Ctx.get_ml_constructor Name.Builtin.cons initial_context)
let option = fst (Ctx.get_ml_type ~at:Location.unknown Name.Builtin.option initial_context)
let none = fst (Ctx.get_ml_constructor Name.Builtin.none initial_context)
let some = fst (Ctx.get_ml_constructor Name.Builtin.some initial_context)
let mlless = fst (Ctx.get_ml_constructor Name.Builtin.mlless initial_context)
let mlequal = fst (Ctx.get_ml_constructor Name.Builtin.mlequal initial_context)
let mlgreater = fst (Ctx.get_ml_constructor Name.Builtin.mlgreater initial_context)
let equal_type = fst (Ctx.get_ml_operation Name.Builtin.equal_type initial_context)
let coerce = fst (Ctx.get_ml_operation Name.Builtin.coerce initial_context)
let eqchk_excs = fst (Ctx.get_ml_exception Name.Builtin.eqchk_excs initial_context)
end
|
8ab6663bc1fb10c37de30a29c2e24a8e43a5cda17dd37d891dbfbd88fb881744 | ocaml-ppx/ppx_import | types_signature_item_ge_408.ml | type signature_item_407 =
| Sig_value of Ident.t * Types.value_description
| Sig_type of Ident.t * Types.type_declaration * Types.rec_status
| Sig_typext of Ident.t * Types.extension_constructor * Types.ext_status
| Sig_module of Ident.t * Types.module_declaration * Types.rec_status
| Sig_modtype of Ident.t * Types.modtype_declaration
| Sig_class of Ident.t * Types.class_declaration * Types.rec_status
| Sig_class_type of Ident.t * Types.class_type_declaration * Types.rec_status
let migrate_signature_item : Types.signature_item -> signature_item_407 =
function
| Sig_value (id, vd, _) -> Sig_value (id, vd)
| Sig_type (id, td, r, _) -> Sig_type (id, td, r)
| Sig_typext (id, ec, es, _) -> Sig_typext (id, ec, es)
| Sig_module (id, _, md, rs, _) -> Sig_module (id, md, rs)
| Sig_modtype (id, td, _) -> Sig_modtype (id, td)
| Sig_class (id, cd, rs, _) -> Sig_class (id, cd, rs)
| Sig_class_type (id, ctd, rs, _) -> Sig_class_type (id, ctd, rs)
| null | https://raw.githubusercontent.com/ocaml-ppx/ppx_import/3373bf551f3016d1b1c58b2b3b463a63328c38a7/src/compat/types_signature_item_ge_408.ml | ocaml | type signature_item_407 =
| Sig_value of Ident.t * Types.value_description
| Sig_type of Ident.t * Types.type_declaration * Types.rec_status
| Sig_typext of Ident.t * Types.extension_constructor * Types.ext_status
| Sig_module of Ident.t * Types.module_declaration * Types.rec_status
| Sig_modtype of Ident.t * Types.modtype_declaration
| Sig_class of Ident.t * Types.class_declaration * Types.rec_status
| Sig_class_type of Ident.t * Types.class_type_declaration * Types.rec_status
let migrate_signature_item : Types.signature_item -> signature_item_407 =
function
| Sig_value (id, vd, _) -> Sig_value (id, vd)
| Sig_type (id, td, r, _) -> Sig_type (id, td, r)
| Sig_typext (id, ec, es, _) -> Sig_typext (id, ec, es)
| Sig_module (id, _, md, rs, _) -> Sig_module (id, md, rs)
| Sig_modtype (id, td, _) -> Sig_modtype (id, td)
| Sig_class (id, cd, rs, _) -> Sig_class (id, cd, rs)
| Sig_class_type (id, ctd, rs, _) -> Sig_class_type (id, ctd, rs)
|
|
3d996f83a04812f1a45cb0db24de719d740a09ad3b2ec12258eaa429cf38f2b3 | mhallin/graphql_ppx | interface.ml | module QueryWithFragments = [%graphql
{|
query {
users {
id
... on AdminUser {
name
}
... on AnonymousUser {
anonymousId
}
}
}
|}]
type user = [
| `User of < id : string >
| `AdminUser of < id : string; name: string >
| `AnonymousUser of < id : string; anonymousId : int >
]
type only_user = [
| `User of < id : string >
]
module QueryWithoutFragments = [%graphql
{|
query {
users {
id
}
}
|}]
let json = {|{
"users": [
{ "__typename": "AdminUser", "id": "1", "name": "bob" },
{ "__typename": "AnonymousUser", "id": "2", "anonymousId": 1},
{ "__typename": "OtherUser", "id": "3"}
]}|}
let user = (
module struct
type t = user
let pp formatter = function
| `User u -> Format.fprintf formatter "`User < id = @[%s@] >" u#id
| `AdminUser u -> Format.fprintf formatter "`AdminUser < id = @[%s@]; name = @[%s@] >" u#id u#name
| `AnonymousUser u -> Format.fprintf formatter "`AnonymousUser < id = @[%s@]; anonymousId = @[%i@] >" u#id u#anonymousId
let equal (a: user) (b: user) =
match a, b with
| (`User u1), (`User u2) -> u1#id = u2#id
| (`AdminUser u1), (`AdminUser u2) -> u1#id = u2#id && u1#name = u2#name
| (`AnonymousUser u1), (`AnonymousUser u2) -> u1#id = u2#id && u1#anonymousId = u2#anonymousId
| _ -> false
end : Alcotest.TESTABLE with type t = user)
let only_user = (
module struct
type t = only_user
let pp formatter = function
| `User u -> Format.fprintf formatter "`User < id = @[%s@] >" u#id
let equal (a: only_user) (b: only_user) =
match a, b with
| (`User u1), (`User u2) -> u1#id = u2#id
end : Alcotest.TESTABLE with type t = only_user)
let decode_with_fragments () =
Alcotest.(check (array user)) "query result equality"
(QueryWithFragments.parse (Yojson.Basic.from_string json))#users
[|
`AdminUser (object method id = "1" method name = "bob" end);
`AnonymousUser (object method id = "2" method anonymousId = 1 end);
`User(object method id = "3" end);
|]
let decode_without_fragments () =
Alcotest.(check (array only_user)) "query result equality"
(QueryWithoutFragments.parse (Yojson.Basic.from_string json))#users
[|
`User(object method id = "1" end);
`User(object method id = "2" end);
`User(object method id = "3" end);
|]
let tests = [
"Decodes the interface with fragments", `Quick, decode_with_fragments;
"Decodes the interface without fragments", `Quick, decode_without_fragments;
]
| null | https://raw.githubusercontent.com/mhallin/graphql_ppx/5796b3759bdf0d29112f48e43a2f0623f7466e8a/tests_native/interface.ml | ocaml | module QueryWithFragments = [%graphql
{|
query {
users {
id
... on AdminUser {
name
}
... on AnonymousUser {
anonymousId
}
}
}
|}]
type user = [
| `User of < id : string >
| `AdminUser of < id : string; name: string >
| `AnonymousUser of < id : string; anonymousId : int >
]
type only_user = [
| `User of < id : string >
]
module QueryWithoutFragments = [%graphql
{|
query {
users {
id
}
}
|}]
let json = {|{
"users": [
{ "__typename": "AdminUser", "id": "1", "name": "bob" },
{ "__typename": "AnonymousUser", "id": "2", "anonymousId": 1},
{ "__typename": "OtherUser", "id": "3"}
]}|}
let user = (
module struct
type t = user
let pp formatter = function
| `User u -> Format.fprintf formatter "`User < id = @[%s@] >" u#id
| `AdminUser u -> Format.fprintf formatter "`AdminUser < id = @[%s@]; name = @[%s@] >" u#id u#name
| `AnonymousUser u -> Format.fprintf formatter "`AnonymousUser < id = @[%s@]; anonymousId = @[%i@] >" u#id u#anonymousId
let equal (a: user) (b: user) =
match a, b with
| (`User u1), (`User u2) -> u1#id = u2#id
| (`AdminUser u1), (`AdminUser u2) -> u1#id = u2#id && u1#name = u2#name
| (`AnonymousUser u1), (`AnonymousUser u2) -> u1#id = u2#id && u1#anonymousId = u2#anonymousId
| _ -> false
end : Alcotest.TESTABLE with type t = user)
let only_user = (
module struct
type t = only_user
let pp formatter = function
| `User u -> Format.fprintf formatter "`User < id = @[%s@] >" u#id
let equal (a: only_user) (b: only_user) =
match a, b with
| (`User u1), (`User u2) -> u1#id = u2#id
end : Alcotest.TESTABLE with type t = only_user)
let decode_with_fragments () =
Alcotest.(check (array user)) "query result equality"
(QueryWithFragments.parse (Yojson.Basic.from_string json))#users
[|
`AdminUser (object method id = "1" method name = "bob" end);
`AnonymousUser (object method id = "2" method anonymousId = 1 end);
`User(object method id = "3" end);
|]
let decode_without_fragments () =
Alcotest.(check (array only_user)) "query result equality"
(QueryWithoutFragments.parse (Yojson.Basic.from_string json))#users
[|
`User(object method id = "1" end);
`User(object method id = "2" end);
`User(object method id = "3" end);
|]
let tests = [
"Decodes the interface with fragments", `Quick, decode_with_fragments;
"Decodes the interface without fragments", `Quick, decode_without_fragments;
]
|
|
1ca6301abdaad7494ab11e37188b5ec39773d6de963baab45bb8e353f534cdf1 | spurious/sagittarius-scheme-mirror | %3a141.scm | (import (rnrs)
(srfi :141)
(srfi :27)
(srfi :64))
(define-syntax assert-eqv (identifier-syntax test-eqv))
(define-syntax assert-<
(syntax-rules ()
((_ a b) (test-assert (< a b)))))
(define-syntax value-assert
(syntax-rules ()
((_ pred type value)
(test-assert type (pred value)))))
(define-syntax define-test
(syntax-rules ()
((_ name proc)
(guard (e (else (print e) (test-assert name #f))) (proc)))))
(test-begin "SRFI-141: Integer division")
Copyright ( c ) 2010 - -2011
;;; 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.
;;;
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ` ` AS IS '' AND
;;; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
;;; OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
;;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
;;; OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
;;; SUCH DAMAGE.
;;;; Tests of integer division operators
;;(declare (usual-integrations))
(define (check-division n d correct-q q r)
(let ((correct-r (- n (* d correct-q))))
(assert-eqv q correct-q)
(assert-eqv r correct-r)))
(define division-test-iterations #x1000)
;; Such a huge bound as this tests bignum arithmetic, not just fixnum
;; arithmetic.
(define division-test-bound #x100000000000000000000000000000000)
(define (random-sign a b)
((if (zero? (random-integer 2)) - +) a b))
(define (randomly-generate-operands n+ d+ receiver)
(do ((i 0 (+ i 1))) ((>= i division-test-iterations))
(let ((n (n+ 0 (random-integer division-test-bound)))
(d (d+ 0 (+ 1 (random-integer (- division-test-bound 1))))))
(receiver n d))))
(define (randomly-generate-divisors d+ receiver)
(do ((i 0 (+ i 1))) ((>= i division-test-iterations))
(let ((d (d+ 0 (+ 1 (random-integer (- division-test-bound 1))))))
(receiver d))))
(define (randomly-test-division n+ d+ / quotient remainder divider)
(randomly-generate-operands n+ d+
(lambda (n d)
(let ((correct-q (divider n d)))
(check-division n d correct-q (quotient n d) (remainder n d))
(receive (q r) (/ n d)
(check-division n d correct-q q r))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:CEILING+/+
(lambda ()
(randomly-test-division + + ceiling/ ceiling-quotient ceiling-remainder
(lambda (n d) (ceiling (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:CEILING-/+
(lambda ()
(randomly-test-division - + ceiling/ ceiling-quotient ceiling-remainder
(lambda (n d) (ceiling (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:CEILING+/-
(lambda ()
(randomly-test-division + - ceiling/ ceiling-quotient ceiling-remainder
(lambda (n d) (ceiling (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:CEILING-/-
(lambda ()
(randomly-test-division - - ceiling/ ceiling-quotient ceiling-remainder
(lambda (n d) (ceiling (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:EUCLIDEAN+/+
(lambda ()
(randomly-test-division
+ + euclidean/ euclidean-quotient euclidean-remainder
(lambda (n d) ((if (< d 0) ceiling floor) (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:EUCLIDEAN-/+
(lambda ()
(randomly-test-division
- + euclidean/ euclidean-quotient euclidean-remainder
(lambda (n d) ((if (< d 0) ceiling floor) (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:EUCLIDEAN+/-
(lambda ()
(randomly-test-division
+ - euclidean/ euclidean-quotient euclidean-remainder
(lambda (n d) ((if (< d 0) ceiling floor) (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:EUCLIDEAN-/-
(lambda ()
(randomly-test-division
- - euclidean/ euclidean-quotient euclidean-remainder
(lambda (n d) ((if (< d 0) ceiling floor) (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:FLOOR+/+
(lambda ()
(randomly-test-division + + floor/ floor-quotient floor-remainder
(lambda (n d) (floor (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:FLOOR-/+
(lambda ()
(randomly-test-division - + floor/ floor-quotient floor-remainder
(lambda (n d) (floor (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:FLOOR+/-
(lambda ()
(randomly-test-division + - floor/ floor-quotient floor-remainder
(lambda (n d) (floor (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:FLOOR-/-
(lambda ()
(randomly-test-division - - floor/ floor-quotient floor-remainder
(lambda (n d) (floor (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:ROUND+/+
(lambda ()
(randomly-test-division + + round/ round-quotient round-remainder
(lambda (n d) (round (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:ROUND-/+
(lambda ()
(randomly-test-division - + round/ round-quotient round-remainder
(lambda (n d) (round (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:ROUND+/-
(lambda ()
(randomly-test-division + - round/ round-quotient round-remainder
(lambda (n d) (round (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:ROUND-/-
(lambda ()
(randomly-test-division - - round/ round-quotient round-remainder
(lambda (n d) (round (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:TRUNCATE+/+
(lambda ()
(randomly-test-division + + truncate/ truncate-quotient truncate-remainder
(lambda (n d) (truncate (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:TRUNCATE-/+
(lambda ()
(randomly-test-division - + truncate/ truncate-quotient truncate-remainder
(lambda (n d) (truncate (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:TRUNCATE+/-
(lambda ()
(randomly-test-division + - truncate/ truncate-quotient truncate-remainder
(lambda (n d) (truncate (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:TRUNCATE-/-
(lambda ()
(randomly-test-division - - truncate/ truncate-quotient truncate-remainder
(lambda (n d) (truncate (/ n d))))))
(define (randomly-test-properties / assert-property)
(randomly-generate-operands random-sign random-sign
(lambda (n d) (receive (q r) (/ n d) (assert-property n d q r)))))
(define (assert-n=dq+r n d q r)
(assert-eqv (+ (* d q) r) n))
(define-test 'N=DQ+R-TESTS:EUCLIDEAN
(lambda () (randomly-test-properties euclidean/ assert-n=dq+r)))
(define-test 'N=DQ+R-TESTS:FLOOR
(lambda () (randomly-test-properties floor/ assert-n=dq+r)))
(define-test 'N=DQ+R-TESTS:ROUND
(lambda () (randomly-test-properties round/ assert-n=dq+r)))
(define-test 'N=DQ+R-TESTS:TRUNCATE
(lambda () (randomly-test-properties truncate/ assert-n=dq+r)))
(define (assert-r<d n d q r)
n q ;ignore
(assert-< (abs r) (abs d)))
(define (assert-r<d* n d q r)
n q ;ignore
(assert-< r (abs d)))
(define-test 'R<D-TESTS:CEILING
(lambda () (randomly-test-properties ceiling/ assert-r<d)))
(define-test 'R<D-TESTS:EUCLIDEAN
(lambda () (randomly-test-properties euclidean/ assert-r<d)))
(define-test 'R<D-TESTS:EUCLIDEAN*
(lambda () (randomly-test-properties euclidean/ assert-r<d*)))
(define-test 'R<D-TESTS:FLOOR
(lambda () (randomly-test-properties floor/ assert-r<d)))
(define-test 'R<D-TESTS:ROUND
(lambda () (randomly-test-properties round/ assert-r<d)))
(define-test 'R<D-TESTS:TRUNCATE
(lambda () (randomly-test-properties truncate/ assert-r<d)))
(define (assert-integral-quotient n d q r)
n d r ;ignore
(value-assert integer? "integer" q))
(define-test 'INTEGRAL-QUOTIENT-TESTS:CEILING
(lambda () (randomly-test-properties ceiling/ assert-integral-quotient)))
(define-test 'INTEGRAL-QUOTIENT-TESTS:EUCLIDEAN
(lambda () (randomly-test-properties euclidean/ assert-integral-quotient)))
(define-test 'INTEGRAL-QUOTIENT-TESTS:FLOOR
(lambda () (randomly-test-properties floor/ assert-integral-quotient)))
(define-test 'INTEGRAL-QUOTIENT-TESTS:ROUND
(lambda () (randomly-test-properties round/ assert-integral-quotient)))
(define-test 'INTEGRAL-QUOTIENT-TESTS:TRUNCATE
(lambda () (randomly-test-properties truncate/ assert-integral-quotient)))
(define (test-trivial-quotient quotient)
(assert-eqv (quotient +1 +1) +1)
(assert-eqv (quotient -1 +1) -1)
(assert-eqv (quotient +1 -1) -1)
(assert-eqv (quotient -1 -1) +1)
(assert-eqv (quotient 0 +1) 0)
(assert-eqv (quotient 0 -1) 0))
(define (test-trivial/ /)
(test-trivial-quotient (lambda (n d) (receive (q r) (/ n d) r q))))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:CEILING-QUOTIENT
(lambda () (test-trivial-quotient ceiling-quotient)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:CEILING/
(lambda () (test-trivial/ ceiling/)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:EUCLIDEAN-QUOTIENT
(lambda () (test-trivial-quotient euclidean-quotient)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:EUCLIDEAN/
(lambda () (test-trivial/ euclidean/)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:FLOOR-QUOTIENT
(lambda () (test-trivial-quotient floor-quotient)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:FLOOR/
(lambda () (test-trivial/ floor/)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:ROUND-QUOTIENT
(lambda () (test-trivial-quotient round-quotient)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:ROUND/
(lambda () (test-trivial/ round/)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:TRUNCATE-QUOTIENT
(lambda () (test-trivial-quotient truncate-quotient)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:TRUNCATE/
(lambda () (test-trivial/ truncate/)))
(define-test 'TRIVIAL-DIVIDEND/RANDOM-DIVISOR-TESTS:CEILING
(lambda ()
(randomly-generate-divisors random-sign
(lambda (d)
(assert-eqv (ceiling-quotient 0 d) 0)
(if (< 1 (abs d))
(begin
(assert-eqv (ceiling-quotient +1 d) (if (negative? d) 0 +1))
(assert-eqv (ceiling-quotient -1 d)
(if (negative? d) +1 0))))))))
(define-test 'TRIVIAL-DIVIDEND/RANDOM-DIVISOR-TESTS:EUCLIDEAN
(lambda ()
(randomly-generate-divisors random-sign
(lambda (d)
(assert-eqv (euclidean-quotient 0 d) 0)
(if (< 1 (abs d))
(begin
(assert-eqv (euclidean-quotient +1 d) 0)
(assert-eqv (euclidean-quotient -1 d)
(if (negative? d) +1 -1))))))))
(define-test 'TRIVIAL-DIVIDEND/RANDOM-DIVISOR-TESTS:FLOOR
(lambda ()
(randomly-generate-divisors random-sign
(lambda (d)
(assert-eqv (floor-quotient 0 d) 0)
(if (< 1 (abs d))
(begin
(assert-eqv (floor-quotient -1 d) (if (negative? d) 0 -1))
(assert-eqv (floor-quotient +1 d) (if (negative? d) -1 0))))))))
(define-test 'TRIVIAL-DIVIDEND/RANDOM-DIVISOR-TESTS:ROUND
(lambda ()
(randomly-generate-divisors random-sign
(lambda (d)
(assert-eqv (round-quotient -1 d) 0)
(assert-eqv (round-quotient 0 d) 0)
(assert-eqv (round-quotient +1 d) 0)))))
(define-test 'TRIVIAL-DIVIDEND/RANDOM-DIVISOR-TESTS:TRUNCATE
(lambda ()
(randomly-generate-divisors random-sign
(lambda (d)
(assert-eqv (truncate-quotient -1 d) 0)
(assert-eqv (truncate-quotient 0 d) 0)
(assert-eqv (truncate-quotient +1 d) 0)))))
(test-end)
| null | https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/test/tests/srfi/%253a141.scm | scheme | 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.
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
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.
Tests of integer division operators
(declare (usual-integrations))
Such a huge bound as this tests bignum arithmetic, not just fixnum
arithmetic.
ignore
ignore
ignore | (import (rnrs)
(srfi :141)
(srfi :27)
(srfi :64))
(define-syntax assert-eqv (identifier-syntax test-eqv))
(define-syntax assert-<
(syntax-rules ()
((_ a b) (test-assert (< a b)))))
(define-syntax value-assert
(syntax-rules ()
((_ pred type value)
(test-assert type (pred value)))))
(define-syntax define-test
(syntax-rules ()
((_ name proc)
(guard (e (else (print e) (test-assert name #f))) (proc)))))
(test-begin "SRFI-141: Integer division")
Copyright ( c ) 2010 - -2011
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ` ` AS IS '' AND
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
(define (check-division n d correct-q q r)
(let ((correct-r (- n (* d correct-q))))
(assert-eqv q correct-q)
(assert-eqv r correct-r)))
(define division-test-iterations #x1000)
(define division-test-bound #x100000000000000000000000000000000)
(define (random-sign a b)
((if (zero? (random-integer 2)) - +) a b))
(define (randomly-generate-operands n+ d+ receiver)
(do ((i 0 (+ i 1))) ((>= i division-test-iterations))
(let ((n (n+ 0 (random-integer division-test-bound)))
(d (d+ 0 (+ 1 (random-integer (- division-test-bound 1))))))
(receiver n d))))
(define (randomly-generate-divisors d+ receiver)
(do ((i 0 (+ i 1))) ((>= i division-test-iterations))
(let ((d (d+ 0 (+ 1 (random-integer (- division-test-bound 1))))))
(receiver d))))
(define (randomly-test-division n+ d+ / quotient remainder divider)
(randomly-generate-operands n+ d+
(lambda (n d)
(let ((correct-q (divider n d)))
(check-division n d correct-q (quotient n d) (remainder n d))
(receive (q r) (/ n d)
(check-division n d correct-q q r))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:CEILING+/+
(lambda ()
(randomly-test-division + + ceiling/ ceiling-quotient ceiling-remainder
(lambda (n d) (ceiling (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:CEILING-/+
(lambda ()
(randomly-test-division - + ceiling/ ceiling-quotient ceiling-remainder
(lambda (n d) (ceiling (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:CEILING+/-
(lambda ()
(randomly-test-division + - ceiling/ ceiling-quotient ceiling-remainder
(lambda (n d) (ceiling (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:CEILING-/-
(lambda ()
(randomly-test-division - - ceiling/ ceiling-quotient ceiling-remainder
(lambda (n d) (ceiling (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:EUCLIDEAN+/+
(lambda ()
(randomly-test-division
+ + euclidean/ euclidean-quotient euclidean-remainder
(lambda (n d) ((if (< d 0) ceiling floor) (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:EUCLIDEAN-/+
(lambda ()
(randomly-test-division
- + euclidean/ euclidean-quotient euclidean-remainder
(lambda (n d) ((if (< d 0) ceiling floor) (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:EUCLIDEAN+/-
(lambda ()
(randomly-test-division
+ - euclidean/ euclidean-quotient euclidean-remainder
(lambda (n d) ((if (< d 0) ceiling floor) (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:EUCLIDEAN-/-
(lambda ()
(randomly-test-division
- - euclidean/ euclidean-quotient euclidean-remainder
(lambda (n d) ((if (< d 0) ceiling floor) (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:FLOOR+/+
(lambda ()
(randomly-test-division + + floor/ floor-quotient floor-remainder
(lambda (n d) (floor (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:FLOOR-/+
(lambda ()
(randomly-test-division - + floor/ floor-quotient floor-remainder
(lambda (n d) (floor (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:FLOOR+/-
(lambda ()
(randomly-test-division + - floor/ floor-quotient floor-remainder
(lambda (n d) (floor (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:FLOOR-/-
(lambda ()
(randomly-test-division - - floor/ floor-quotient floor-remainder
(lambda (n d) (floor (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:ROUND+/+
(lambda ()
(randomly-test-division + + round/ round-quotient round-remainder
(lambda (n d) (round (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:ROUND-/+
(lambda ()
(randomly-test-division - + round/ round-quotient round-remainder
(lambda (n d) (round (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:ROUND+/-
(lambda ()
(randomly-test-division + - round/ round-quotient round-remainder
(lambda (n d) (round (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:ROUND-/-
(lambda ()
(randomly-test-division - - round/ round-quotient round-remainder
(lambda (n d) (round (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:TRUNCATE+/+
(lambda ()
(randomly-test-division + + truncate/ truncate-quotient truncate-remainder
(lambda (n d) (truncate (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:TRUNCATE-/+
(lambda ()
(randomly-test-division - + truncate/ truncate-quotient truncate-remainder
(lambda (n d) (truncate (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:TRUNCATE+/-
(lambda ()
(randomly-test-division + - truncate/ truncate-quotient truncate-remainder
(lambda (n d) (truncate (/ n d))))))
(define-test 'RANDOM-CORRECTNESS-TESTS:TRUNCATE-/-
(lambda ()
(randomly-test-division - - truncate/ truncate-quotient truncate-remainder
(lambda (n d) (truncate (/ n d))))))
(define (randomly-test-properties / assert-property)
(randomly-generate-operands random-sign random-sign
(lambda (n d) (receive (q r) (/ n d) (assert-property n d q r)))))
(define (assert-n=dq+r n d q r)
(assert-eqv (+ (* d q) r) n))
(define-test 'N=DQ+R-TESTS:EUCLIDEAN
(lambda () (randomly-test-properties euclidean/ assert-n=dq+r)))
(define-test 'N=DQ+R-TESTS:FLOOR
(lambda () (randomly-test-properties floor/ assert-n=dq+r)))
(define-test 'N=DQ+R-TESTS:ROUND
(lambda () (randomly-test-properties round/ assert-n=dq+r)))
(define-test 'N=DQ+R-TESTS:TRUNCATE
(lambda () (randomly-test-properties truncate/ assert-n=dq+r)))
(define (assert-r<d n d q r)
(assert-< (abs r) (abs d)))
(define (assert-r<d* n d q r)
(assert-< r (abs d)))
(define-test 'R<D-TESTS:CEILING
(lambda () (randomly-test-properties ceiling/ assert-r<d)))
(define-test 'R<D-TESTS:EUCLIDEAN
(lambda () (randomly-test-properties euclidean/ assert-r<d)))
(define-test 'R<D-TESTS:EUCLIDEAN*
(lambda () (randomly-test-properties euclidean/ assert-r<d*)))
(define-test 'R<D-TESTS:FLOOR
(lambda () (randomly-test-properties floor/ assert-r<d)))
(define-test 'R<D-TESTS:ROUND
(lambda () (randomly-test-properties round/ assert-r<d)))
(define-test 'R<D-TESTS:TRUNCATE
(lambda () (randomly-test-properties truncate/ assert-r<d)))
(define (assert-integral-quotient n d q r)
(value-assert integer? "integer" q))
(define-test 'INTEGRAL-QUOTIENT-TESTS:CEILING
(lambda () (randomly-test-properties ceiling/ assert-integral-quotient)))
(define-test 'INTEGRAL-QUOTIENT-TESTS:EUCLIDEAN
(lambda () (randomly-test-properties euclidean/ assert-integral-quotient)))
(define-test 'INTEGRAL-QUOTIENT-TESTS:FLOOR
(lambda () (randomly-test-properties floor/ assert-integral-quotient)))
(define-test 'INTEGRAL-QUOTIENT-TESTS:ROUND
(lambda () (randomly-test-properties round/ assert-integral-quotient)))
(define-test 'INTEGRAL-QUOTIENT-TESTS:TRUNCATE
(lambda () (randomly-test-properties truncate/ assert-integral-quotient)))
(define (test-trivial-quotient quotient)
(assert-eqv (quotient +1 +1) +1)
(assert-eqv (quotient -1 +1) -1)
(assert-eqv (quotient +1 -1) -1)
(assert-eqv (quotient -1 -1) +1)
(assert-eqv (quotient 0 +1) 0)
(assert-eqv (quotient 0 -1) 0))
(define (test-trivial/ /)
(test-trivial-quotient (lambda (n d) (receive (q r) (/ n d) r q))))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:CEILING-QUOTIENT
(lambda () (test-trivial-quotient ceiling-quotient)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:CEILING/
(lambda () (test-trivial/ ceiling/)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:EUCLIDEAN-QUOTIENT
(lambda () (test-trivial-quotient euclidean-quotient)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:EUCLIDEAN/
(lambda () (test-trivial/ euclidean/)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:FLOOR-QUOTIENT
(lambda () (test-trivial-quotient floor-quotient)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:FLOOR/
(lambda () (test-trivial/ floor/)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:ROUND-QUOTIENT
(lambda () (test-trivial-quotient round-quotient)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:ROUND/
(lambda () (test-trivial/ round/)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:TRUNCATE-QUOTIENT
(lambda () (test-trivial-quotient truncate-quotient)))
(define-test 'TRIVIAL-DIVIDEND/TRIVIAL-DIVISOR-TESTS:TRUNCATE/
(lambda () (test-trivial/ truncate/)))
(define-test 'TRIVIAL-DIVIDEND/RANDOM-DIVISOR-TESTS:CEILING
(lambda ()
(randomly-generate-divisors random-sign
(lambda (d)
(assert-eqv (ceiling-quotient 0 d) 0)
(if (< 1 (abs d))
(begin
(assert-eqv (ceiling-quotient +1 d) (if (negative? d) 0 +1))
(assert-eqv (ceiling-quotient -1 d)
(if (negative? d) +1 0))))))))
(define-test 'TRIVIAL-DIVIDEND/RANDOM-DIVISOR-TESTS:EUCLIDEAN
(lambda ()
(randomly-generate-divisors random-sign
(lambda (d)
(assert-eqv (euclidean-quotient 0 d) 0)
(if (< 1 (abs d))
(begin
(assert-eqv (euclidean-quotient +1 d) 0)
(assert-eqv (euclidean-quotient -1 d)
(if (negative? d) +1 -1))))))))
(define-test 'TRIVIAL-DIVIDEND/RANDOM-DIVISOR-TESTS:FLOOR
(lambda ()
(randomly-generate-divisors random-sign
(lambda (d)
(assert-eqv (floor-quotient 0 d) 0)
(if (< 1 (abs d))
(begin
(assert-eqv (floor-quotient -1 d) (if (negative? d) 0 -1))
(assert-eqv (floor-quotient +1 d) (if (negative? d) -1 0))))))))
(define-test 'TRIVIAL-DIVIDEND/RANDOM-DIVISOR-TESTS:ROUND
(lambda ()
(randomly-generate-divisors random-sign
(lambda (d)
(assert-eqv (round-quotient -1 d) 0)
(assert-eqv (round-quotient 0 d) 0)
(assert-eqv (round-quotient +1 d) 0)))))
(define-test 'TRIVIAL-DIVIDEND/RANDOM-DIVISOR-TESTS:TRUNCATE
(lambda ()
(randomly-generate-divisors random-sign
(lambda (d)
(assert-eqv (truncate-quotient -1 d) 0)
(assert-eqv (truncate-quotient 0 d) 0)
(assert-eqv (truncate-quotient +1 d) 0)))))
(test-end)
|
65c2024594d7657dc6561847357417e1a251a4ab38ee257d1713336d17922cfc | conjure-cp/conjure | AttributeAsConstraint.hs | # LANGUAGE DeriveGeneric , DeriveDataTypeable , DeriveFunctor , , DeriveFoldable #
module Conjure.Language.Expression.Op.AttributeAsConstraint where
import Conjure.Prelude
import Conjure.Language.Expression.Op.Internal.Common
import qualified Data.Aeson as JSON -- aeson
import qualified Data.HashMap.Strict as M -- unordered-containers
import qualified Data.Vector as V -- vector
data OpAttributeAsConstraint x = OpAttributeAsConstraint x
AttrName -- attribute name
(Maybe x) -- it's value
deriving (Eq, Ord, Show, Data, Functor, Traversable, Foldable, Typeable, Generic)
instance Serialize x => Serialize (OpAttributeAsConstraint x)
instance Hashable x => Hashable (OpAttributeAsConstraint x)
instance ToJSON x => ToJSON (OpAttributeAsConstraint x) where toJSON = genericToJSON jsonOptions
instance FromJSON x => FromJSON (OpAttributeAsConstraint x) where parseJSON = genericParseJSON jsonOptions
instance TypeOf (OpAttributeAsConstraint x) where
-- can check more here
typeOf OpAttributeAsConstraint{} = return TypeBool
instance SimplifyOp OpAttributeAsConstraint x where
simplifyOp _ = na "simplifyOp{OpAttributeAsConstraint}"
instance Pretty x => Pretty (OpAttributeAsConstraint x) where
prettyPrec _ (OpAttributeAsConstraint x attr Nothing ) = pretty attr <> prParens (pretty x)
prettyPrec _ (OpAttributeAsConstraint x attr (Just val)) = pretty attr <> prettyList prParens "," [x, val]
instance VarSymBreakingDescription x => VarSymBreakingDescription (OpAttributeAsConstraint x) where
varSymBreakingDescription (OpAttributeAsConstraint a b c) = JSON.Object $ M.fromList
[ ("type", JSON.String "OpAttributeAsConstraint")
, ("children", JSON.Array $ V.fromList
[ varSymBreakingDescription a
, toJSON b
, maybe JSON.Null varSymBreakingDescription c
])
]
| null | https://raw.githubusercontent.com/conjure-cp/conjure/dd5a27df138af2ccbbb970274c2b8f22ac6b26a0/src/Conjure/Language/Expression/Op/AttributeAsConstraint.hs | haskell | aeson
unordered-containers
vector
attribute name
it's value
can check more here | # LANGUAGE DeriveGeneric , DeriveDataTypeable , DeriveFunctor , , DeriveFoldable #
module Conjure.Language.Expression.Op.AttributeAsConstraint where
import Conjure.Prelude
import Conjure.Language.Expression.Op.Internal.Common
data OpAttributeAsConstraint x = OpAttributeAsConstraint x
deriving (Eq, Ord, Show, Data, Functor, Traversable, Foldable, Typeable, Generic)
instance Serialize x => Serialize (OpAttributeAsConstraint x)
instance Hashable x => Hashable (OpAttributeAsConstraint x)
instance ToJSON x => ToJSON (OpAttributeAsConstraint x) where toJSON = genericToJSON jsonOptions
instance FromJSON x => FromJSON (OpAttributeAsConstraint x) where parseJSON = genericParseJSON jsonOptions
instance TypeOf (OpAttributeAsConstraint x) where
typeOf OpAttributeAsConstraint{} = return TypeBool
instance SimplifyOp OpAttributeAsConstraint x where
simplifyOp _ = na "simplifyOp{OpAttributeAsConstraint}"
instance Pretty x => Pretty (OpAttributeAsConstraint x) where
prettyPrec _ (OpAttributeAsConstraint x attr Nothing ) = pretty attr <> prParens (pretty x)
prettyPrec _ (OpAttributeAsConstraint x attr (Just val)) = pretty attr <> prettyList prParens "," [x, val]
instance VarSymBreakingDescription x => VarSymBreakingDescription (OpAttributeAsConstraint x) where
varSymBreakingDescription (OpAttributeAsConstraint a b c) = JSON.Object $ M.fromList
[ ("type", JSON.String "OpAttributeAsConstraint")
, ("children", JSON.Array $ V.fromList
[ varSymBreakingDescription a
, toJSON b
, maybe JSON.Null varSymBreakingDescription c
])
]
|
eeabbd3e8c9dd9315b18d9a130d04138ad4bf5b14cdfb5c95af01efb51f59ab6 | soegaard/metapict | pointilism2.rkt | #lang racket
;;;
Pointilism - Animation
;;;
; Inspired by
;
The image shows on the moon saluting the american flag .
(require metapict
(only-in racket/gui image-snip%)
(only-in 2htdp/universe big-bang on-tick to-draw)
(only-in 2htdp/image overlay empty-scene))
(def bm (read-bitmap "moonlanding.jpg")) ; read bitmap from disk
(defv (w h) (bitmap-size bm)) ; determine width and height
tell the physical size
(curve-pict-window (window 0 w h 0)) ; set logical coordinate system
(define (draw-points n size) ; draw n circles of radius size
(for/draw ([n n])
(def x (random w)) ; generate random point (w,h)
(def y (random h))
(def c (get-pixel bm x y)) ; find color of that point
(color c (fill (circle (pt x y) size))))) ; draw disk of that color
(define (pict->scene p)
(make-object image-snip% (pict->bitmap p)))
(define (handle-on-tick world)
(defm (list size scene) world)
(list size (draw scene (draw-points 100 size))))
(define (draw-world w)
(pict->scene (second w)))
(big-bang (list 4 (blank w h))
[on-tick handle-on-tick]
[to-draw draw-world])
| null | https://raw.githubusercontent.com/soegaard/metapict/47ae265f73cbb92ff3e7bdd61e49f4af17597fdf/metapict/examples/pointilism2.rkt | racket |
Inspired by
read bitmap from disk
determine width and height
set logical coordinate system
draw n circles of radius size
generate random point (w,h)
find color of that point
draw disk of that color | #lang racket
Pointilism - Animation
The image shows on the moon saluting the american flag .
(require metapict
(only-in racket/gui image-snip%)
(only-in 2htdp/universe big-bang on-tick to-draw)
(only-in 2htdp/image overlay empty-scene))
tell the physical size
(for/draw ([n n])
(def y (random h))
(define (pict->scene p)
(make-object image-snip% (pict->bitmap p)))
(define (handle-on-tick world)
(defm (list size scene) world)
(list size (draw scene (draw-points 100 size))))
(define (draw-world w)
(pict->scene (second w)))
(big-bang (list 4 (blank w h))
[on-tick handle-on-tick]
[to-draw draw-world])
|
ca347d084ad3829f89460375474180ffade2d6a176f560c3a85e9990ca8b9ed9 | facebookarchive/duckling_old | helpers.clj | (ns duckling.helpers
"This namespace contains the common helpers used in rules"
(:require
[clj-time.core :as t]
[duckling.util :as util]))
(defmacro fn& [dim & args-body]
(let [meta-map (when (-> args-body first map?)
(first args-body))
args-body (if meta-map
(rest args-body)
args-body)]
(merge meta-map
`{:dim ~(keyword dim)
:pred (fn ~@args-body)})))
(defn dim
"Returns a func checking dim of a token and additional preds"
[dim-val & predicates]
(fn [token]
(and (= dim-val (:dim token))
(every? #(% token) predicates))))
(defn integer
"Return a func (duckling pattern) checking that dim=number and integer=true,
optional range (inclusive), and additional preds"
[& [min max & predicates]]
(fn [token]
(and (= :number (:dim token))
(:integer token)
(or (nil? min) (<= min (:val token)))
(or (nil? max) (<= (:val token) max))
(every? #(% token) predicates))))
| null | https://raw.githubusercontent.com/facebookarchive/duckling_old/bf5bb9758c36313b56e136a28ba401696eeff10b/src/duckling/helpers.clj | clojure | (ns duckling.helpers
"This namespace contains the common helpers used in rules"
(:require
[clj-time.core :as t]
[duckling.util :as util]))
(defmacro fn& [dim & args-body]
(let [meta-map (when (-> args-body first map?)
(first args-body))
args-body (if meta-map
(rest args-body)
args-body)]
(merge meta-map
`{:dim ~(keyword dim)
:pred (fn ~@args-body)})))
(defn dim
"Returns a func checking dim of a token and additional preds"
[dim-val & predicates]
(fn [token]
(and (= dim-val (:dim token))
(every? #(% token) predicates))))
(defn integer
"Return a func (duckling pattern) checking that dim=number and integer=true,
optional range (inclusive), and additional preds"
[& [min max & predicates]]
(fn [token]
(and (= :number (:dim token))
(:integer token)
(or (nil? min) (<= min (:val token)))
(or (nil? max) (<= (:val token) max))
(every? #(% token) predicates))))
|
|
7d947919242c2fd13d3593799c48e85871a90173abef918e60154cf97e5f1ce1 | faylang/fay | Compiler.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards #
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE ViewPatterns #
| The Haskell→Javascript compiler .
module Fay.Compiler
(runCompileModule
,compileViaStr
,compileWith
,compileExp
,compileDecl
,compileToplevelModule
,compileModuleFromContents
,compileModuleFromAST
,parseFay)
where
import Fay.Compiler.Prelude
import Fay.Compiler.Decl
import Fay.Compiler.Defaults
import Fay.Compiler.Desugar
import Fay.Compiler.Exp
import Fay.Compiler.FFI
import Fay.Compiler.Import
import Fay.Compiler.InitialPass (initialPass)
import Fay.Compiler.Misc
import Fay.Compiler.Optimizer
import Fay.Compiler.Parse
import Fay.Compiler.PrimOp (findPrimOp)
import Fay.Compiler.QName
import Fay.Compiler.State
import Fay.Compiler.Typecheck
import Fay.Config
import qualified Fay.Exts as F
import Fay.Exts.NoAnnotation (unAnn)
import qualified Fay.Exts.NoAnnotation as N
import Fay.Types
import Control.Monad.Except (throwError)
import Control.Monad.RWS (gets, modify)
import qualified Data.Set as S
import Language.Haskell.Exts hiding (name)
import Language.Haskell.Names (annotateModule)
--------------------------------------------------------------------------------
-- Top level entry points
| Compile a Haskell source string to a JavaScript source string .
compileViaStr
:: FilePath
-> Config
-> (F.Module -> Compile [JsStmt])
-> String
-> IO (Either CompileError (Printer,CompileState,CompileWriter))
compileViaStr filepath cfg with from = do
rs <- defaultCompileReader cfg
runTopCompile rs
defaultCompileState
(parseResult (throwError . uncurry ParseError)
(fmap (mconcat . map printJS) . with)
(parseFay filepath from))
| Compile the top - level module .
compileToplevelModule :: FilePath -> F.Module -> Compile [JsStmt]
compileToplevelModule filein mod@Module{} = do
cfg <- config id
when (configTypecheck cfg) $ do
res <- io $ typecheck cfg $
fromMaybe (F.moduleNameString (F.moduleName mod)) $
configFilePath cfg
either throwError warn res
initialPass filein
-- Reset imports after initialPass so the modules can be imported during code generation.
(hstmts, fstmts) <- startCompile compileFileWithSource filein
return (hstmts++fstmts)
compileToplevelModule _ m = throwError $ UnsupportedModuleSyntax "compileToplevelModule" m
--------------------------------------------------------------------------------
-- Compilers
-- | Compile a source string.
compileModuleFromContents :: String -> Compile ([JsStmt], [JsStmt])
compileModuleFromContents = compileFileWithSource "<interactive>"
-- | Compile given the location and source string.
compileFileWithSource :: FilePath -> String -> Compile ([JsStmt], [JsStmt])
compileFileWithSource filepath contents = do
exportStdlib <- config configExportStdlib
((hstmts,fstmts),st,wr) <- compileWith filepath compileModuleFromAST compileFileWithSource desugar contents
modify $ \s -> s { stateImported = stateImported st
, stateJsModulePaths = stateJsModulePaths st
}
hstmts' <- maybeOptimize $ hstmts ++ writerCons wr ++ makeTranscoding exportStdlib (stateModuleName st) wr
fstmts' <- maybeOptimize fstmts
return (hstmts', fstmts')
where
makeTranscoding :: Bool -> ModuleName a -> CompileWriter -> [JsStmt]
makeTranscoding exportStdlib moduleName CompileWriter{..} =
let fay2js = if null writerFayToJs || (anStdlibModule moduleName && not exportStdlib)
then []
else fayToJsHash writerFayToJs
js2fay = if null writerJsToFay || (anStdlibModule moduleName && not exportStdlib)
then []
else jsToFayHash writerJsToFay
in fay2js ++ js2fay
maybeOptimize :: [JsStmt] -> Compile [JsStmt]
maybeOptimize stmts = do
cfg <- config id
return $ if configOptimize cfg
then runOptimizer optimizeToplevel stmts
else stmts
| Compile a parse HSE module .
compileModuleFromAST :: ([JsStmt], [JsStmt]) -> F.Module -> Compile ([JsStmt], [JsStmt])
compileModuleFromAST (hstmts0, fstmts0) mod'@Module{} = do
~mod@(Module _ _ pragmas _ decls) <- annotateModule Haskell2010 defaultExtensions mod'
let modName = unAnn $ F.moduleName mod
modify $ \s -> s { stateUseFromString = hasLanguagePragmas ["OverloadedStrings", "RebindableSyntax"] pragmas
}
current <- compileDecls True decls
exportStdlib <- config configExportStdlib
exportStdlibOnly <- config configExportStdlibOnly
modulePaths <- createModulePath modName
extExports <- generateExports
strictExports <- generateStrictExports
let hstmts = hstmts0 ++ modulePaths ++ current ++ extExports
fstmts = fstmts0 ++ strictExports
return $ if exportStdlibOnly
then if anStdlibModule modName
then (hstmts, fstmts)
else ([], [])
else if not exportStdlib && anStdlibModule modName
then ([], [])
else (hstmts, fstmts)
compileModuleFromAST _ mod = throwError $ UnsupportedModuleSyntax "compileModuleFromAST" mod
--------------------------------------------------------------------------------
-- Misc compilation
| For a module , generate
-- | var A = {};
-- | A.B = {};
createModulePath :: ModuleName a -> Compile [JsStmt]
createModulePath (unAnn -> m) = do
cfg <- config id
let isTs = configTypeScript cfg
reg <- fmap concat . mapM (modPath isTs) . mkModulePaths $ m
strict <-
if shouldExportStrictWrapper m cfg
then fmap concat . mapM (modPath isTs) . mkModulePaths $ (\(ModuleName i n) -> ModuleName i ("Strict." ++ n)) m
else return []
return $ reg ++ strict
where
modPath :: Bool -> ModulePath -> Compile [JsStmt]
modPath isTs mp = whenImportNotGenerated mp $ \(unModulePath -> l) -> case l of
[n] -> if isTs
then [JsMapVar (JsNameVar . UnQual () $ Ident () n) (JsObj [])]
else [JsVar (JsNameVar . UnQual () $ Ident () n) (JsObj [])]
_ -> [JsSetModule mp (JsObj [])]
whenImportNotGenerated :: ModulePath -> (ModulePath -> [JsStmt]) -> Compile [JsStmt]
whenImportNotGenerated mp makePath = do
added <- gets $ addedModulePath mp
if added
then return []
else do
modify $ addModulePath mp
return $ makePath mp
-- | Generate exports for non local names, local exports have already been added to the module.
generateExports :: Compile [JsStmt]
generateExports = do
modName <- gets stateModuleName
maybe [] (map (exportExp modName) . S.toList) <$> gets (getNonLocalExportsWithoutNewtypes modName)
where
exportExp :: N.ModuleName -> N.QName -> JsStmt
exportExp m v = JsSetQName Nothing (changeModule m v) $ case findPrimOp v of
TODO add test case for this case , is it needed at all ?
Nothing -> JsName $ JsNameVar v
-- | Generate strict wrappers for the exports of the module.
generateStrictExports :: Compile [JsStmt]
generateStrictExports = do
cfg <- config id
modName <- gets stateModuleName
if shouldExportStrictWrapper modName cfg
then do
locals <- gets (getLocalExportsWithoutNewtypes modName)
nonLocals <- gets (getNonLocalExportsWithoutNewtypes modName)
let int = maybe [] (map exportExp' . S.toList) locals
let ext = maybe [] (map (exportExp modName) . S.toList) nonLocals
return $ int ++ ext
else return []
where
exportExp :: N.ModuleName -> N.QName -> JsStmt
exportExp m v = JsSetQName Nothing (changeModule' ("Strict." ++) $ changeModule m v) $ JsName $ JsNameVar $ changeModule' ("Strict." ++) v
exportExp' :: N.QName -> JsStmt
exportExp' name = JsSetQName Nothing (changeModule' ("Strict." ++) name) $ serialize (JsName (JsNameVar name))
serialize :: JsExp -> JsExp
serialize n = JsApp (JsRawExp "Fay$$fayToJs") [JsRawExp "['automatic']", n]
-- | Is the module a standard module, i.e., one that we'd rather not
-- output code for if we're compiling separate files.
anStdlibModule :: ModuleName a -> Bool
anStdlibModule (ModuleName _ name) = name `elem` ["Prelude","FFI","Fay.FFI","Data.Data","Data.Ratio","Debug.Trace","Data.Char"]
| null | https://raw.githubusercontent.com/faylang/fay/8455d975f9f0db2ecc922410e43e484fbd134699/src/Fay/Compiler.hs | haskell | # LANGUAGE ScopedTypeVariables #
------------------------------------------------------------------------------
Top level entry points
Reset imports after initialPass so the modules can be imported during code generation.
------------------------------------------------------------------------------
Compilers
| Compile a source string.
| Compile given the location and source string.
------------------------------------------------------------------------------
Misc compilation
| var A = {};
| A.B = {};
| Generate exports for non local names, local exports have already been added to the module.
| Generate strict wrappers for the exports of the module.
| Is the module a standard module, i.e., one that we'd rather not
output code for if we're compiling separate files. | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards #
# LANGUAGE ViewPatterns #
| The Haskell→Javascript compiler .
module Fay.Compiler
(runCompileModule
,compileViaStr
,compileWith
,compileExp
,compileDecl
,compileToplevelModule
,compileModuleFromContents
,compileModuleFromAST
,parseFay)
where
import Fay.Compiler.Prelude
import Fay.Compiler.Decl
import Fay.Compiler.Defaults
import Fay.Compiler.Desugar
import Fay.Compiler.Exp
import Fay.Compiler.FFI
import Fay.Compiler.Import
import Fay.Compiler.InitialPass (initialPass)
import Fay.Compiler.Misc
import Fay.Compiler.Optimizer
import Fay.Compiler.Parse
import Fay.Compiler.PrimOp (findPrimOp)
import Fay.Compiler.QName
import Fay.Compiler.State
import Fay.Compiler.Typecheck
import Fay.Config
import qualified Fay.Exts as F
import Fay.Exts.NoAnnotation (unAnn)
import qualified Fay.Exts.NoAnnotation as N
import Fay.Types
import Control.Monad.Except (throwError)
import Control.Monad.RWS (gets, modify)
import qualified Data.Set as S
import Language.Haskell.Exts hiding (name)
import Language.Haskell.Names (annotateModule)
| Compile a Haskell source string to a JavaScript source string .
compileViaStr
:: FilePath
-> Config
-> (F.Module -> Compile [JsStmt])
-> String
-> IO (Either CompileError (Printer,CompileState,CompileWriter))
compileViaStr filepath cfg with from = do
rs <- defaultCompileReader cfg
runTopCompile rs
defaultCompileState
(parseResult (throwError . uncurry ParseError)
(fmap (mconcat . map printJS) . with)
(parseFay filepath from))
| Compile the top - level module .
compileToplevelModule :: FilePath -> F.Module -> Compile [JsStmt]
compileToplevelModule filein mod@Module{} = do
cfg <- config id
when (configTypecheck cfg) $ do
res <- io $ typecheck cfg $
fromMaybe (F.moduleNameString (F.moduleName mod)) $
configFilePath cfg
either throwError warn res
initialPass filein
(hstmts, fstmts) <- startCompile compileFileWithSource filein
return (hstmts++fstmts)
compileToplevelModule _ m = throwError $ UnsupportedModuleSyntax "compileToplevelModule" m
compileModuleFromContents :: String -> Compile ([JsStmt], [JsStmt])
compileModuleFromContents = compileFileWithSource "<interactive>"
compileFileWithSource :: FilePath -> String -> Compile ([JsStmt], [JsStmt])
compileFileWithSource filepath contents = do
exportStdlib <- config configExportStdlib
((hstmts,fstmts),st,wr) <- compileWith filepath compileModuleFromAST compileFileWithSource desugar contents
modify $ \s -> s { stateImported = stateImported st
, stateJsModulePaths = stateJsModulePaths st
}
hstmts' <- maybeOptimize $ hstmts ++ writerCons wr ++ makeTranscoding exportStdlib (stateModuleName st) wr
fstmts' <- maybeOptimize fstmts
return (hstmts', fstmts')
where
makeTranscoding :: Bool -> ModuleName a -> CompileWriter -> [JsStmt]
makeTranscoding exportStdlib moduleName CompileWriter{..} =
let fay2js = if null writerFayToJs || (anStdlibModule moduleName && not exportStdlib)
then []
else fayToJsHash writerFayToJs
js2fay = if null writerJsToFay || (anStdlibModule moduleName && not exportStdlib)
then []
else jsToFayHash writerJsToFay
in fay2js ++ js2fay
maybeOptimize :: [JsStmt] -> Compile [JsStmt]
maybeOptimize stmts = do
cfg <- config id
return $ if configOptimize cfg
then runOptimizer optimizeToplevel stmts
else stmts
| Compile a parse HSE module .
compileModuleFromAST :: ([JsStmt], [JsStmt]) -> F.Module -> Compile ([JsStmt], [JsStmt])
compileModuleFromAST (hstmts0, fstmts0) mod'@Module{} = do
~mod@(Module _ _ pragmas _ decls) <- annotateModule Haskell2010 defaultExtensions mod'
let modName = unAnn $ F.moduleName mod
modify $ \s -> s { stateUseFromString = hasLanguagePragmas ["OverloadedStrings", "RebindableSyntax"] pragmas
}
current <- compileDecls True decls
exportStdlib <- config configExportStdlib
exportStdlibOnly <- config configExportStdlibOnly
modulePaths <- createModulePath modName
extExports <- generateExports
strictExports <- generateStrictExports
let hstmts = hstmts0 ++ modulePaths ++ current ++ extExports
fstmts = fstmts0 ++ strictExports
return $ if exportStdlibOnly
then if anStdlibModule modName
then (hstmts, fstmts)
else ([], [])
else if not exportStdlib && anStdlibModule modName
then ([], [])
else (hstmts, fstmts)
compileModuleFromAST _ mod = throwError $ UnsupportedModuleSyntax "compileModuleFromAST" mod
| For a module , generate
createModulePath :: ModuleName a -> Compile [JsStmt]
createModulePath (unAnn -> m) = do
cfg <- config id
let isTs = configTypeScript cfg
reg <- fmap concat . mapM (modPath isTs) . mkModulePaths $ m
strict <-
if shouldExportStrictWrapper m cfg
then fmap concat . mapM (modPath isTs) . mkModulePaths $ (\(ModuleName i n) -> ModuleName i ("Strict." ++ n)) m
else return []
return $ reg ++ strict
where
modPath :: Bool -> ModulePath -> Compile [JsStmt]
modPath isTs mp = whenImportNotGenerated mp $ \(unModulePath -> l) -> case l of
[n] -> if isTs
then [JsMapVar (JsNameVar . UnQual () $ Ident () n) (JsObj [])]
else [JsVar (JsNameVar . UnQual () $ Ident () n) (JsObj [])]
_ -> [JsSetModule mp (JsObj [])]
whenImportNotGenerated :: ModulePath -> (ModulePath -> [JsStmt]) -> Compile [JsStmt]
whenImportNotGenerated mp makePath = do
added <- gets $ addedModulePath mp
if added
then return []
else do
modify $ addModulePath mp
return $ makePath mp
generateExports :: Compile [JsStmt]
generateExports = do
modName <- gets stateModuleName
maybe [] (map (exportExp modName) . S.toList) <$> gets (getNonLocalExportsWithoutNewtypes modName)
where
exportExp :: N.ModuleName -> N.QName -> JsStmt
exportExp m v = JsSetQName Nothing (changeModule m v) $ case findPrimOp v of
TODO add test case for this case , is it needed at all ?
Nothing -> JsName $ JsNameVar v
generateStrictExports :: Compile [JsStmt]
generateStrictExports = do
cfg <- config id
modName <- gets stateModuleName
if shouldExportStrictWrapper modName cfg
then do
locals <- gets (getLocalExportsWithoutNewtypes modName)
nonLocals <- gets (getNonLocalExportsWithoutNewtypes modName)
let int = maybe [] (map exportExp' . S.toList) locals
let ext = maybe [] (map (exportExp modName) . S.toList) nonLocals
return $ int ++ ext
else return []
where
exportExp :: N.ModuleName -> N.QName -> JsStmt
exportExp m v = JsSetQName Nothing (changeModule' ("Strict." ++) $ changeModule m v) $ JsName $ JsNameVar $ changeModule' ("Strict." ++) v
exportExp' :: N.QName -> JsStmt
exportExp' name = JsSetQName Nothing (changeModule' ("Strict." ++) name) $ serialize (JsName (JsNameVar name))
serialize :: JsExp -> JsExp
serialize n = JsApp (JsRawExp "Fay$$fayToJs") [JsRawExp "['automatic']", n]
anStdlibModule :: ModuleName a -> Bool
anStdlibModule (ModuleName _ name) = name `elem` ["Prelude","FFI","Fay.FFI","Data.Data","Data.Ratio","Debug.Trace","Data.Char"]
|
777ff2404859668be0b3f5f9bab724c8ade2dc5828470ae3715c17585619b8e3 | serokell/ariadne | AccountSettings.hs | module Ariadne.UI.Qt.Widgets.Dialogs.AccountSettings
( RenameHandler
, DeleteHandler
, runAccountSettings
) where
import qualified Data.Text as T
import Graphics.UI.Qtah.Core.HSize (HSize(..))
import Graphics.UI.Qtah.Core.Types (QtCursorShape(..))
import Graphics.UI.Qtah.Signal (connect_)
import qualified Graphics.UI.Qtah.Core.QEvent as QEvent
import qualified Graphics.UI.Qtah.Event as Event
import qualified Graphics.UI.Qtah.Gui.QCursor as QCursor
import qualified Graphics.UI.Qtah.Gui.QMouseEvent as QMouseEvent
import qualified Graphics.UI.Qtah.Widgets.QAbstractButton as QAbstractButton
import qualified Graphics.UI.Qtah.Widgets.QApplication as QApplication
import qualified Graphics.UI.Qtah.Widgets.QBoxLayout as QBoxLayout
import qualified Graphics.UI.Qtah.Widgets.QDialog as QDialog
import qualified Graphics.UI.Qtah.Widgets.QHBoxLayout as QHBoxLayout
import qualified Graphics.UI.Qtah.Widgets.QLabel as QLabel
import qualified Graphics.UI.Qtah.Widgets.QLineEdit as QLineEdit
import qualified Graphics.UI.Qtah.Widgets.QPushButton as QPushButton
import qualified Graphics.UI.Qtah.Widgets.QWidget as QWidget
import Ariadne.UI.Qt.UI
import Ariadne.UI.Qt.Widgets.Dialogs.Util
data AccountSettings =
AccountSettings
{ accountSettings :: QDialog.QDialog
}
type RenameHandler = Text -> IO ()
type DeleteHandler = IO ()
initAccountSettings :: Text -> RenameHandler -> DeleteHandler -> IO AccountSettings
initAccountSettings currentName renameHandler deleteHandler = do
accountSettings <- QDialog.new
layout <- createLayout accountSettings
let headerString = toString $ T.toUpper "ACCOUNT SETTINGS"
QWidget.setWindowTitle accountSettings headerString
header <- QLabel.newWithText headerString
addHeader layout header
accountNameLabel <- QLabel.newWithText ("ACCOUNT NAME" :: String)
accountNameEdit <- QLineEdit.newWithText $ toString currentName
addRow layout accountNameLabel accountNameEdit
pointingCursor <- QCursor.newWithCursorShape PointingHandCursor
buttonsLayout <- QHBoxLayout.new
deleteButton <- QPushButton.newWithText ("Delete account" :: String)
QWidget.setCursor deleteButton pointingCursor
QBoxLayout.addStretch buttonsLayout
QBoxLayout.addWidget buttonsLayout deleteButton
QBoxLayout.addStretch buttonsLayout
QBoxLayout.addLayout layout buttonsLayout
QPushButton.setDefault deleteButton False
QPushButton.setAutoDefault deleteButton False
setProperty deleteButton ("dialogButtonRole" :: Text) ("textDangerButton" :: Text)
let asettings = AccountSettings{..}
connect_ deleteButton QAbstractButton.clickedSignal $ \_ ->
deleteHandler >> QDialog.accept accountSettings
connect_ accountNameEdit QLineEdit.editingFinishedSignal $
QLineEdit.text accountNameEdit <&> fromString >>= renameHandler
QWidget.adjustSize accountSettings
-- Let user resize the dialog, but not too much
HSize{width = asWidth, height = asHeight} <- QWidget.size accountSettings
QWidget.setMinimumSize accountSettings $ HSize{width = asWidth, height = asHeight}
QWidget.setMaximumSize accountSettings $ HSize{width = 2 * asWidth, height = asHeight}
-- This unfocuses any focused widget when user clicks outside input fields,
-- essentially triggering editingFinished signal.
void $ Event.onEvent accountSettings $ \(ev :: QMouseEvent.QMouseEvent) -> do
evType <- QEvent.eventType ev
when (evType == QEvent.MouseButtonRelease) $
QApplication.focusWidget >>= QWidget.clearFocus
return False
return asettings
runAccountSettings :: Text -> RenameHandler -> DeleteHandler -> IO ()
runAccountSettings currentName renameHandler deleteHandler = do
AccountSettings{..} <- initAccountSettings currentName renameHandler deleteHandler
void $ QDialog.exec accountSettings
| null | https://raw.githubusercontent.com/serokell/ariadne/5f49ee53b6bbaf332cb6f110c75f7b971acdd452/ui/qt-lib/src/Ariadne/UI/Qt/Widgets/Dialogs/AccountSettings.hs | haskell | Let user resize the dialog, but not too much
This unfocuses any focused widget when user clicks outside input fields,
essentially triggering editingFinished signal. | module Ariadne.UI.Qt.Widgets.Dialogs.AccountSettings
( RenameHandler
, DeleteHandler
, runAccountSettings
) where
import qualified Data.Text as T
import Graphics.UI.Qtah.Core.HSize (HSize(..))
import Graphics.UI.Qtah.Core.Types (QtCursorShape(..))
import Graphics.UI.Qtah.Signal (connect_)
import qualified Graphics.UI.Qtah.Core.QEvent as QEvent
import qualified Graphics.UI.Qtah.Event as Event
import qualified Graphics.UI.Qtah.Gui.QCursor as QCursor
import qualified Graphics.UI.Qtah.Gui.QMouseEvent as QMouseEvent
import qualified Graphics.UI.Qtah.Widgets.QAbstractButton as QAbstractButton
import qualified Graphics.UI.Qtah.Widgets.QApplication as QApplication
import qualified Graphics.UI.Qtah.Widgets.QBoxLayout as QBoxLayout
import qualified Graphics.UI.Qtah.Widgets.QDialog as QDialog
import qualified Graphics.UI.Qtah.Widgets.QHBoxLayout as QHBoxLayout
import qualified Graphics.UI.Qtah.Widgets.QLabel as QLabel
import qualified Graphics.UI.Qtah.Widgets.QLineEdit as QLineEdit
import qualified Graphics.UI.Qtah.Widgets.QPushButton as QPushButton
import qualified Graphics.UI.Qtah.Widgets.QWidget as QWidget
import Ariadne.UI.Qt.UI
import Ariadne.UI.Qt.Widgets.Dialogs.Util
data AccountSettings =
AccountSettings
{ accountSettings :: QDialog.QDialog
}
type RenameHandler = Text -> IO ()
type DeleteHandler = IO ()
initAccountSettings :: Text -> RenameHandler -> DeleteHandler -> IO AccountSettings
initAccountSettings currentName renameHandler deleteHandler = do
accountSettings <- QDialog.new
layout <- createLayout accountSettings
let headerString = toString $ T.toUpper "ACCOUNT SETTINGS"
QWidget.setWindowTitle accountSettings headerString
header <- QLabel.newWithText headerString
addHeader layout header
accountNameLabel <- QLabel.newWithText ("ACCOUNT NAME" :: String)
accountNameEdit <- QLineEdit.newWithText $ toString currentName
addRow layout accountNameLabel accountNameEdit
pointingCursor <- QCursor.newWithCursorShape PointingHandCursor
buttonsLayout <- QHBoxLayout.new
deleteButton <- QPushButton.newWithText ("Delete account" :: String)
QWidget.setCursor deleteButton pointingCursor
QBoxLayout.addStretch buttonsLayout
QBoxLayout.addWidget buttonsLayout deleteButton
QBoxLayout.addStretch buttonsLayout
QBoxLayout.addLayout layout buttonsLayout
QPushButton.setDefault deleteButton False
QPushButton.setAutoDefault deleteButton False
setProperty deleteButton ("dialogButtonRole" :: Text) ("textDangerButton" :: Text)
let asettings = AccountSettings{..}
connect_ deleteButton QAbstractButton.clickedSignal $ \_ ->
deleteHandler >> QDialog.accept accountSettings
connect_ accountNameEdit QLineEdit.editingFinishedSignal $
QLineEdit.text accountNameEdit <&> fromString >>= renameHandler
QWidget.adjustSize accountSettings
HSize{width = asWidth, height = asHeight} <- QWidget.size accountSettings
QWidget.setMinimumSize accountSettings $ HSize{width = asWidth, height = asHeight}
QWidget.setMaximumSize accountSettings $ HSize{width = 2 * asWidth, height = asHeight}
void $ Event.onEvent accountSettings $ \(ev :: QMouseEvent.QMouseEvent) -> do
evType <- QEvent.eventType ev
when (evType == QEvent.MouseButtonRelease) $
QApplication.focusWidget >>= QWidget.clearFocus
return False
return asettings
runAccountSettings :: Text -> RenameHandler -> DeleteHandler -> IO ()
runAccountSettings currentName renameHandler deleteHandler = do
AccountSettings{..} <- initAccountSettings currentName renameHandler deleteHandler
void $ QDialog.exec accountSettings
|
c12572409e06d7aa7a2e572ee974d8b21aeae5c9fe510935deb72b9f6d38d814 | kuberlog/holon | Daemon.lisp | (defpackage :holon.Daemon (:use :cl))
(in-package :holon.Daemon)
(defclass Daemon () (
(name :initarg :name :accessor name)
(description :initarg :description)
(approx-marginal-cost :initarg :approx-marginal-cost :initform nil)))
(defun print-daemon (daemon)
(let ((marginal-cost (slot-value daemon 'approx-marginal-cost)))
(format nil (concatenate 'string
"name: ~a~%description: ~a~%"
(if (not (null marginal-cost)) "approx-marginal-cost: ~a~%" "")
"~%")
(slot-value daemon 'name)
(slot-value daemon 'description)
(if (not (null marginal-cost))
marginal-cost
""))))
(defun serialize (daemon)
`(,(slot-value daemon 'name) .
((:description . ,(slot-value daemon 'description))
(:approx-marginal-cost . ,(slot-value daemon 'approx-marginal-cost)))))
| null | https://raw.githubusercontent.com/kuberlog/holon/380fe5ccd83a014389c15b7d238164d20430a360/lisp/ecosystem/Daemon.lisp | lisp | (defpackage :holon.Daemon (:use :cl))
(in-package :holon.Daemon)
(defclass Daemon () (
(name :initarg :name :accessor name)
(description :initarg :description)
(approx-marginal-cost :initarg :approx-marginal-cost :initform nil)))
(defun print-daemon (daemon)
(let ((marginal-cost (slot-value daemon 'approx-marginal-cost)))
(format nil (concatenate 'string
"name: ~a~%description: ~a~%"
(if (not (null marginal-cost)) "approx-marginal-cost: ~a~%" "")
"~%")
(slot-value daemon 'name)
(slot-value daemon 'description)
(if (not (null marginal-cost))
marginal-cost
""))))
(defun serialize (daemon)
`(,(slot-value daemon 'name) .
((:description . ,(slot-value daemon 'description))
(:approx-marginal-cost . ,(slot-value daemon 'approx-marginal-cost)))))
|
|
42524d95433edb54db9a8fc4862b3f665c30a994caec11a0227d13fce8f0c711 | Clozure/ccl | apropos-window.lisp | ;;;-*-Mode: LISP; Package: GUI -*-
;;;
;;; Copyright 2007 Clozure Associates
;;;
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; -2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(in-package "GUI")
(defclass package-combo-box (ns:ns-combo-box)
((packages :initform nil))
(:metaclass ns:+ns-object))
;;; This is a premature optimization. Instead of calling LIST-ALL-PACKAGES
;;; so frequently, just get a fresh copy when the user clicks in the
;;; combo box.
(objc:defmethod (#/becomeFirstResponder :<BOOL>) ((self package-combo-box))
(with-slots (packages) self
(setf packages (coerce (list-all-packages) 'vector))
(setf packages (sort packages #'string-lessp :key #'package-name)))
(call-next-method))
(defclass apropos-window-controller (ns:ns-window-controller)
((apropos-array :foreign-type :id :initform +null-ptr+
:reader apropos-array
:documentation "Bound to NSArrayController in nib file")
(array-controller :foreign-type :id :accessor array-controller)
(combo-box :foreign-type :id :accessor combo-box)
(table-view :foreign-type :id :accessor table-view)
(text-view :foreign-type :id :accessor text-view)
(external-symbols-checkbox :foreign-type :id
:accessor external-symbols-checkbox)
(shows-external-symbols :initform nil)
(symbol-list :initform nil)
(package :initform nil)
(input :initform nil)
(previous-input :initform nil :accessor previous-input
:documentation "Last string entered"))
(:metaclass ns:+ns-object))
(defmethod (setf apropos-array) (value (self apropos-window-controller))
(with-slots (apropos-array) self
(unless (eql value apropos-array)
(#/release apropos-array)
(setf apropos-array (#/retain value)))))
Diasable automatic KVO notifications , since having our class swizzled
out from underneath us confuses CLOS . ( Leopard does n't hose us ,
and we can use automatic KVO notifications there . )
(objc:defmethod (#/automaticallyNotifiesObserversForKey: :<BOOL>) ((self +apropos-window-controller)
key)
(declare (ignore key))
nil)
(objc:defmethod (#/awakeFromNib :void) ((self apropos-window-controller))
(with-slots (table-view text-view) self
(#/setString: text-view #@"")
(#/setDelegate: table-view self)
(#/setDoubleAction: table-view (@selector #/definitionForSelectedSymbol:))))
(objc:defmethod #/init ((self apropos-window-controller))
(prog1
(#/initWithWindowNibName: self #@"apropos")
(#/setShouldCascadeWindows: self nil)
(#/setWindowFrameAutosaveName: self #@"apropos panel")
(setf (apropos-array self) (#/array ns:ns-mutable-array))))
(objc:defmethod (#/dealloc :void) ((self apropos-window-controller))
(#/release (slot-value self 'apropos-array))
(call-next-method))
(objc:defmethod (#/toggleShowsExternalSymbols: :void)
((self apropos-window-controller) sender)
(declare (ignore sender))
(with-slots (shows-external-symbols) self
(setf shows-external-symbols (not shows-external-symbols))
(update-symbol-list self)
(update-apropos-array self)))
(objc:defmethod (#/setPackage: :void) ((self apropos-window-controller)
sender)
(with-slots (combo-box package) self
(assert (eql sender combo-box))
(with-slots (packages) sender
(let ((index (#/indexOfSelectedItem sender)))
(if (minusp index)
(setf package nil) ;search all packages
(setf package (svref packages index))))))
(update-symbol-list self)
(update-apropos-array self))
(defmethod update-symbol-list ((self apropos-window-controller))
(with-slots (input package shows-external-symbols symbol-list) self
(when (plusp (length input))
(setf symbol-list nil)
(if package
(if shows-external-symbols
(do-external-symbols (sym package)
(when (ccl::%apropos-substring-p input (symbol-name sym))
(push sym symbol-list)))
(do-symbols (sym package)
(when (ccl::%apropos-substring-p input (symbol-name sym))
(push sym symbol-list))))
(if shows-external-symbols
(dolist (p (list-all-packages))
(do-external-symbols (sym p)
(when (ccl::%apropos-substring-p input (symbol-name sym))
(push sym symbol-list))))
(do-all-symbols (sym)
(when (ccl::%apropos-substring-p input (symbol-name sym))
(push sym symbol-list)))))
(setf symbol-list (sort symbol-list #'string-lessp)))))
(defmethod update-apropos-array ((self apropos-window-controller))
(with-slots (input apropos-array symbol-list package) self
(when (plusp (length input))
(let ((new-array (#/array ns:ns-mutable-array))
(*package* (or package (find-package "COMMON-LISP-USER")))
(n 0))
(dolist (s symbol-list)
(#/addObject: new-array (#/dictionaryWithObjectsAndKeys:
ns:ns-dictionary
(#/autorelease
(%make-nsstring
(prin1-to-string s)))
#@"symbol"
(#/numberWithInt: ns:ns-number n)
#@"index"
(#/autorelease
(%make-nsstring
(inspector::symbol-type-line s)))
#@"kind"
+null-ptr+))
(incf n))
(#/willChangeValueForKey: self #@"aproposArray")
(setf apropos-array new-array)
(#/didChangeValueForKey: self #@"aproposArray")))))
(objc:defmethod (#/apropos: :void) ((self apropos-window-controller) sender)
(let* ((input (lisp-string-from-nsstring (#/stringValue sender))))
(when (and (plusp (length input))
(not (string-equal input (previous-input self))))
(setf (slot-value self 'input) input)
(setf (previous-input self) input)
(update-symbol-list self)
(update-apropos-array self))))
(objc:defmethod (#/inspectSelectedSymbol: :void) ((self apropos-window-controller) sender)
(declare (ignorable sender))
(let* ((row (#/clickedRow (table-view self))))
(unless (minusp row)
(with-slots (array-controller symbol-list) self
(let* ((number (#/valueForKeyPath: array-controller #@"selection.index"))
(i (#/intValue number))
(sym (elt symbol-list i)))
(inspect sym))))))
(objc:defmethod (#/definitionForSelectedSymbol: :void) ((self apropos-window-controller) sender)
(declare (ignorable sender))
(let* ((row (#/clickedRow (table-view self))))
(unless (minusp row)
(with-slots (array-controller symbol-list) self
(let* ((number (#/valueForKeyPath: array-controller #@"selection.index"))
(i (#/intValue number))
(sym (elt symbol-list i)))
(hemlock::edit-definition sym))))))
;;; Data source methods for package combo box
(objc:defmethod (#/numberOfItemsInComboBox: :<NSI>nteger) ((self apropos-window-controller)
combo-box)
(declare (ignore combo-box))
(length (list-all-packages)))
(objc:defmethod #/comboBox:objectValueForItemAtIndex: ((self apropos-window-controller)
combo-box
(index :<NSI>nteger))
(with-slots (packages) combo-box
(let* ((pkg-name (and packages
(package-name (svref packages index)))))
(if pkg-name
(#/autorelease (%make-nsstring pkg-name))
+null-ptr+))))
(objc:defmethod #/comboBox:completedString: ((self apropos-window-controller)
combo-box
partial-string)
(flet ((string-prefix-p (s1 s2)
"Is s1 a prefix of s2?"
(string-equal s1 s2 :end2 (min (length s1) (length s2)))))
(with-slots (packages) combo-box
(let* ((s (lisp-string-from-nsstring partial-string)))
(dotimes (i (length packages) +null-ptr+)
(let ((name (package-name (svref packages i))))
(when (string-prefix-p s name)
(return (#/autorelease (%make-nsstring name))))))))))
(objc:defmethod (#/comboBox:indexOfItemWithStringValue: :<NSUI>nteger)
((self apropos-window-controller)
combo-box
string)
(with-slots (packages) combo-box
(let* ((s (lisp-string-from-nsstring string)))
(or (position s packages :test #'(lambda (str pkg)
(string-equal str (package-name pkg))))
#$NSNotFound))))
;;; Table view delegate methods
(objc:defmethod (#/tableViewSelectionDidChange: :void) ((self apropos-window-controller)
notification)
(with-slots (array-controller symbol-list text-view) self
(let* ((tv (#/object notification))
(row (#/selectedRow tv)))
(unless (minusp row)
(let* ((number (#/valueForKeyPath:
array-controller #@"selection.index"))
(i (#/intValue number))
(sym (elt symbol-list i))
(info (make-array '(0) :element-type 'base-char
:fill-pointer 0 :adjustable t)))
(with-output-to-string (s info)
(dolist (doctype '(compiler-macro function method-combination
setf structure t type variable))
(let ((docstring (documentation sym doctype)))
(when docstring
(format s "~&~a" docstring))
(when (eq doctype 'function)
(format s "~&arglist: ~s" (arglist sym))))))
(if (plusp (length info))
(#/setString: text-view (#/autorelease (%make-nsstring info)))
(#/setString: text-view #@"")))))))
| null | https://raw.githubusercontent.com/Clozure/ccl/6c1a9458f7a5437b73ec227e989aa5b825f32fd3/cocoa-ide/apropos-window.lisp | lisp | -*-Mode: LISP; Package: GUI -*-
Copyright 2007 Clozure Associates
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This is a premature optimization. Instead of calling LIST-ALL-PACKAGES
so frequently, just get a fresh copy when the user clicks in the
combo box.
search all packages
Data source methods for package combo box
Table view delegate methods | distributed under the License is distributed on an " AS IS " BASIS ,
(in-package "GUI")
(defclass package-combo-box (ns:ns-combo-box)
((packages :initform nil))
(:metaclass ns:+ns-object))
(objc:defmethod (#/becomeFirstResponder :<BOOL>) ((self package-combo-box))
(with-slots (packages) self
(setf packages (coerce (list-all-packages) 'vector))
(setf packages (sort packages #'string-lessp :key #'package-name)))
(call-next-method))
(defclass apropos-window-controller (ns:ns-window-controller)
((apropos-array :foreign-type :id :initform +null-ptr+
:reader apropos-array
:documentation "Bound to NSArrayController in nib file")
(array-controller :foreign-type :id :accessor array-controller)
(combo-box :foreign-type :id :accessor combo-box)
(table-view :foreign-type :id :accessor table-view)
(text-view :foreign-type :id :accessor text-view)
(external-symbols-checkbox :foreign-type :id
:accessor external-symbols-checkbox)
(shows-external-symbols :initform nil)
(symbol-list :initform nil)
(package :initform nil)
(input :initform nil)
(previous-input :initform nil :accessor previous-input
:documentation "Last string entered"))
(:metaclass ns:+ns-object))
(defmethod (setf apropos-array) (value (self apropos-window-controller))
(with-slots (apropos-array) self
(unless (eql value apropos-array)
(#/release apropos-array)
(setf apropos-array (#/retain value)))))
Diasable automatic KVO notifications , since having our class swizzled
out from underneath us confuses CLOS . ( Leopard does n't hose us ,
and we can use automatic KVO notifications there . )
(objc:defmethod (#/automaticallyNotifiesObserversForKey: :<BOOL>) ((self +apropos-window-controller)
key)
(declare (ignore key))
nil)
(objc:defmethod (#/awakeFromNib :void) ((self apropos-window-controller))
(with-slots (table-view text-view) self
(#/setString: text-view #@"")
(#/setDelegate: table-view self)
(#/setDoubleAction: table-view (@selector #/definitionForSelectedSymbol:))))
(objc:defmethod #/init ((self apropos-window-controller))
(prog1
(#/initWithWindowNibName: self #@"apropos")
(#/setShouldCascadeWindows: self nil)
(#/setWindowFrameAutosaveName: self #@"apropos panel")
(setf (apropos-array self) (#/array ns:ns-mutable-array))))
(objc:defmethod (#/dealloc :void) ((self apropos-window-controller))
(#/release (slot-value self 'apropos-array))
(call-next-method))
(objc:defmethod (#/toggleShowsExternalSymbols: :void)
((self apropos-window-controller) sender)
(declare (ignore sender))
(with-slots (shows-external-symbols) self
(setf shows-external-symbols (not shows-external-symbols))
(update-symbol-list self)
(update-apropos-array self)))
(objc:defmethod (#/setPackage: :void) ((self apropos-window-controller)
sender)
(with-slots (combo-box package) self
(assert (eql sender combo-box))
(with-slots (packages) sender
(let ((index (#/indexOfSelectedItem sender)))
(if (minusp index)
(setf package (svref packages index))))))
(update-symbol-list self)
(update-apropos-array self))
(defmethod update-symbol-list ((self apropos-window-controller))
(with-slots (input package shows-external-symbols symbol-list) self
(when (plusp (length input))
(setf symbol-list nil)
(if package
(if shows-external-symbols
(do-external-symbols (sym package)
(when (ccl::%apropos-substring-p input (symbol-name sym))
(push sym symbol-list)))
(do-symbols (sym package)
(when (ccl::%apropos-substring-p input (symbol-name sym))
(push sym symbol-list))))
(if shows-external-symbols
(dolist (p (list-all-packages))
(do-external-symbols (sym p)
(when (ccl::%apropos-substring-p input (symbol-name sym))
(push sym symbol-list))))
(do-all-symbols (sym)
(when (ccl::%apropos-substring-p input (symbol-name sym))
(push sym symbol-list)))))
(setf symbol-list (sort symbol-list #'string-lessp)))))
(defmethod update-apropos-array ((self apropos-window-controller))
(with-slots (input apropos-array symbol-list package) self
(when (plusp (length input))
(let ((new-array (#/array ns:ns-mutable-array))
(*package* (or package (find-package "COMMON-LISP-USER")))
(n 0))
(dolist (s symbol-list)
(#/addObject: new-array (#/dictionaryWithObjectsAndKeys:
ns:ns-dictionary
(#/autorelease
(%make-nsstring
(prin1-to-string s)))
#@"symbol"
(#/numberWithInt: ns:ns-number n)
#@"index"
(#/autorelease
(%make-nsstring
(inspector::symbol-type-line s)))
#@"kind"
+null-ptr+))
(incf n))
(#/willChangeValueForKey: self #@"aproposArray")
(setf apropos-array new-array)
(#/didChangeValueForKey: self #@"aproposArray")))))
(objc:defmethod (#/apropos: :void) ((self apropos-window-controller) sender)
(let* ((input (lisp-string-from-nsstring (#/stringValue sender))))
(when (and (plusp (length input))
(not (string-equal input (previous-input self))))
(setf (slot-value self 'input) input)
(setf (previous-input self) input)
(update-symbol-list self)
(update-apropos-array self))))
(objc:defmethod (#/inspectSelectedSymbol: :void) ((self apropos-window-controller) sender)
(declare (ignorable sender))
(let* ((row (#/clickedRow (table-view self))))
(unless (minusp row)
(with-slots (array-controller symbol-list) self
(let* ((number (#/valueForKeyPath: array-controller #@"selection.index"))
(i (#/intValue number))
(sym (elt symbol-list i)))
(inspect sym))))))
(objc:defmethod (#/definitionForSelectedSymbol: :void) ((self apropos-window-controller) sender)
(declare (ignorable sender))
(let* ((row (#/clickedRow (table-view self))))
(unless (minusp row)
(with-slots (array-controller symbol-list) self
(let* ((number (#/valueForKeyPath: array-controller #@"selection.index"))
(i (#/intValue number))
(sym (elt symbol-list i)))
(hemlock::edit-definition sym))))))
(objc:defmethod (#/numberOfItemsInComboBox: :<NSI>nteger) ((self apropos-window-controller)
combo-box)
(declare (ignore combo-box))
(length (list-all-packages)))
(objc:defmethod #/comboBox:objectValueForItemAtIndex: ((self apropos-window-controller)
combo-box
(index :<NSI>nteger))
(with-slots (packages) combo-box
(let* ((pkg-name (and packages
(package-name (svref packages index)))))
(if pkg-name
(#/autorelease (%make-nsstring pkg-name))
+null-ptr+))))
(objc:defmethod #/comboBox:completedString: ((self apropos-window-controller)
combo-box
partial-string)
(flet ((string-prefix-p (s1 s2)
"Is s1 a prefix of s2?"
(string-equal s1 s2 :end2 (min (length s1) (length s2)))))
(with-slots (packages) combo-box
(let* ((s (lisp-string-from-nsstring partial-string)))
(dotimes (i (length packages) +null-ptr+)
(let ((name (package-name (svref packages i))))
(when (string-prefix-p s name)
(return (#/autorelease (%make-nsstring name))))))))))
(objc:defmethod (#/comboBox:indexOfItemWithStringValue: :<NSUI>nteger)
((self apropos-window-controller)
combo-box
string)
(with-slots (packages) combo-box
(let* ((s (lisp-string-from-nsstring string)))
(or (position s packages :test #'(lambda (str pkg)
(string-equal str (package-name pkg))))
#$NSNotFound))))
(objc:defmethod (#/tableViewSelectionDidChange: :void) ((self apropos-window-controller)
notification)
(with-slots (array-controller symbol-list text-view) self
(let* ((tv (#/object notification))
(row (#/selectedRow tv)))
(unless (minusp row)
(let* ((number (#/valueForKeyPath:
array-controller #@"selection.index"))
(i (#/intValue number))
(sym (elt symbol-list i))
(info (make-array '(0) :element-type 'base-char
:fill-pointer 0 :adjustable t)))
(with-output-to-string (s info)
(dolist (doctype '(compiler-macro function method-combination
setf structure t type variable))
(let ((docstring (documentation sym doctype)))
(when docstring
(format s "~&~a" docstring))
(when (eq doctype 'function)
(format s "~&arglist: ~s" (arglist sym))))))
(if (plusp (length info))
(#/setString: text-view (#/autorelease (%make-nsstring info)))
(#/setString: text-view #@"")))))))
|
8dbd55595d1257df5e26a8b7c18b16e75c2c804c9311102cb59cd834fdeadb13 | Ptival/chick | DefinitionObjectKind.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# OPTIONS_GHC -fno - warn - orphans #
module PrettyPrinting.Chick.DefinitionObjectKind where
import Control.Monad.Reader (runReader)
import Data.Default (def)
import DefinitionObjectKind (DefinitionObjectKind (..))
import Language (Language (Chick))
import PrettyPrinting.PrettyPrintable
( PrettyPrintable (prettyDoc),
)
import PrettyPrinting.PrettyPrintableUnannotated
( PrettyPrintableUnannotated (prettyDocU),
)
import Prettyprinter ()
instance PrettyPrintable 'Chick DefinitionObjectKind where
prettyDoc v = runReader (prettyDocU @'Chick v) def
instance PrettyPrintableUnannotated 'Chick DefinitionObjectKind where
prettyDocU = \case
Definition -> return "Definition"
Fixpoint -> return "Fixpoint"
| null | https://raw.githubusercontent.com/Ptival/chick/a5ce39a842ff72348f1c9cea303997d5300163e2/backend/lib/PrettyPrinting/Chick/DefinitionObjectKind.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# OPTIONS_GHC -fno - warn - orphans #
module PrettyPrinting.Chick.DefinitionObjectKind where
import Control.Monad.Reader (runReader)
import Data.Default (def)
import DefinitionObjectKind (DefinitionObjectKind (..))
import Language (Language (Chick))
import PrettyPrinting.PrettyPrintable
( PrettyPrintable (prettyDoc),
)
import PrettyPrinting.PrettyPrintableUnannotated
( PrettyPrintableUnannotated (prettyDocU),
)
import Prettyprinter ()
instance PrettyPrintable 'Chick DefinitionObjectKind where
prettyDoc v = runReader (prettyDocU @'Chick v) def
instance PrettyPrintableUnannotated 'Chick DefinitionObjectKind where
prettyDocU = \case
Definition -> return "Definition"
Fixpoint -> return "Fixpoint"
|
4d8696fee422bb5393bbf0be9a6c5a9c3d981953b9acaa0925d2d5bec7809aba | tlaplus/tlapm | mltoll.mli | Copyright 2004 INRIA
val translate : string -> Phrase.phrase list -> Mlproof.proof -> Llproof.proof;;
val is_meta : string -> bool;;
val get_meta_type : string -> string;;
| null | https://raw.githubusercontent.com/tlaplus/tlapm/b82e2fd049c5bc1b14508ae16890666c6928975f/zenon/mltoll.mli | ocaml | Copyright 2004 INRIA
val translate : string -> Phrase.phrase list -> Mlproof.proof -> Llproof.proof;;
val is_meta : string -> bool;;
val get_meta_type : string -> string;;
|
|
3488e3a0fc98fe5d9a0caf7108f92fe1a5d3312417368fcd6ffb80291ef605b4 | melisgl/try | testable.lisp | (in-package :try)
(defsection @try/testables (:title "Testables")
"Valid first arguments to TRY are called testables. A testable may
be:
- a @FUNCTION-DESIGNATOR
- the name of a global test
- the name of a global function
- a function object
- a trial
- a list of testables
- a PACKAGE
In the function designator cases, TRY calls the designated function.
TRIALs, being @FUNCALLABLE-INSTANCEs, designate themselves. If the
trial is not RUNNINGP, then it will be rerun (see @TRY/RERUN). Don't
invoke TRY with RUNNINGP trials (but see
@TRY/IMPLICIT-TRY-IMPLEMENTATION for discussion).
When given a list of testables, TRY calls each testable one by one.
Finally, a PACKAGE stands for the result of calling
LIST-PACKAGE-TESTS on that package.")
(defun call-testable (testable)
(multiple-value-bind (function-designators wrapper-cform)
(list-function-designators testable)
(if wrapper-cform
(call-with-wrapper function-designators wrapper-cform)
(destructuring-bind (function-designator) function-designators
(funcall function-designator)))))
(defun call-with-wrapper (function-designators wrapper-cform)
(let ((wrapper (make-instance 'trial
'%test-name wrapper-cform
:cform wrapper-cform)))
(with-trial (wrapper)
(wrap-trial-body-for-return nil
(mapc #'funcall function-designators)))))
Return two values :
;;;
1 . A list of FUNCTION - DESIGNATORs to be called with no arguments
for this TESTABLE . For example , if TESTABLE is a package , then
;;; it is the list of symbols in that package with DEFTEST
definitions . If TESTABLE is a FUNCTION - DESIGNATOR ( including
) , then it is returned as ( LIST TESTABLE ) .
;;;
2 . A CFORM for an extra trial to wrap around the calls to the
function designators in the first value to ensure that all
;;; events are produced within a trial. If no wrapping is required,
then this is NIL . When CFORM is executed , it must rerun the
;;; equivalent of (TRY TESTABLE), hence in most cases that's
;;; exactly what's returned.
(defun list-function-designators (testable)
(cond ((null testable)
;; Do nothing in an extra trial.
(values () `(try ())))
((and (symbolp testable) (test-bound-p testable))
;; DEFTEST establishes a trial. No need for wrapping.
(values `(,testable) nil))
;; We can't return a TRY-TRIAL as the function-designator
;; because when funcalled it would lead us back here and to
;; infinite recursion.
((trialp testable)
(if (try-trial-p testable)
(let ((previous-testable (try-trial-testable testable)))
(assert (not (and (trialp previous-testable)
(try-trial-p previous-testable))))
(values (list-function-designators previous-testable)
`(try ,previous-testable)))
;; Named and lambda trials
(values `(,testable) nil)))
((or (and (symbolp testable) (fboundp testable))
;; TRIALs are funcallable thus FUNCTIONP so except for
;; TRY-TRIALs handled above) trials end up here.
(functionp testable))
(values (list testable) `(try ,testable)))
((symbolp testable)
(error "~S is not testable because it is not ~S." testable 'fboundp))
((listp testable)
(values (mapcan #'list-function-designators testable)
`(try ,testable)))
((packagep testable)
(values (list-package-tests testable)
`(try ,testable)))
(t
(error "~S is not testable." testable))))
| null | https://raw.githubusercontent.com/melisgl/try/a37c61f8b81d4bdf38f559bca54eef3868bb87a1/src/testable.lisp | lisp |
it is the list of symbols in that package with DEFTEST
events are produced within a trial. If no wrapping is required,
equivalent of (TRY TESTABLE), hence in most cases that's
exactly what's returned.
Do nothing in an extra trial.
DEFTEST establishes a trial. No need for wrapping.
We can't return a TRY-TRIAL as the function-designator
because when funcalled it would lead us back here and to
infinite recursion.
Named and lambda trials
TRIALs are funcallable thus FUNCTIONP so except for
TRY-TRIALs handled above) trials end up here. | (in-package :try)
(defsection @try/testables (:title "Testables")
"Valid first arguments to TRY are called testables. A testable may
be:
- a @FUNCTION-DESIGNATOR
- the name of a global test
- the name of a global function
- a function object
- a trial
- a list of testables
- a PACKAGE
In the function designator cases, TRY calls the designated function.
TRIALs, being @FUNCALLABLE-INSTANCEs, designate themselves. If the
trial is not RUNNINGP, then it will be rerun (see @TRY/RERUN). Don't
invoke TRY with RUNNINGP trials (but see
@TRY/IMPLICIT-TRY-IMPLEMENTATION for discussion).
When given a list of testables, TRY calls each testable one by one.
Finally, a PACKAGE stands for the result of calling
LIST-PACKAGE-TESTS on that package.")
(defun call-testable (testable)
(multiple-value-bind (function-designators wrapper-cform)
(list-function-designators testable)
(if wrapper-cform
(call-with-wrapper function-designators wrapper-cform)
(destructuring-bind (function-designator) function-designators
(funcall function-designator)))))
(defun call-with-wrapper (function-designators wrapper-cform)
(let ((wrapper (make-instance 'trial
'%test-name wrapper-cform
:cform wrapper-cform)))
(with-trial (wrapper)
(wrap-trial-body-for-return nil
(mapc #'funcall function-designators)))))
Return two values :
1 . A list of FUNCTION - DESIGNATORs to be called with no arguments
for this TESTABLE . For example , if TESTABLE is a package , then
definitions . If TESTABLE is a FUNCTION - DESIGNATOR ( including
) , then it is returned as ( LIST TESTABLE ) .
2 . A CFORM for an extra trial to wrap around the calls to the
function designators in the first value to ensure that all
then this is NIL . When CFORM is executed , it must rerun the
(defun list-function-designators (testable)
(cond ((null testable)
(values () `(try ())))
((and (symbolp testable) (test-bound-p testable))
(values `(,testable) nil))
((trialp testable)
(if (try-trial-p testable)
(let ((previous-testable (try-trial-testable testable)))
(assert (not (and (trialp previous-testable)
(try-trial-p previous-testable))))
(values (list-function-designators previous-testable)
`(try ,previous-testable)))
(values `(,testable) nil)))
((or (and (symbolp testable) (fboundp testable))
(functionp testable))
(values (list testable) `(try ,testable)))
((symbolp testable)
(error "~S is not testable because it is not ~S." testable 'fboundp))
((listp testable)
(values (mapcan #'list-function-designators testable)
`(try ,testable)))
((packagep testable)
(values (list-package-tests testable)
`(try ,testable)))
(t
(error "~S is not testable." testable))))
|
5e9136ce339088c62b9b7a3dad488ce81e79333aac0c5e886533c8e19050bdd4 | Frama-C/Frama-C-snapshot | TacChoice.mli | (**************************************************************************)
(* *)
This file is part of WP plug - in of Frama - C.
(* *)
Copyright ( C ) 2007 - 2019
CEA ( Commissariat a l'energie atomique et aux energies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
* Built - in Choice , Absurd & Contrapose Tactical ( auto - registered )
open Tactical
open Strategy
module Choice :
sig
val tactical : tactical
val strategy : ?priority:float -> selection -> strategy
end
module Absurd :
sig
val tactical : tactical
val strategy : ?priority:float -> selection -> strategy
end
module Contrapose :
sig
val tactical : tactical
val strategy : ?priority:float -> selection -> strategy
end
| null | https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/wp/TacChoice.mli | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************ | This file is part of WP plug - in of Frama - C.
Copyright ( C ) 2007 - 2019
CEA ( Commissariat a l'energie atomique et aux energies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
* Built - in Choice , Absurd & Contrapose Tactical ( auto - registered )
open Tactical
open Strategy
module Choice :
sig
val tactical : tactical
val strategy : ?priority:float -> selection -> strategy
end
module Absurd :
sig
val tactical : tactical
val strategy : ?priority:float -> selection -> strategy
end
module Contrapose :
sig
val tactical : tactical
val strategy : ?priority:float -> selection -> strategy
end
|
0bac22aa86bd4f5cb23348af7f566923c0a161b6ad9fac1bf3c9ce7bc62ec006 | avsm/mirage-duniverse | config.ml | open Nocrypto
open Utils
open Core
open Sexplib.Std
type certchain = X509.t list * Rsa.priv [@@deriving sexp]
type own_cert = [
| `None
| `Single of certchain
| `Multiple of certchain list
| `Multiple_default of certchain * certchain list
] [@@deriving sexp]
type session_cache = SessionID.t -> epoch_data option
let session_cache_of_sexp _ = fun _ -> None
let sexp_of_session_cache _ = Sexplib.Sexp.Atom "SESSION_CACHE"
type config = {
ciphers : Ciphersuite.ciphersuite list ;
protocol_versions : tls_version * tls_version ;
hashes : Hash.hash list ;
(* signatures : Packet.signature_algorithm_type list ; *)
use_reneg : bool ;
authenticator : X509.Authenticator.a option ;
peer_name : string option ;
own_certificates : own_cert ;
acceptable_cas : X509.distinguished_name list ;
session_cache : session_cache ;
cached_session : epoch_data option ;
alpn_protocols : string list ;
} [@@deriving sexp]
module Ciphers = struct
(* A good place for various pre-baked cipher lists and helper functions to
* slice and groom those lists. *)
let default = [
`TLS_DHE_RSA_WITH_AES_256_CCM ;
`TLS_DHE_RSA_WITH_AES_128_CCM ;
`TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 ;
`TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 ;
`TLS_DHE_RSA_WITH_AES_256_CBC_SHA ;
`TLS_DHE_RSA_WITH_AES_128_CBC_SHA ;
`TLS_RSA_WITH_AES_256_CCM ;
`TLS_RSA_WITH_AES_128_CCM ;
`TLS_RSA_WITH_AES_256_CBC_SHA256 ;
`TLS_RSA_WITH_AES_128_CBC_SHA256 ;
`TLS_RSA_WITH_AES_256_CBC_SHA ;
`TLS_RSA_WITH_AES_128_CBC_SHA ;
]
let supported = default @ [
`TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 ;
`TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 ;
`TLS_RSA_WITH_AES_256_GCM_SHA384 ;
`TLS_RSA_WITH_AES_128_GCM_SHA256 ;
`TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA ;
`TLS_RSA_WITH_3DES_EDE_CBC_SHA ;
`TLS_RSA_WITH_RC4_128_SHA ;
`TLS_RSA_WITH_RC4_128_MD5
]
let fs_of = List.filter Ciphersuite.ciphersuite_fs
let fs = fs_of default
end
let default_hashes =
[ `SHA512 ; `SHA384 ; `SHA256 ; `SHA224 ; `SHA1 ]
let supported_hashes =
default_hashes @ [ `MD5 ]
let min_dh_size = 1024
let min_rsa_key_size = 1024
ff - dhe draft 2048 - bit group
let default_config = {
ciphers = Ciphers.default ;
protocol_versions = (TLS_1_0, TLS_1_2) ;
hashes = default_hashes ;
use_reneg = false ;
authenticator = None ;
peer_name = None ;
own_certificates = `None ;
acceptable_cas = [] ;
session_cache = (fun _ -> None) ;
cached_session = None ;
alpn_protocols = [] ;
}
let invalid msg = invalid_arg ("Tls.Config: invalid configuration: " ^ msg)
let validate_common config =
let (v_min, v_max) = config.protocol_versions in
if v_max < v_min then invalid "bad version range" ;
( match config.hashes with
| [] when v_max >= TLS_1_2 ->
invalid "TLS 1.2 configured but no hashes provided"
| hs when not (List_set.subset hs supported_hashes) ->
invalid "Some hash algorithms are not supported"
| _ ->
() ) ;
if not (List_set.is_proper_set config.ciphers) then
invalid "set of ciphers is not a proper set" ;
if List.length config.ciphers = 0 then
invalid "set of ciphers is empty" ;
if List.exists (fun proto -> let len = String.length proto in len = 0 || len > 255) config.alpn_protocols then
invalid "invalid alpn protocol" ;
if List.length config.alpn_protocols > 0xffff then
invalid "alpn protocols list too large"
module CertTypeUsageOrdered = struct
type t = X509.key_type * X509.Extension.key_usage
let compare = compare
end
module CertTypeUsageSet = Set.Make(CertTypeUsageOrdered)
let validate_certificate_chain = function
| (s::chain, priv) ->
let pub = Rsa.pub_of_priv priv in
if Rsa.pub_bits pub < min_rsa_key_size then
invalid "RSA key too short!" ;
( match X509.public_key s with
| `RSA pub' when pub = pub' -> ()
| _ -> invalid "public / private key combination" ) ;
( match init_and_last chain with
| Some (ch, trust) ->
(* TODO: verify that certificates are x509 v3 if TLS_1_2 *)
( match X509.Validation.verify_chain_of_trust ~anchors:[trust] (s :: ch) with
| `Ok _ -> ()
| `Fail x -> invalid ("certificate chain does not validate: " ^
(X509.Validation.validation_error_to_string x)) )
| None -> () )
| _ -> invalid "certificate"
let validate_client config =
match config.own_certificates with
| `None -> ()
| `Single c -> validate_certificate_chain c
| _ -> invalid_arg "multiple client certificates not supported in client config"
module StringSet = Set.Make(String)
let non_overlapping cs =
let namessets =
let nameslists =
filter_map cs ~f:(function
| (s :: _, _) -> Some s
| _ -> None)
|> List.map X509.hostnames
in
List.map (fun xs -> List.fold_right StringSet.add xs StringSet.empty) nameslists
in
let rec check = function
| [] -> ()
| s::ss -> if not (List.for_all
(fun ss' -> StringSet.is_empty (StringSet.inter s ss'))
ss)
then
invalid_arg "overlapping names in certificates"
else
check ss
in
check namessets
let validate_server config =
let open Ciphersuite in
let typeusage =
let tylist =
List.map ciphersuite_kex config.ciphers |>
List.filter needs_certificate |>
List.map required_keytype_and_usage
in
List.fold_right CertTypeUsageSet.add tylist CertTypeUsageSet.empty
and certificate_chains =
match config.own_certificates with
| `Single c -> [c]
| `Multiple cs -> cs
| `Multiple_default (c, cs) -> c :: cs
| `None -> []
in
let server_certs =
List.map (function
| (s::_,_) -> s
| _ -> invalid "empty certificate chain")
certificate_chains
in
if
not (CertTypeUsageSet.for_all
(fun (t, u) ->
List.exists (fun c ->
X509.supports_keytype c t &&
X509.Extension.supports_usage ~not_present:true c u)
server_certs)
typeusage)
then
invalid "certificate type or usage does not match" ;
List.iter validate_certificate_chain certificate_chains ;
( match config.own_certificates with
| `Multiple cs -> non_overlapping cs
| `Multiple_default (_, cs) -> non_overlapping cs
| _ -> () )
(* TODO: verify that certificates are x509 v3 if TLS_1_2 *)
type client = config [@@deriving sexp]
type server = config [@@deriving sexp]
let of_server conf = conf
and of_client conf = conf
let peer conf name = { conf with peer_name = Some name }
let with_authenticator conf auth = { conf with authenticator = Some auth }
let with_own_certificates conf own_certificates = { conf with own_certificates }
let with_acceptable_cas conf acceptable_cas = { conf with acceptable_cas }
let (<?>) ma b = match ma with None -> b | Some a -> a
let client
~authenticator ?peer_name ?ciphers ?version ?hashes ?reneg ?certificates ?cached_session ?alpn_protocols () =
let config =
{ default_config with
authenticator = Some authenticator ;
ciphers = ciphers <?> default_config.ciphers ;
protocol_versions = version <?> default_config.protocol_versions ;
hashes = hashes <?> default_config.hashes ;
use_reneg = reneg <?> default_config.use_reneg ;
own_certificates = certificates <?> default_config.own_certificates ;
peer_name = peer_name ;
cached_session = cached_session ;
alpn_protocols = alpn_protocols <?> default_config.alpn_protocols ;
} in
( validate_common config ; validate_client config ; config )
let server
?ciphers ?version ?hashes ?reneg ?certificates ?acceptable_cas ?authenticator ?session_cache ?alpn_protocols () =
let config =
{ default_config with
ciphers = ciphers <?> default_config.ciphers ;
protocol_versions = version <?> default_config.protocol_versions ;
hashes = hashes <?> default_config.hashes ;
use_reneg = reneg <?> default_config.use_reneg ;
own_certificates = certificates <?> default_config.own_certificates ;
acceptable_cas = acceptable_cas <?> default_config.acceptable_cas ;
authenticator = authenticator ;
session_cache = session_cache <?> default_config.session_cache ;
alpn_protocols = alpn_protocols <?> default_config.alpn_protocols ;
} in
( validate_common config ; validate_server config ; config )
| null | https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/tls/lib/config.ml | ocaml | signatures : Packet.signature_algorithm_type list ;
A good place for various pre-baked cipher lists and helper functions to
* slice and groom those lists.
TODO: verify that certificates are x509 v3 if TLS_1_2
TODO: verify that certificates are x509 v3 if TLS_1_2 | open Nocrypto
open Utils
open Core
open Sexplib.Std
type certchain = X509.t list * Rsa.priv [@@deriving sexp]
type own_cert = [
| `None
| `Single of certchain
| `Multiple of certchain list
| `Multiple_default of certchain * certchain list
] [@@deriving sexp]
type session_cache = SessionID.t -> epoch_data option
let session_cache_of_sexp _ = fun _ -> None
let sexp_of_session_cache _ = Sexplib.Sexp.Atom "SESSION_CACHE"
type config = {
ciphers : Ciphersuite.ciphersuite list ;
protocol_versions : tls_version * tls_version ;
hashes : Hash.hash list ;
use_reneg : bool ;
authenticator : X509.Authenticator.a option ;
peer_name : string option ;
own_certificates : own_cert ;
acceptable_cas : X509.distinguished_name list ;
session_cache : session_cache ;
cached_session : epoch_data option ;
alpn_protocols : string list ;
} [@@deriving sexp]
module Ciphers = struct
let default = [
`TLS_DHE_RSA_WITH_AES_256_CCM ;
`TLS_DHE_RSA_WITH_AES_128_CCM ;
`TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 ;
`TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 ;
`TLS_DHE_RSA_WITH_AES_256_CBC_SHA ;
`TLS_DHE_RSA_WITH_AES_128_CBC_SHA ;
`TLS_RSA_WITH_AES_256_CCM ;
`TLS_RSA_WITH_AES_128_CCM ;
`TLS_RSA_WITH_AES_256_CBC_SHA256 ;
`TLS_RSA_WITH_AES_128_CBC_SHA256 ;
`TLS_RSA_WITH_AES_256_CBC_SHA ;
`TLS_RSA_WITH_AES_128_CBC_SHA ;
]
let supported = default @ [
`TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 ;
`TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 ;
`TLS_RSA_WITH_AES_256_GCM_SHA384 ;
`TLS_RSA_WITH_AES_128_GCM_SHA256 ;
`TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA ;
`TLS_RSA_WITH_3DES_EDE_CBC_SHA ;
`TLS_RSA_WITH_RC4_128_SHA ;
`TLS_RSA_WITH_RC4_128_MD5
]
let fs_of = List.filter Ciphersuite.ciphersuite_fs
let fs = fs_of default
end
let default_hashes =
[ `SHA512 ; `SHA384 ; `SHA256 ; `SHA224 ; `SHA1 ]
let supported_hashes =
default_hashes @ [ `MD5 ]
let min_dh_size = 1024
let min_rsa_key_size = 1024
ff - dhe draft 2048 - bit group
let default_config = {
ciphers = Ciphers.default ;
protocol_versions = (TLS_1_0, TLS_1_2) ;
hashes = default_hashes ;
use_reneg = false ;
authenticator = None ;
peer_name = None ;
own_certificates = `None ;
acceptable_cas = [] ;
session_cache = (fun _ -> None) ;
cached_session = None ;
alpn_protocols = [] ;
}
let invalid msg = invalid_arg ("Tls.Config: invalid configuration: " ^ msg)
let validate_common config =
let (v_min, v_max) = config.protocol_versions in
if v_max < v_min then invalid "bad version range" ;
( match config.hashes with
| [] when v_max >= TLS_1_2 ->
invalid "TLS 1.2 configured but no hashes provided"
| hs when not (List_set.subset hs supported_hashes) ->
invalid "Some hash algorithms are not supported"
| _ ->
() ) ;
if not (List_set.is_proper_set config.ciphers) then
invalid "set of ciphers is not a proper set" ;
if List.length config.ciphers = 0 then
invalid "set of ciphers is empty" ;
if List.exists (fun proto -> let len = String.length proto in len = 0 || len > 255) config.alpn_protocols then
invalid "invalid alpn protocol" ;
if List.length config.alpn_protocols > 0xffff then
invalid "alpn protocols list too large"
module CertTypeUsageOrdered = struct
type t = X509.key_type * X509.Extension.key_usage
let compare = compare
end
module CertTypeUsageSet = Set.Make(CertTypeUsageOrdered)
let validate_certificate_chain = function
| (s::chain, priv) ->
let pub = Rsa.pub_of_priv priv in
if Rsa.pub_bits pub < min_rsa_key_size then
invalid "RSA key too short!" ;
( match X509.public_key s with
| `RSA pub' when pub = pub' -> ()
| _ -> invalid "public / private key combination" ) ;
( match init_and_last chain with
| Some (ch, trust) ->
( match X509.Validation.verify_chain_of_trust ~anchors:[trust] (s :: ch) with
| `Ok _ -> ()
| `Fail x -> invalid ("certificate chain does not validate: " ^
(X509.Validation.validation_error_to_string x)) )
| None -> () )
| _ -> invalid "certificate"
let validate_client config =
match config.own_certificates with
| `None -> ()
| `Single c -> validate_certificate_chain c
| _ -> invalid_arg "multiple client certificates not supported in client config"
module StringSet = Set.Make(String)
let non_overlapping cs =
let namessets =
let nameslists =
filter_map cs ~f:(function
| (s :: _, _) -> Some s
| _ -> None)
|> List.map X509.hostnames
in
List.map (fun xs -> List.fold_right StringSet.add xs StringSet.empty) nameslists
in
let rec check = function
| [] -> ()
| s::ss -> if not (List.for_all
(fun ss' -> StringSet.is_empty (StringSet.inter s ss'))
ss)
then
invalid_arg "overlapping names in certificates"
else
check ss
in
check namessets
let validate_server config =
let open Ciphersuite in
let typeusage =
let tylist =
List.map ciphersuite_kex config.ciphers |>
List.filter needs_certificate |>
List.map required_keytype_and_usage
in
List.fold_right CertTypeUsageSet.add tylist CertTypeUsageSet.empty
and certificate_chains =
match config.own_certificates with
| `Single c -> [c]
| `Multiple cs -> cs
| `Multiple_default (c, cs) -> c :: cs
| `None -> []
in
let server_certs =
List.map (function
| (s::_,_) -> s
| _ -> invalid "empty certificate chain")
certificate_chains
in
if
not (CertTypeUsageSet.for_all
(fun (t, u) ->
List.exists (fun c ->
X509.supports_keytype c t &&
X509.Extension.supports_usage ~not_present:true c u)
server_certs)
typeusage)
then
invalid "certificate type or usage does not match" ;
List.iter validate_certificate_chain certificate_chains ;
( match config.own_certificates with
| `Multiple cs -> non_overlapping cs
| `Multiple_default (_, cs) -> non_overlapping cs
| _ -> () )
type client = config [@@deriving sexp]
type server = config [@@deriving sexp]
let of_server conf = conf
and of_client conf = conf
let peer conf name = { conf with peer_name = Some name }
let with_authenticator conf auth = { conf with authenticator = Some auth }
let with_own_certificates conf own_certificates = { conf with own_certificates }
let with_acceptable_cas conf acceptable_cas = { conf with acceptable_cas }
let (<?>) ma b = match ma with None -> b | Some a -> a
let client
~authenticator ?peer_name ?ciphers ?version ?hashes ?reneg ?certificates ?cached_session ?alpn_protocols () =
let config =
{ default_config with
authenticator = Some authenticator ;
ciphers = ciphers <?> default_config.ciphers ;
protocol_versions = version <?> default_config.protocol_versions ;
hashes = hashes <?> default_config.hashes ;
use_reneg = reneg <?> default_config.use_reneg ;
own_certificates = certificates <?> default_config.own_certificates ;
peer_name = peer_name ;
cached_session = cached_session ;
alpn_protocols = alpn_protocols <?> default_config.alpn_protocols ;
} in
( validate_common config ; validate_client config ; config )
let server
?ciphers ?version ?hashes ?reneg ?certificates ?acceptable_cas ?authenticator ?session_cache ?alpn_protocols () =
let config =
{ default_config with
ciphers = ciphers <?> default_config.ciphers ;
protocol_versions = version <?> default_config.protocol_versions ;
hashes = hashes <?> default_config.hashes ;
use_reneg = reneg <?> default_config.use_reneg ;
own_certificates = certificates <?> default_config.own_certificates ;
acceptable_cas = acceptable_cas <?> default_config.acceptable_cas ;
authenticator = authenticator ;
session_cache = session_cache <?> default_config.session_cache ;
alpn_protocols = alpn_protocols <?> default_config.alpn_protocols ;
} in
( validate_common config ; validate_server config ; config )
|
b8375c80904db5f25cc6a82c61a5e1872b81be3e1aa1a2bdc9e897d40851f1a5 | xoken/xoken-node | Service.hs | module Network.Xoken.Node.Service
( module X
) where
import Network.Xoken.Node.Service.Address as X
import Network.Xoken.Node.Service.Allegory as X
import Network.Xoken.Node.Service.Block as X
import Network.Xoken.Node.Service.Chain as X
import Network.Xoken.Node.Service.Transaction as X
import Network.Xoken.Node.Service.User as X
| null | https://raw.githubusercontent.com/xoken/xoken-node/99124fbe1b1cb9c2fc442c788c7c2bac06f5e900/node/src/Network/Xoken/Node/Service.hs | haskell | module Network.Xoken.Node.Service
( module X
) where
import Network.Xoken.Node.Service.Address as X
import Network.Xoken.Node.Service.Allegory as X
import Network.Xoken.Node.Service.Block as X
import Network.Xoken.Node.Service.Chain as X
import Network.Xoken.Node.Service.Transaction as X
import Network.Xoken.Node.Service.User as X
|
|
2ec044128af2831787bea6e938f8cca7c5f753ea52fdc0ccee3b5fe21eced8f6 | dwayne/eopl3 | parser.rkt | #lang eopl
;; Program ::= Expression
;;
;; Expression ::= Number
;;
;; ::= Identifier
;;
;; ::= -(Expression, Expression)
;;
;; ::= zero?(Expression)
;;
;; ::= if Expression then Expression else Expression
;;
;; ::= let Identifier = Expression in Expression
;;
;; ::= proc (Identifier) Expression
;;
;; ::= (Expression Expression)
(provide
AST
program
a-program
expression expression?
const-exp
var-exp
diff-exp
zero?-exp
if-exp
let-exp
proc-exp
call-exp
Parser
parse)
(define scanner-spec
'((number (digit (arbno digit)) number)
(identifier (letter (arbno letter)) symbol)
(ws ((arbno whitespace)) skip)))
(define grammar
'((program (expression)
a-program)
(expression (number)
const-exp)
(expression (identifier)
var-exp)
(expression ("-" "(" expression "," expression ")")
diff-exp)
(expression ("zero?" "(" expression ")")
zero?-exp)
(expression ("if" expression "then" expression "else" expression)
if-exp)
(expression ("let" identifier "=" expression "in" expression)
let-exp)
(expression ("proc" "(" identifier ")" expression)
proc-exp)
(expression ("(" expression expression ")")
call-exp)))
(sllgen:make-define-datatypes scanner-spec grammar)
(define parse
(sllgen:make-string-parser scanner-spec grammar))
| null | https://raw.githubusercontent.com/dwayne/eopl3/9d5fdb2a8dafac3bc48852d49cda8b83e7a825cf/solutions/03-ch3/interpreters/racket/PROC-3.26/parser.rkt | racket | Program ::= Expression
Expression ::= Number
::= Identifier
::= -(Expression, Expression)
::= zero?(Expression)
::= if Expression then Expression else Expression
::= let Identifier = Expression in Expression
::= proc (Identifier) Expression
::= (Expression Expression) | #lang eopl
(provide
AST
program
a-program
expression expression?
const-exp
var-exp
diff-exp
zero?-exp
if-exp
let-exp
proc-exp
call-exp
Parser
parse)
(define scanner-spec
'((number (digit (arbno digit)) number)
(identifier (letter (arbno letter)) symbol)
(ws ((arbno whitespace)) skip)))
(define grammar
'((program (expression)
a-program)
(expression (number)
const-exp)
(expression (identifier)
var-exp)
(expression ("-" "(" expression "," expression ")")
diff-exp)
(expression ("zero?" "(" expression ")")
zero?-exp)
(expression ("if" expression "then" expression "else" expression)
if-exp)
(expression ("let" identifier "=" expression "in" expression)
let-exp)
(expression ("proc" "(" identifier ")" expression)
proc-exp)
(expression ("(" expression expression ")")
call-exp)))
(sllgen:make-define-datatypes scanner-spec grammar)
(define parse
(sllgen:make-string-parser scanner-spec grammar))
|
a85c16ba779f777960a503f1089d37ff9eeb24fa8bedfec4b3e1640804cab62c | TrustInSoft/tis-interpreter | source_manager.mli | Modified by TrustInSoft
(**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
(** The source viewer multi-tabs widget window. *)
type t
val selection_locked : bool ref
* Prevents the filetree callback from resetting the selected line when it
was selected via a click in the original source viewer .
was selected via a click in the original source viewer. *)
val make:
?tab_pos:Gtk.Tags.position -> ?packing:(GObj.widget -> unit) -> unit -> t
val load_file:
t -> ?title:string -> filename:string -> ?line:int ->
click_cb:(Pretty_source.localizable option -> unit) -> unit -> unit
* If [ line ] is 0 then the last line of the text is shown .
If [ line ] is less that 0 then no scrolling occurs ( default ) .
If [ title ] is not provided the page title is the filename .
[ ] is a callback called whenever the user clicks on the
original source code . This callback is given the localizable that the
user clicked on , if any was found . This localizable is estimated from
a reverse mapping from the original source to the source , and not
always exact .
If [line] is less that 0 then no scrolling occurs (default).
If [title] is not provided the page title is the filename.
[click_cb] is a callback called whenever the user clicks on the
original source code. This callback is given the localizable that the
user clicked on, if any was found. This localizable is estimated from
a reverse mapping from the original source to the Cil source, and not
always exact. *)
val select_file: t -> string -> unit (** Selection by page filename *)
val select_name: t -> string -> unit (** Selection by page title *)
val get_current_source_view : t -> GSourceView2.source_view
(** Returns the source viewer for the currently displayed tab *)
val clear : t -> unit
(** Remove all pages added by [load_file] *)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/gui/source_manager.mli | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
* The source viewer multi-tabs widget window.
* Selection by page filename
* Selection by page title
* Returns the source viewer for the currently displayed tab
* Remove all pages added by [load_file] | Modified by TrustInSoft
This file is part of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
type t
val selection_locked : bool ref
* Prevents the filetree callback from resetting the selected line when it
was selected via a click in the original source viewer .
was selected via a click in the original source viewer. *)
val make:
?tab_pos:Gtk.Tags.position -> ?packing:(GObj.widget -> unit) -> unit -> t
val load_file:
t -> ?title:string -> filename:string -> ?line:int ->
click_cb:(Pretty_source.localizable option -> unit) -> unit -> unit
* If [ line ] is 0 then the last line of the text is shown .
If [ line ] is less that 0 then no scrolling occurs ( default ) .
If [ title ] is not provided the page title is the filename .
[ ] is a callback called whenever the user clicks on the
original source code . This callback is given the localizable that the
user clicked on , if any was found . This localizable is estimated from
a reverse mapping from the original source to the source , and not
always exact .
If [line] is less that 0 then no scrolling occurs (default).
If [title] is not provided the page title is the filename.
[click_cb] is a callback called whenever the user clicks on the
original source code. This callback is given the localizable that the
user clicked on, if any was found. This localizable is estimated from
a reverse mapping from the original source to the Cil source, and not
always exact. *)
val get_current_source_view : t -> GSourceView2.source_view
val clear : t -> unit
|
415ec5ace6f99fed8e9f9a18d4ce70e82f07d25dc3419afd3fb40c5363beecdd | ghc/nofib | TypeCheck5.hs |
-- ==========================================================--
= = = A type - checker -- v5 File : TypeCheck5.m ( 1 ) = = = --
-- === Corrected version for 0.210a ===--
-- ==========================================================--
module TypeCheck5 where
import BaseDefs
import Utils
import MyUtils
1.3
-- ==========================================================--
-- === Formatting of results ===--
-- ==========================================================--
tcMapAnnExpr :: (a -> b) ->
AnnExpr c a ->
AnnExpr c b
tcMapAnnExpr f (ann, node)
= (f ann, mapAnnExpr' node)
where
mapAnnExpr' (AVar v) = AVar v
mapAnnExpr' (ANum n) = ANum n
mapAnnExpr' (AConstr c) = AConstr c
mapAnnExpr' (AAp ae1 ae2)
= AAp (tcMapAnnExpr f ae1) (tcMapAnnExpr f ae2)
mapAnnExpr' (ALet recFlag annDefs mainExpr)
= ALet recFlag (map mapAnnDefn annDefs) (tcMapAnnExpr f mainExpr)
mapAnnExpr' (ACase switchExpr annAlts)
= ACase (tcMapAnnExpr f switchExpr) (map mapAnnAlt annAlts)
mapAnnExpr' (ALam vs e) = ALam vs (tcMapAnnExpr f e)
mapAnnDefn (naam, expr)
= (naam, tcMapAnnExpr f expr)
mapAnnAlt (naam, (pars, resExpr))
= (naam, (pars, tcMapAnnExpr f resExpr))
-- ======================================================--
--
tcSubstAnnTree :: Subst ->
AnnExpr Naam TExpr ->
AnnExpr Naam TExpr
tcSubstAnnTree phi tree = tcMapAnnExpr (tcSub_type phi) tree
-- ======================================================--
--
tcTreeToEnv :: AnnExpr Naam TExpr ->
TypeEnv
tcTreeToEnv tree
= t2e tree
where
t2e (nodeType, node) = t2e' node
t2e' (AVar v) = []
t2e' (ANum n) = []
t2e' (AConstr c) = []
t2e' (AAp ae1 ae2) = (t2e ae1) ++ (t2e ae2)
t2e' (ALam cs e) = t2e e
t2e' (ALet rf dl me)
= (concat (map aFN dl)) ++ (t2e me)
t2e' (ACase sw alts)
= (t2e sw) ++ (concat (map (t2e.second.second) alts))
aFN (naam, (tijp, body))
= (naam, tijp):(t2e' body)
-- ======================================================--
--
tcShowtExpr :: TExpr ->
[Char]
tcShowtExpr t
= pretty' False t
where
pretty' b (TVar tvname) = [' ', toEnum (96+(lookup tvname tvdict))]
pretty' b (TCons "int" []) = " int"
pretty' b (TCons "bool" []) = " bool"
pretty' b (TCons "char" []) = " char"
pretty' True (TArr t1 t2)
= " (" ++ (pretty' True t1) ++ " -> " ++
(pretty' False t2) ++ ")"
pretty' False (TArr t1 t2)
= (pretty' True t1) ++ " -> " ++
(pretty' False t2)
pretty' b (TCons notArrow cl)
= " (" ++ notArrow ++
concat (map (pretty' True) cl) ++ ")"
lookup tvname []
= panic "tcShowtExpr: Type name lookup failed"
lookup tvname (t:ts) | t==tvname = 1
| otherwise = 1 + (lookup tvname ts)
tvdict = nub (tvdict' t)
tvdict' (TVar t) = [t]
tvdict' (TCons c ts) = concat (map tvdict' ts)
tvdict' (TArr t1 t2) = tvdict' t1 ++ tvdict' t2
-- ======================================================--
--
tcPretty :: (Naam, TExpr) ->
[Char]
tcPretty (naam, tipe)
= "\n " ++ (ljustify 25 (naam ++ " :: ")) ++
(tcShowtExpr tipe)
-- ======================================================--
tcCheck :: TcTypeEnv ->
TypeNameSupply ->
AtomicProgram ->
([Char], Reply (AnnExpr Naam TExpr, TypeEnv) Message)
tcCheck baseTypes ns (tdefs, expr)
= if good tcResult
then (fullEnvWords, Ok (rootTree, fullEnv))
else ("", Fail "No type")
where
tcResult = tc (tdefs++builtInTypes)
(baseTypes++finalConstrTypes) finalNs expr
good (Ok x) = True
good (Fail x2) = False
(rootSubst, rootType, annoTree) = f tcResult where f (Ok x) = x
rootTree = tcSubstAnnTree rootSubst annoTree
rootEnv = tcTreeToEnv rootTree
fullEnv = rootEnv ++ map f finalConstrTypes
where
f (naam, (Scheme vs t)) = (naam, t)
fullEnvWords = concat (map tcPretty fullEnv)
(finalNs, constrTypes) =
mapAccuml tcConstrTypeSchemes ns (tdefs++builtInTypes)
finalConstrTypes = concat constrTypes
builtInTypes
= [ ("bool", [], [("True", []), ("False", [])]) ]
-- ==========================================================--
= = = 9.2 Representation of type expressions = = = --
-- ==========================================================--
-- ======================================================--
--tcArrow :: TExpr ->
-- TExpr ->
-- TExpr
--
--tcArrow t1 t2 = TArr t1 t2
-- ======================================================--
tcInt :: TExpr
tcInt = TCons "int" []
-- ======================================================--
tcBool :: TExpr
tcBool = TCons "bool" []
-- ======================================================--
tcTvars_in :: TExpr ->
[TVName]
tcTvars_in t = tvars_in' t []
where
tvars_in' (TVar x) l = x:l
tvars_in' (TCons y ts) l = foldr tvars_in' l ts
tvars_in' (TArr t1 t2) l = tvars_in' t1 (tvars_in' t2 l)
-- ==========================================================--
= = = 9.41 Substitutions = = = --
-- ==========================================================--
-- ======================================================--
tcApply_sub :: Subst ->
TVName ->
TExpr
tcApply_sub phi tvn
= if TVar tvn == lookUpResult
then TVar tvn
else tcSub_type phi lookUpResult
where
lookUpResult = utLookupDef phi tvn (TVar tvn)
-- ======================================================--
tcSub_type :: Subst ->
TExpr ->
TExpr
tcSub_type phi (TVar tvn) = tcApply_sub phi tvn
tcSub_type phi (TCons tcn ts) = TCons tcn (map (tcSub_type phi) ts)
tcSub_type phi (TArr t1 t2) = TArr (tcSub_type phi t1) (tcSub_type phi t2)
-- ======================================================--
tcScomp :: Subst ->
Subst ->
Subst
tcScomp sub2 sub1 = sub1 ++ sub2
-- ======================================================--
tcId_subst :: Subst
tcId_subst = []
-- ======================================================--
tcDelta :: TVName ->
TExpr ->
Subst
all TVar - > TVar substitutions lead downhill
tcDelta tvn (TVar tvn2)
| tvn == tvn2 = []
| tvn > tvn2 = [(tvn, TVar tvn2)]
| tvn < tvn2 = [(tvn2, TVar tvn)]
tcDelta tvn non_var_texpr = [(tvn, non_var_texpr)]
-- ==========================================================--
= = = 9.42 Unification = = = --
-- ==========================================================--
-- ======================================================--
tcExtend :: Subst ->
TVName ->
TExpr ->
Reply Subst Message
tcExtend phi tvn t
| t == TVar tvn
= Ok phi
| tvn `notElem` (tcTvars_in t)
= Ok ((tcDelta tvn t) `tcScomp` phi)
| otherwise
= myFail
( "Type error in source program:\n\n" ++
"Circular substitution:\n " ++
tcShowtExpr (TVar tvn) ++
"\n going to\n" ++
" " ++
tcShowtExpr t ++
"\n")
-- ======================================================--
tcUnify :: Subst ->
(TExpr, TExpr) ->
Reply Subst Message
tcUnify phi (TVar tvn, t)
= if phitvn == TVar tvn
then tcExtend phi tvn phit
else tcUnify phi (phitvn, phit)
where
phitvn = tcApply_sub phi tvn
phit = tcSub_type phi t
tcUnify phi (p@(TCons _ _), q@(TVar _))
= tcUnify phi (q, p)
tcUnify phi (p@(TArr _ _), q@(TVar _))
= tcUnify phi (q, p)
tcUnify phi (TArr t1 t2, TArr t1' t2')
= tcUnifyl phi [(t1, t1'), (t2, t2')]
tcUnify phi (TCons tcn ts, TCons tcn' ts')
| tcn == tcn'
= tcUnifyl phi (ts `zip` ts')
tcUnify phi (t1, t2)
= myFail
( "Type error in source program:\n\n" ++
"Cannot unify\n " ++
tcShowtExpr t1 ++
"\n with\n " ++
tcShowtExpr t2 ++
"\n"
)
-- ======================================================--
tcUnifyl :: Subst ->
[(TExpr, TExpr)] ->
Reply Subst Message
tcUnifyl phi eqns
= foldr unify' (Ok phi) eqns
where
unify' eqn (Ok phi) = tcUnify phi eqn
unify' eqn (Fail m) = Fail m
-- ==========================================================--
= = = 9.42.2 Merging of substitutions = = = --
-- ==========================================================--
-- ======================================================--
tcMergeSubs :: Subst ->
Subst
tcMergeSubs phi
= if newBinds == []
then unifiedOlds
else tcMergeSubs (unifiedOlds ++ newBinds)
where
(newBinds, unifiedOlds) = tcMergeSubsMain phi
-- ======================================================--
tcMergeSubsMain :: Subst ->
(Subst, Subst) -- pair of new binds, unified olds
tcMergeSubsMain phi
= (concat newUnifiersChecked,
zip oldVars (tcOldUnified newUnifiersChecked oldGroups))
where
oldVars = nub (utDomain phi)
oldGroups = map (utLookupAll phi) oldVars
newUnifiers = map (tcUnifySet tcId_subst) oldGroups
newUnifiersChecked = map tcCheckUnifier newUnifiers
-- ======================================================--
tcCheckUnifier :: Reply Subst Message -> Subst
tcCheckUnifier (Ok r) = r
tcCheckUnifier (Fail m)
= panic ("tcCheckUnifier: " ++ m)
-- ======================================================--
tcOldUnified :: [Subst] -> [[TExpr]] -> [TExpr]
tcOldUnified [] [] = []
tcOldUnified (u:us) (og:ogs)
= (tcSub_type u (head og)): tcOldUnified us ogs
-- ==========================================================--
= = = 9.5 Keeping track of types = = = --
-- ==========================================================--
-- ======================================================--
tcUnknowns_scheme :: TypeScheme ->
[TVName]
tcUnknowns_scheme (Scheme scvs t) = tcTvars_in t `tcBar` scvs
-- ======================================================--
tcBar :: (Eq a) => [a] ->
[a] ->
[a]
tcBar xs ys = [ x | x <- xs, not (x `elem` ys)]
-- ======================================================--
tcSub_scheme :: Subst ->
TypeScheme ->
TypeScheme
tcSub_scheme phi (Scheme scvs t)
= Scheme scvs (tcSub_type (tcExclude phi scvs) t)
where
tcExclude phi scvs = [(n,e) | (n,e) <- phi, not (n `elem` scvs)]
-- ==========================================================--
= = = 9.53 Association lists = = = --
-- ==========================================================--
-- ======================================================--
tcCharVal :: AList Naam b -> Naam -> b
tcCharVal al k
= utLookupDef al k (panic ("tcCharVal: no such variable: " ++ k))
-- ======================================================--
tcUnknowns_te :: TcTypeEnv ->
[TVName]
tcUnknowns_te gamma = concat (map tcUnknowns_scheme (utRange gamma))
-- ======================================================--
tcSub_te :: Subst ->
TcTypeEnv ->
TcTypeEnv
tcSub_te phi gamma = [(x, tcSub_scheme phi st) | (x, st) <- gamma]
-- ==========================================================--
= = = 9.6 New variables = = = --
-- ==========================================================--
-- ======================================================--
tcNext_name :: TypeNameSupply ->
TVName
tcNext_name ns@(f, s) = ns
-- ======================================================--
tcDeplete :: TypeNameSupply ->
TypeNameSupply
tcDeplete (f, s) = (f, tcNSSucc s)
-- ======================================================--
tcSplit :: TypeNameSupply ->
(TypeNameSupply, TypeNameSupply)
tcSplit (f, s) = ((f2, [0]), (tcNSSucc f2, [0]))
where f2 = tcNSDouble f
-- ======================================================--
tcName_sequence :: TypeNameSupply ->
[TVName]
tcName_sequence ns = tcNext_name ns: tcName_sequence (tcDeplete ns)
-- ======================================================--
tcNSSucc :: [Int] ->
[Int]
tcNSSucc [] = [1]
tcNSSucc (n:ns) | n < tcNSslimit = n+1: ns
| otherwise = 0: tcNSSucc ns
-- ======================================================--
tcNSDouble :: [Int] ->
[Int]
tcNSDouble [] = []
tcNSDouble (n:ns)
= 2*n': ns'
where n' | n > tcNSdlimit = n - tcNSdlimit
| otherwise = n
ns' | n' == n = tcNSDouble ns
| otherwise = tcNSSucc (tcNSDouble ns)
tcNSdlimit :: Int
tcNSdlimit = 2^30
tcNSslimit :: Int
tcNSslimit = tcNSdlimit + (tcNSdlimit - 1)
-- ==========================================================--
= = = 9.7 The type - checker = = = --
-- ==========================================================--
-- ======================================================--
tc :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
CExpr ->
Reply TypeInfo Message
tc tds gamma ns (ENum n)
= Ok (tcId_subst, TCons "int" [], (TCons "int" [], ANum n))
tc tds gamma ns (EVar x)
= tcvar tds gamma ns x
tc tds gamma ns (EConstr c)
= tcvar tds gamma ns c
tc tds gamma ns (EAp e1 e2)
= tcap tds gamma ns e1 e2
tc tds gamma ns (ELam [] e)
= tc tds gamma ns e
tc tds gamma ns (ELam [x] e)
= tclambda tds gamma ns x e
tc tds gamma ns (ELam (x:y:xs) e)
= tclambda tds gamma ns x (ELam (y:xs) e)
tc tds gamma ns (ELet recursive dl e)
= if not recursive
then tclet tds gamma ns xs es e
else tcletrec tds gamma ns xs es e
where
(xs, es) = unzip2 dl
tc tds gamma ns (ECase switch alts)
= tccase tds gamma ns switch constructors arglists exprs
where
(constructors, alters) = unzip2 alts
(arglists, exprs) = unzip2 alters
-- ==========================================================--
= = = 0.00 Type - checking case - expressions = = = --
-- ==========================================================--
tcConstrTypeSchemes :: TypeNameSupply ->
TypeDef ->
(TypeNameSupply, AList Naam TypeScheme)
tcConstrTypeSchemes ns (tn, stvs, cal)
= (finalNameSupply, map2nd enScheme cAltsCurried)
where
-- associates new type vars with each poly var
-- in the type
newTVs = tcNewTypeVars (tn, stvs, cal) ns
-- the actual type variables themselves
tVs = map second newTVs
-- the types of the constructor functions
cAltsCurried = map2nd (foldr TArr tdSignature) cAltsXLated
cAltsXLated = map2nd (map (tcTDefSubst newTVs)) cal
tdSignature = TCons tn (map TVar tVs)
enScheme texp = Scheme ((nub.tcTvars_in) texp) texp
-- the revised name supply
finalNameSupply = applyNtimes ( length tVs + 2) tcDeplete ns
-- apply a function n times to an arg
applyNtimes n func arg
| n ==0 = arg
| otherwise = applyNtimes (n-1) func (func arg)
-- ======================================================--
--
tccase :: [TypeDef] -> -- constructor type definitions
TcTypeEnv -> -- current type bindings
TypeNameSupply -> -- name supply
CExpr -> -- switch expression
[Naam] -> -- constructors
[[Naam]] -> -- argument lists
[CExpr] -> -- resulting expressions
Reply TypeInfo Message
tccase tds gamma ns sw cs als res
-- get the type definition in use, & an association of
-- variables therein to type vars & pass
-- Also, reorder the argument lists
-- and resulting expressions so as to reflect the
-- sequence of constructors in the definition
= if length tdCNames /= length (nub cs)
then myFail
"Error in source program: missing alternatives in CASE"
else tccase1 tds gamma ns1 sw reOals reOres newTVs tdInUse
where
tdInUse = tcGetTypeDef tds cs
newTVs = tcNewTypeVars tdInUse ns2
(ns1, ns2) = tcSplit ns
merge = zip cs (zip als res)
tdCNames = map first (tcK33 tdInUse)
(reOals, reOres) = unzip2 (tcReorder tdCNames merge)
-- ======================================================--
--
tcReorder :: [Naam] -> [(Naam,b)] -> [b]
tcReorder [] uol = []
tcReorder (k:ks) uol
= (utLookupDef uol k
(myFail
("Error in source program: undeclared constructor '" ++ k ++
"' in CASE") ) )
: tcReorder ks uol
-- ======================================================--
-- Projection functions and similar rubbish.
tcDeOksel (Ok x) = x
tcDeOksel (Fail m) = panic ("tcDeOkSel: " ++ m)
tcOk13sel (Ok (a, b, c)) = a
tcOk13sel (Fail m) = panic ("tcOk13sel: " ++ m)
tcOk23sel (Ok (a, b, c)) = b
tcOk23sel (Fail m) = panic ("tcOk23sel: " ++ m)
tcOk33sel (Ok (a, b, c)) = c
tcOk33sel (Fail m) = panic ("tcOk33sel: " ++ m)
tcK31sel (a, b, c) = a
tcK33 (a,b,c) = c
-- ======================================================--
--
tccase1 :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
CExpr ->
[[Naam]] ->
[CExpr] ->
AList Naam TVName ->
TypeDef ->
Reply TypeInfo Message
tccase1 tds gamma ns sw reOals reOres newTVs tdInUse
-- calculate all the gammas for the RHS's
-- call tc for each RHS, so as to gather all the
-- sigmas and types for each RHS, then pass on
= tccase2 tds gamma ns2 sw reOals newTVs tdInUse rhsTcs
where
rhsGammas = tcGetAllGammas newTVs (tcK33 tdInUse) reOals
rhsTcs = rhsTc1 ns1 rhsGammas reOres
rhsTc1 nsl [] [] = []
rhsTc1 nsl (g:gs) (r:rs)
= tc tds (g++gamma) nsl1 r : rhsTc1 nsl2 gs rs
where (nsl1, nsl2) = tcSplit nsl
(ns1, ns2) = tcSplit ns
-- ======================================================--
--
tccase2 :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
CExpr ->
[[Naam]] ->
AList Naam TVName ->
TypeDef ->
[Reply TypeInfo Message] ->
Reply TypeInfo Message
tccase2 tds gamma ns sw reOals newTVs tdInUse rhsTcs
-- get the unifiers for T1 to Tk and hence the unifier for all
-- type variables in the type definition. Also compute the
-- unifier of the result types.
= tccase3 tds gamma ns sw reOals newTVs tdInUse rhsTcs
phi_1_to_n tau_1_to_n phi_rhs
where
phi_1_to_n = map tcOk13sel rhsTcs
tau_1_to_n = map tcOk23sel rhsTcs
phi_rhs = tcDeOksel (tcUnifySet tcId_subst tau_1_to_n)
-- ======================================================--
--
tccase3 :: [TypeDef] -> -- tds
TcTypeEnv -> -- gamma
TypeNameSupply -> -- ns
CExpr -> -- sw
[[Naam]] -> -- reOals
AList Naam TVName -> -- newTVs
TypeDef -> -- tdInUse
[Reply TypeInfo Message] -> -- rhsTcs
[Subst] -> -- phi_1_to_n
[TExpr] -> -- tau_1_to_n
Subst -> -- phi_rhs
Reply TypeInfo Message
tccase3 tds gamma ns sw reOals newTVs tdInUse rhsTcs
phi_1_to_n tau_1_to_n phi_rhs
make up substitutions for each of the unknown tvars
merge the substitutions into one
-- apply the substitution to the typedef's signature to get the
-- most general allowable input type
-- call tc to get the type of the switch expression
-- check that this is an instance of the deduced input type
-- gather the new bindings from the RHSs and switch expression
-- return Ok (the big substitution, the result type, gathered bindings)
= Ok (phi_Big, tau_final,
(tau_final, ACase tree_s
(zip tdCNames (zip reOals annotatedRHSs))))
where
phi_sTau_sTree_s = tc tds gamma ns sw
phi_s = tcOk13sel phi_sTau_sTree_s
tau_s = tcOk23sel phi_sTau_sTree_s
tree_s = tcOk33sel phi_sTau_sTree_s
phi = tcMergeSubs (concat phi_1_to_n ++ phi_rhs ++ phi_s)
tau_lhs = tcSub_type phi tdSignature
phi_lhs = tcUnify tcId_subst (tau_lhs, tau_s) -- reverse these?
phi_Big = tcMergeSubs (tcDeOksel phi_lhs ++ phi)
tau_final = tcSub_type phi_Big (head (map tcOk23sel rhsTcs))
annotatedRHSs = map tcOk33sel rhsTcs
tVs = map second newTVs
tdSignature = TCons (tcK31sel tdInUse) (map TVar tVs)
tdCNames = map first (tcK33 tdInUse)
-- ======================================================--
--
tcUnifySet :: Subst ->
[TExpr] ->
Reply Subst Message
tcUnifySet sub (e1:[]) = Ok sub
tcUnifySet sub (e1:e2:[])
= tcUnify sub (e1, e2)
tcUnifySet sub (e1:e2:e3:es)
= tcUnifySet newSub (e2:e3:es)
where
newSub = tcDeOksel (tcUnify sub (e1, e2))
-- ======================================================--
--
tcNewTypeVars :: TypeDef ->
TypeNameSupply ->
AList Naam TVName
tcNewTypeVars (t, vl, c) ns = zip vl (tcName_sequence ns)
-- ======================================================--
--
tcGetGammaN :: AList Naam TVName ->
ConstrAlt ->
[Naam] ->
AList Naam TypeScheme
tcGetGammaN tvl (cname, cal) cparams
= zip cparams (map (Scheme [] . tcTDefSubst tvl) cal)
-- ======================================================--
--
tcTDefSubst :: AList Naam TVName ->
TDefExpr ->
TExpr
tcTDefSubst nameMap (TDefVar n)
= f result
where
f (Just tvn) = TVar tvn
f Nothing = TCons n []
result = utLookup nameMap n
tcTDefSubst nameMap (TDefCons c al)
= TCons c (map (tcTDefSubst nameMap) al)
-- ======================================================--
--
tcGetAllGammas :: AList Naam TVName ->
[ConstrAlt] ->
[[Naam]] ->
[AList Naam TypeScheme]
tcGetAllGammas tvl [] [] = []
note param lists cparamss must be ordered in
-- accordance with calts
tcGetAllGammas tvl (calt:calts) (cparams:cparamss) =
tcGetGammaN tvl calt cparams :
tcGetAllGammas tvl calts cparamss
-- ======================================================--
--
tcGetTypeDef :: [TypeDef] -> -- type definitions
[Naam] -> -- list of constructors used here
TypeDef
tcGetTypeDef tds cs
= if length tdefset == 0
then myFail "Undeclared constructors in use"
else if length tdefset > 1
then myFail "CASE expression contains mixed constructors"
else head tdefset
where
tdefset = nub
[ (tname, ftvs, cl) |
(tname, ftvs, cl) <- tds,
usedc <- cs,
usedc `elem` (map first cl) ]
-- ==========================================================--
= = = 9.71 Type - checking lists of expressions = = = --
-- ==========================================================--
-- ======================================================--
--
tcl :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
[CExpr] ->
Reply (Subst, [TExpr], [AnnExpr Naam TExpr]) Message
tcl tds gamma ns []
= Ok (tcId_subst, [], [])
tcl tds gamma ns (e:es)
= tcl1 tds gamma ns0 es (tc tds gamma ns1 e)
where
(ns0, ns1) = tcSplit ns
-- ======================================================--
--
tcl1 tds gamma ns es (Fail m) = Fail m
tcl1 tds gamma ns es (Ok (phi, t, annotatedE))
= tcl2 phi t (tcl tds (tcSub_te phi gamma) ns es) annotatedE
-- ======================================================--
--
tcl2 phi t (Fail m) annotatedE = Fail m
tcl2 phi t (Ok (psi, ts, annotatedEs)) annotatedE
= Ok (psi `tcScomp` phi, (tcSub_type psi t):ts,
annotatedE:annotatedEs)
-- ==========================================================--
= = = 9.72 Type - checking variables = = = --
-- ==========================================================--
-- ======================================================--
--
tcvar :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
Naam ->
Reply TypeInfo Message
tcvar tds gamma ns x = Ok (tcId_subst, finalType, (finalType, AVar x))
where
scheme = tcCharVal gamma x
finalType = tcNewinstance ns scheme
-- ======================================================--
--
tcNewinstance :: TypeNameSupply ->
TypeScheme ->
TExpr
tcNewinstance ns (Scheme scvs t) = tcSub_type phi t
where
al = scvs `zip` (tcName_sequence ns)
phi = tcAl_to_subst al
-- ======================================================--
--
tcAl_to_subst :: AList TVName TVName ->
Subst
tcAl_to_subst al = map2nd TVar al
-- ==========================================================--
= = = 9.73 Type - checking applications = = = --
-- ==========================================================--
-- ======================================================--
--
tcap :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
CExpr ->
CExpr ->
Reply TypeInfo Message
tcap tds gamma ns e1 e2 = tcap1 tvn (tcl tds gamma ns' [e1, e2])
where
tvn = tcNext_name ns
ns' = tcDeplete ns
-- ======================================================--
--
tcap1 tvn (Fail m)
= Fail m
tcap1 tvn (Ok (phi, [t1, t2], [ae1, ae2]))
= tcap2 tvn (tcUnify phi (t1, t2 `TArr` (TVar tvn))) [ae1, ae2]
-- ======================================================--
--
tcap2 tvn (Fail m) [ae1, ae2]
= Fail m
tcap2 tvn (Ok phi) [ae1, ae2]
= Ok (phi, finalType, (finalType, AAp ae1 ae2))
where
finalType = tcApply_sub phi tvn
-- ==========================================================--
= = = 9.74 Type - checking lambda abstractions = = = --
-- ==========================================================--
-- ======================================================--
--
tclambda :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
Naam ->
CExpr ->
Reply TypeInfo Message
tclambda tds gamma ns x e = tclambda1 tvn x (tc tds gamma' ns' e)
where
ns' = tcDeplete ns
gamma' = tcNew_bvar (x, tvn): gamma
tvn = tcNext_name ns
-- ======================================================--
--
tclambda1 tvn x (Fail m) = Fail m
tclambda1 tvn x (Ok (phi, t, annotatedE)) =
Ok (phi, finalType, (finalType, ALam [x] annotatedE))
where
finalType = (tcApply_sub phi tvn) `TArr` t
-- ======================================================--
--
tcNew_bvar (x, tvn) = (x, Scheme [] (TVar tvn))
-- ==========================================================--
= = = 9.75 Type - checking let - expressions = = = --
-- ==========================================================--
-- ======================================================--
--
tclet :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
[Naam] ->
[CExpr] ->
CExpr ->
Reply TypeInfo Message
tclet tds gamma ns xs es e
= tclet1 tds gamma ns0 xs e rhsTypes
where
(ns0, ns1) = tcSplit ns
rhsTypes = tcl tds gamma ns1 es
-- ======================================================--
--
tclet1 tds gamma ns xs e (Fail m) = Fail m
tclet1 tds gamma ns xs e (Ok (phi, ts, rhsAnnExprs))
= tclet2 phi xs False (tc tds gamma'' ns1 e) rhsAnnExprs
where
gamma'' = tcAdd_decls gamma' ns0 xs ts
gamma' = tcSub_te phi gamma
(ns0, ns1) = tcSplit ns
-- ======================================================--
--
tclet2 phi xs recFlag (Fail m) rhsAnnExprs = Fail m
tclet2 phi xs recFlag (Ok (phi', t, annotatedE)) rhsAnnExprs
= Ok (phi' `tcScomp` phi, t, (t, ALet recFlag (zip xs rhsAnnExprs) annotatedE))
-- ======================================================--
--
tcAdd_decls :: TcTypeEnv ->
TypeNameSupply ->
[Naam] ->
[TExpr] ->
TcTypeEnv
tcAdd_decls gamma ns xs ts = (xs `zip` schemes) ++ gamma
where
schemes = map (tcGenbar unknowns ns) ts
unknowns = tcUnknowns_te gamma
-- ======================================================--
--
tcGenbar unknowns ns t = Scheme (map second al) t'
where
al = scvs `zip` (tcName_sequence ns)
scvs = (nub (tcTvars_in t)) `tcBar` unknowns
t' = tcSub_type (tcAl_to_subst al) t
-- ==========================================================--
= = = 9.76 Type - checking letrec - expressions = = = --
-- ==========================================================--
-- ======================================================--
--
tcletrec :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
[Naam] ->
[CExpr] ->
CExpr ->
Reply TypeInfo Message
tcletrec tds gamma ns xs es e
= tcletrec1 tds gamma ns0 xs nbvs e
(tcl tds (nbvs ++ gamma) ns1 es)
where
(ns0, ns') = tcSplit ns
(ns1, ns2) = tcSplit ns'
nbvs = tcNew_bvars xs ns2
-- ======================================================--
--
tcNew_bvars xs ns = map tcNew_bvar (xs `zip` (tcName_sequence ns))
-- ======================================================--
--
tcletrec1 tds gamma ns xs nbvs e (Fail m) = (Fail m)
tcletrec1 tds gamma ns xs nbvs e (Ok (phi, ts, rhsAnnExprs))
= tcletrec2 tds gamma' ns xs nbvs' e (tcUnifyl phi (ts `zip` ts')) rhsAnnExprs
where
ts' = map tcOld_bvar nbvs'
nbvs' = tcSub_te phi nbvs
gamma' = tcSub_te phi gamma
-- ======================================================--
--
tcOld_bvar (x, Scheme [] t) = t
-- ======================================================--
--
tcletrec2 tds gamma ns xs nbvs e (Fail m) rhsAnnExprs = (Fail m)
tcletrec2 tds gamma ns xs nbvs e (Ok phi) rhsAnnExprs
= tclet2 phi xs True (tc tds gamma'' ns1 e) rhsAnnExprs
where
ts = map tcOld_bvar nbvs'
nbvs' = tcSub_te phi nbvs
gamma' = tcSub_te phi gamma
gamma'' = tcAdd_decls gamma' ns0 (map first nbvs) ts
(ns0, ns1) = tcSplit ns
subnames = map first nbvs
-- ==========================================================--
= = = End TypeCheck5.m ( 1 ) = = = --
-- ==========================================================--
| null | https://raw.githubusercontent.com/ghc/nofib/f34b90b5a6ce46284693119a06d1133908b11856/real/anna/TypeCheck5.hs | haskell | ==========================================================--
v5 File : TypeCheck5.m ( 1 ) = = = --
=== Corrected version for 0.210a ===--
==========================================================--
==========================================================--
=== Formatting of results ===--
==========================================================--
======================================================--
======================================================--
======================================================--
======================================================--
======================================================--
==========================================================--
==========================================================--
======================================================--
tcArrow :: TExpr ->
TExpr ->
TExpr
tcArrow t1 t2 = TArr t1 t2
======================================================--
======================================================--
======================================================--
==========================================================--
==========================================================--
======================================================--
======================================================--
======================================================--
======================================================--
======================================================--
==========================================================--
==========================================================--
======================================================--
======================================================--
======================================================--
==========================================================--
==========================================================--
======================================================--
======================================================--
pair of new binds, unified olds
======================================================--
======================================================--
==========================================================--
==========================================================--
======================================================--
======================================================--
======================================================--
==========================================================--
==========================================================--
======================================================--
======================================================--
======================================================--
==========================================================--
==========================================================--
======================================================--
======================================================--
======================================================--
======================================================--
======================================================--
======================================================--
==========================================================--
==========================================================--
======================================================--
==========================================================--
==========================================================--
associates new type vars with each poly var
in the type
the actual type variables themselves
the types of the constructor functions
the revised name supply
apply a function n times to an arg
======================================================--
constructor type definitions
current type bindings
name supply
switch expression
constructors
argument lists
resulting expressions
get the type definition in use, & an association of
variables therein to type vars & pass
Also, reorder the argument lists
and resulting expressions so as to reflect the
sequence of constructors in the definition
======================================================--
======================================================--
Projection functions and similar rubbish.
======================================================--
calculate all the gammas for the RHS's
call tc for each RHS, so as to gather all the
sigmas and types for each RHS, then pass on
======================================================--
get the unifiers for T1 to Tk and hence the unifier for all
type variables in the type definition. Also compute the
unifier of the result types.
======================================================--
tds
gamma
ns
sw
reOals
newTVs
tdInUse
rhsTcs
phi_1_to_n
tau_1_to_n
phi_rhs
apply the substitution to the typedef's signature to get the
most general allowable input type
call tc to get the type of the switch expression
check that this is an instance of the deduced input type
gather the new bindings from the RHSs and switch expression
return Ok (the big substitution, the result type, gathered bindings)
reverse these?
======================================================--
======================================================--
======================================================--
======================================================--
======================================================--
accordance with calts
======================================================--
type definitions
list of constructors used here
==========================================================--
==========================================================--
======================================================--
======================================================--
======================================================--
==========================================================--
==========================================================--
======================================================--
======================================================--
======================================================--
==========================================================--
==========================================================--
======================================================--
======================================================--
======================================================--
==========================================================--
==========================================================--
======================================================--
======================================================--
======================================================--
==========================================================--
==========================================================--
======================================================--
======================================================--
======================================================--
======================================================--
======================================================--
==========================================================--
==========================================================--
======================================================--
======================================================--
======================================================--
======================================================--
======================================================--
==========================================================--
==========================================================-- |
module TypeCheck5 where
import BaseDefs
import Utils
import MyUtils
1.3
tcMapAnnExpr :: (a -> b) ->
AnnExpr c a ->
AnnExpr c b
tcMapAnnExpr f (ann, node)
= (f ann, mapAnnExpr' node)
where
mapAnnExpr' (AVar v) = AVar v
mapAnnExpr' (ANum n) = ANum n
mapAnnExpr' (AConstr c) = AConstr c
mapAnnExpr' (AAp ae1 ae2)
= AAp (tcMapAnnExpr f ae1) (tcMapAnnExpr f ae2)
mapAnnExpr' (ALet recFlag annDefs mainExpr)
= ALet recFlag (map mapAnnDefn annDefs) (tcMapAnnExpr f mainExpr)
mapAnnExpr' (ACase switchExpr annAlts)
= ACase (tcMapAnnExpr f switchExpr) (map mapAnnAlt annAlts)
mapAnnExpr' (ALam vs e) = ALam vs (tcMapAnnExpr f e)
mapAnnDefn (naam, expr)
= (naam, tcMapAnnExpr f expr)
mapAnnAlt (naam, (pars, resExpr))
= (naam, (pars, tcMapAnnExpr f resExpr))
tcSubstAnnTree :: Subst ->
AnnExpr Naam TExpr ->
AnnExpr Naam TExpr
tcSubstAnnTree phi tree = tcMapAnnExpr (tcSub_type phi) tree
tcTreeToEnv :: AnnExpr Naam TExpr ->
TypeEnv
tcTreeToEnv tree
= t2e tree
where
t2e (nodeType, node) = t2e' node
t2e' (AVar v) = []
t2e' (ANum n) = []
t2e' (AConstr c) = []
t2e' (AAp ae1 ae2) = (t2e ae1) ++ (t2e ae2)
t2e' (ALam cs e) = t2e e
t2e' (ALet rf dl me)
= (concat (map aFN dl)) ++ (t2e me)
t2e' (ACase sw alts)
= (t2e sw) ++ (concat (map (t2e.second.second) alts))
aFN (naam, (tijp, body))
= (naam, tijp):(t2e' body)
tcShowtExpr :: TExpr ->
[Char]
tcShowtExpr t
= pretty' False t
where
pretty' b (TVar tvname) = [' ', toEnum (96+(lookup tvname tvdict))]
pretty' b (TCons "int" []) = " int"
pretty' b (TCons "bool" []) = " bool"
pretty' b (TCons "char" []) = " char"
pretty' True (TArr t1 t2)
= " (" ++ (pretty' True t1) ++ " -> " ++
(pretty' False t2) ++ ")"
pretty' False (TArr t1 t2)
= (pretty' True t1) ++ " -> " ++
(pretty' False t2)
pretty' b (TCons notArrow cl)
= " (" ++ notArrow ++
concat (map (pretty' True) cl) ++ ")"
lookup tvname []
= panic "tcShowtExpr: Type name lookup failed"
lookup tvname (t:ts) | t==tvname = 1
| otherwise = 1 + (lookup tvname ts)
tvdict = nub (tvdict' t)
tvdict' (TVar t) = [t]
tvdict' (TCons c ts) = concat (map tvdict' ts)
tvdict' (TArr t1 t2) = tvdict' t1 ++ tvdict' t2
tcPretty :: (Naam, TExpr) ->
[Char]
tcPretty (naam, tipe)
= "\n " ++ (ljustify 25 (naam ++ " :: ")) ++
(tcShowtExpr tipe)
tcCheck :: TcTypeEnv ->
TypeNameSupply ->
AtomicProgram ->
([Char], Reply (AnnExpr Naam TExpr, TypeEnv) Message)
tcCheck baseTypes ns (tdefs, expr)
= if good tcResult
then (fullEnvWords, Ok (rootTree, fullEnv))
else ("", Fail "No type")
where
tcResult = tc (tdefs++builtInTypes)
(baseTypes++finalConstrTypes) finalNs expr
good (Ok x) = True
good (Fail x2) = False
(rootSubst, rootType, annoTree) = f tcResult where f (Ok x) = x
rootTree = tcSubstAnnTree rootSubst annoTree
rootEnv = tcTreeToEnv rootTree
fullEnv = rootEnv ++ map f finalConstrTypes
where
f (naam, (Scheme vs t)) = (naam, t)
fullEnvWords = concat (map tcPretty fullEnv)
(finalNs, constrTypes) =
mapAccuml tcConstrTypeSchemes ns (tdefs++builtInTypes)
finalConstrTypes = concat constrTypes
builtInTypes
= [ ("bool", [], [("True", []), ("False", [])]) ]
tcInt :: TExpr
tcInt = TCons "int" []
tcBool :: TExpr
tcBool = TCons "bool" []
tcTvars_in :: TExpr ->
[TVName]
tcTvars_in t = tvars_in' t []
where
tvars_in' (TVar x) l = x:l
tvars_in' (TCons y ts) l = foldr tvars_in' l ts
tvars_in' (TArr t1 t2) l = tvars_in' t1 (tvars_in' t2 l)
tcApply_sub :: Subst ->
TVName ->
TExpr
tcApply_sub phi tvn
= if TVar tvn == lookUpResult
then TVar tvn
else tcSub_type phi lookUpResult
where
lookUpResult = utLookupDef phi tvn (TVar tvn)
tcSub_type :: Subst ->
TExpr ->
TExpr
tcSub_type phi (TVar tvn) = tcApply_sub phi tvn
tcSub_type phi (TCons tcn ts) = TCons tcn (map (tcSub_type phi) ts)
tcSub_type phi (TArr t1 t2) = TArr (tcSub_type phi t1) (tcSub_type phi t2)
tcScomp :: Subst ->
Subst ->
Subst
tcScomp sub2 sub1 = sub1 ++ sub2
tcId_subst :: Subst
tcId_subst = []
tcDelta :: TVName ->
TExpr ->
Subst
all TVar - > TVar substitutions lead downhill
tcDelta tvn (TVar tvn2)
| tvn == tvn2 = []
| tvn > tvn2 = [(tvn, TVar tvn2)]
| tvn < tvn2 = [(tvn2, TVar tvn)]
tcDelta tvn non_var_texpr = [(tvn, non_var_texpr)]
tcExtend :: Subst ->
TVName ->
TExpr ->
Reply Subst Message
tcExtend phi tvn t
| t == TVar tvn
= Ok phi
| tvn `notElem` (tcTvars_in t)
= Ok ((tcDelta tvn t) `tcScomp` phi)
| otherwise
= myFail
( "Type error in source program:\n\n" ++
"Circular substitution:\n " ++
tcShowtExpr (TVar tvn) ++
"\n going to\n" ++
" " ++
tcShowtExpr t ++
"\n")
tcUnify :: Subst ->
(TExpr, TExpr) ->
Reply Subst Message
tcUnify phi (TVar tvn, t)
= if phitvn == TVar tvn
then tcExtend phi tvn phit
else tcUnify phi (phitvn, phit)
where
phitvn = tcApply_sub phi tvn
phit = tcSub_type phi t
tcUnify phi (p@(TCons _ _), q@(TVar _))
= tcUnify phi (q, p)
tcUnify phi (p@(TArr _ _), q@(TVar _))
= tcUnify phi (q, p)
tcUnify phi (TArr t1 t2, TArr t1' t2')
= tcUnifyl phi [(t1, t1'), (t2, t2')]
tcUnify phi (TCons tcn ts, TCons tcn' ts')
| tcn == tcn'
= tcUnifyl phi (ts `zip` ts')
tcUnify phi (t1, t2)
= myFail
( "Type error in source program:\n\n" ++
"Cannot unify\n " ++
tcShowtExpr t1 ++
"\n with\n " ++
tcShowtExpr t2 ++
"\n"
)
tcUnifyl :: Subst ->
[(TExpr, TExpr)] ->
Reply Subst Message
tcUnifyl phi eqns
= foldr unify' (Ok phi) eqns
where
unify' eqn (Ok phi) = tcUnify phi eqn
unify' eqn (Fail m) = Fail m
tcMergeSubs :: Subst ->
Subst
tcMergeSubs phi
= if newBinds == []
then unifiedOlds
else tcMergeSubs (unifiedOlds ++ newBinds)
where
(newBinds, unifiedOlds) = tcMergeSubsMain phi
tcMergeSubsMain :: Subst ->
tcMergeSubsMain phi
= (concat newUnifiersChecked,
zip oldVars (tcOldUnified newUnifiersChecked oldGroups))
where
oldVars = nub (utDomain phi)
oldGroups = map (utLookupAll phi) oldVars
newUnifiers = map (tcUnifySet tcId_subst) oldGroups
newUnifiersChecked = map tcCheckUnifier newUnifiers
tcCheckUnifier :: Reply Subst Message -> Subst
tcCheckUnifier (Ok r) = r
tcCheckUnifier (Fail m)
= panic ("tcCheckUnifier: " ++ m)
tcOldUnified :: [Subst] -> [[TExpr]] -> [TExpr]
tcOldUnified [] [] = []
tcOldUnified (u:us) (og:ogs)
= (tcSub_type u (head og)): tcOldUnified us ogs
tcUnknowns_scheme :: TypeScheme ->
[TVName]
tcUnknowns_scheme (Scheme scvs t) = tcTvars_in t `tcBar` scvs
tcBar :: (Eq a) => [a] ->
[a] ->
[a]
tcBar xs ys = [ x | x <- xs, not (x `elem` ys)]
tcSub_scheme :: Subst ->
TypeScheme ->
TypeScheme
tcSub_scheme phi (Scheme scvs t)
= Scheme scvs (tcSub_type (tcExclude phi scvs) t)
where
tcExclude phi scvs = [(n,e) | (n,e) <- phi, not (n `elem` scvs)]
tcCharVal :: AList Naam b -> Naam -> b
tcCharVal al k
= utLookupDef al k (panic ("tcCharVal: no such variable: " ++ k))
tcUnknowns_te :: TcTypeEnv ->
[TVName]
tcUnknowns_te gamma = concat (map tcUnknowns_scheme (utRange gamma))
tcSub_te :: Subst ->
TcTypeEnv ->
TcTypeEnv
tcSub_te phi gamma = [(x, tcSub_scheme phi st) | (x, st) <- gamma]
tcNext_name :: TypeNameSupply ->
TVName
tcNext_name ns@(f, s) = ns
tcDeplete :: TypeNameSupply ->
TypeNameSupply
tcDeplete (f, s) = (f, tcNSSucc s)
tcSplit :: TypeNameSupply ->
(TypeNameSupply, TypeNameSupply)
tcSplit (f, s) = ((f2, [0]), (tcNSSucc f2, [0]))
where f2 = tcNSDouble f
tcName_sequence :: TypeNameSupply ->
[TVName]
tcName_sequence ns = tcNext_name ns: tcName_sequence (tcDeplete ns)
tcNSSucc :: [Int] ->
[Int]
tcNSSucc [] = [1]
tcNSSucc (n:ns) | n < tcNSslimit = n+1: ns
| otherwise = 0: tcNSSucc ns
tcNSDouble :: [Int] ->
[Int]
tcNSDouble [] = []
tcNSDouble (n:ns)
= 2*n': ns'
where n' | n > tcNSdlimit = n - tcNSdlimit
| otherwise = n
ns' | n' == n = tcNSDouble ns
| otherwise = tcNSSucc (tcNSDouble ns)
tcNSdlimit :: Int
tcNSdlimit = 2^30
tcNSslimit :: Int
tcNSslimit = tcNSdlimit + (tcNSdlimit - 1)
tc :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
CExpr ->
Reply TypeInfo Message
tc tds gamma ns (ENum n)
= Ok (tcId_subst, TCons "int" [], (TCons "int" [], ANum n))
tc tds gamma ns (EVar x)
= tcvar tds gamma ns x
tc tds gamma ns (EConstr c)
= tcvar tds gamma ns c
tc tds gamma ns (EAp e1 e2)
= tcap tds gamma ns e1 e2
tc tds gamma ns (ELam [] e)
= tc tds gamma ns e
tc tds gamma ns (ELam [x] e)
= tclambda tds gamma ns x e
tc tds gamma ns (ELam (x:y:xs) e)
= tclambda tds gamma ns x (ELam (y:xs) e)
tc tds gamma ns (ELet recursive dl e)
= if not recursive
then tclet tds gamma ns xs es e
else tcletrec tds gamma ns xs es e
where
(xs, es) = unzip2 dl
tc tds gamma ns (ECase switch alts)
= tccase tds gamma ns switch constructors arglists exprs
where
(constructors, alters) = unzip2 alts
(arglists, exprs) = unzip2 alters
tcConstrTypeSchemes :: TypeNameSupply ->
TypeDef ->
(TypeNameSupply, AList Naam TypeScheme)
tcConstrTypeSchemes ns (tn, stvs, cal)
= (finalNameSupply, map2nd enScheme cAltsCurried)
where
newTVs = tcNewTypeVars (tn, stvs, cal) ns
tVs = map second newTVs
cAltsCurried = map2nd (foldr TArr tdSignature) cAltsXLated
cAltsXLated = map2nd (map (tcTDefSubst newTVs)) cal
tdSignature = TCons tn (map TVar tVs)
enScheme texp = Scheme ((nub.tcTvars_in) texp) texp
finalNameSupply = applyNtimes ( length tVs + 2) tcDeplete ns
applyNtimes n func arg
| n ==0 = arg
| otherwise = applyNtimes (n-1) func (func arg)
Reply TypeInfo Message
tccase tds gamma ns sw cs als res
= if length tdCNames /= length (nub cs)
then myFail
"Error in source program: missing alternatives in CASE"
else tccase1 tds gamma ns1 sw reOals reOres newTVs tdInUse
where
tdInUse = tcGetTypeDef tds cs
newTVs = tcNewTypeVars tdInUse ns2
(ns1, ns2) = tcSplit ns
merge = zip cs (zip als res)
tdCNames = map first (tcK33 tdInUse)
(reOals, reOres) = unzip2 (tcReorder tdCNames merge)
tcReorder :: [Naam] -> [(Naam,b)] -> [b]
tcReorder [] uol = []
tcReorder (k:ks) uol
= (utLookupDef uol k
(myFail
("Error in source program: undeclared constructor '" ++ k ++
"' in CASE") ) )
: tcReorder ks uol
tcDeOksel (Ok x) = x
tcDeOksel (Fail m) = panic ("tcDeOkSel: " ++ m)
tcOk13sel (Ok (a, b, c)) = a
tcOk13sel (Fail m) = panic ("tcOk13sel: " ++ m)
tcOk23sel (Ok (a, b, c)) = b
tcOk23sel (Fail m) = panic ("tcOk23sel: " ++ m)
tcOk33sel (Ok (a, b, c)) = c
tcOk33sel (Fail m) = panic ("tcOk33sel: " ++ m)
tcK31sel (a, b, c) = a
tcK33 (a,b,c) = c
tccase1 :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
CExpr ->
[[Naam]] ->
[CExpr] ->
AList Naam TVName ->
TypeDef ->
Reply TypeInfo Message
tccase1 tds gamma ns sw reOals reOres newTVs tdInUse
= tccase2 tds gamma ns2 sw reOals newTVs tdInUse rhsTcs
where
rhsGammas = tcGetAllGammas newTVs (tcK33 tdInUse) reOals
rhsTcs = rhsTc1 ns1 rhsGammas reOres
rhsTc1 nsl [] [] = []
rhsTc1 nsl (g:gs) (r:rs)
= tc tds (g++gamma) nsl1 r : rhsTc1 nsl2 gs rs
where (nsl1, nsl2) = tcSplit nsl
(ns1, ns2) = tcSplit ns
tccase2 :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
CExpr ->
[[Naam]] ->
AList Naam TVName ->
TypeDef ->
[Reply TypeInfo Message] ->
Reply TypeInfo Message
tccase2 tds gamma ns sw reOals newTVs tdInUse rhsTcs
= tccase3 tds gamma ns sw reOals newTVs tdInUse rhsTcs
phi_1_to_n tau_1_to_n phi_rhs
where
phi_1_to_n = map tcOk13sel rhsTcs
tau_1_to_n = map tcOk23sel rhsTcs
phi_rhs = tcDeOksel (tcUnifySet tcId_subst tau_1_to_n)
Reply TypeInfo Message
tccase3 tds gamma ns sw reOals newTVs tdInUse rhsTcs
phi_1_to_n tau_1_to_n phi_rhs
make up substitutions for each of the unknown tvars
merge the substitutions into one
= Ok (phi_Big, tau_final,
(tau_final, ACase tree_s
(zip tdCNames (zip reOals annotatedRHSs))))
where
phi_sTau_sTree_s = tc tds gamma ns sw
phi_s = tcOk13sel phi_sTau_sTree_s
tau_s = tcOk23sel phi_sTau_sTree_s
tree_s = tcOk33sel phi_sTau_sTree_s
phi = tcMergeSubs (concat phi_1_to_n ++ phi_rhs ++ phi_s)
tau_lhs = tcSub_type phi tdSignature
phi_Big = tcMergeSubs (tcDeOksel phi_lhs ++ phi)
tau_final = tcSub_type phi_Big (head (map tcOk23sel rhsTcs))
annotatedRHSs = map tcOk33sel rhsTcs
tVs = map second newTVs
tdSignature = TCons (tcK31sel tdInUse) (map TVar tVs)
tdCNames = map first (tcK33 tdInUse)
tcUnifySet :: Subst ->
[TExpr] ->
Reply Subst Message
tcUnifySet sub (e1:[]) = Ok sub
tcUnifySet sub (e1:e2:[])
= tcUnify sub (e1, e2)
tcUnifySet sub (e1:e2:e3:es)
= tcUnifySet newSub (e2:e3:es)
where
newSub = tcDeOksel (tcUnify sub (e1, e2))
tcNewTypeVars :: TypeDef ->
TypeNameSupply ->
AList Naam TVName
tcNewTypeVars (t, vl, c) ns = zip vl (tcName_sequence ns)
tcGetGammaN :: AList Naam TVName ->
ConstrAlt ->
[Naam] ->
AList Naam TypeScheme
tcGetGammaN tvl (cname, cal) cparams
= zip cparams (map (Scheme [] . tcTDefSubst tvl) cal)
tcTDefSubst :: AList Naam TVName ->
TDefExpr ->
TExpr
tcTDefSubst nameMap (TDefVar n)
= f result
where
f (Just tvn) = TVar tvn
f Nothing = TCons n []
result = utLookup nameMap n
tcTDefSubst nameMap (TDefCons c al)
= TCons c (map (tcTDefSubst nameMap) al)
tcGetAllGammas :: AList Naam TVName ->
[ConstrAlt] ->
[[Naam]] ->
[AList Naam TypeScheme]
tcGetAllGammas tvl [] [] = []
note param lists cparamss must be ordered in
tcGetAllGammas tvl (calt:calts) (cparams:cparamss) =
tcGetGammaN tvl calt cparams :
tcGetAllGammas tvl calts cparamss
TypeDef
tcGetTypeDef tds cs
= if length tdefset == 0
then myFail "Undeclared constructors in use"
else if length tdefset > 1
then myFail "CASE expression contains mixed constructors"
else head tdefset
where
tdefset = nub
[ (tname, ftvs, cl) |
(tname, ftvs, cl) <- tds,
usedc <- cs,
usedc `elem` (map first cl) ]
tcl :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
[CExpr] ->
Reply (Subst, [TExpr], [AnnExpr Naam TExpr]) Message
tcl tds gamma ns []
= Ok (tcId_subst, [], [])
tcl tds gamma ns (e:es)
= tcl1 tds gamma ns0 es (tc tds gamma ns1 e)
where
(ns0, ns1) = tcSplit ns
tcl1 tds gamma ns es (Fail m) = Fail m
tcl1 tds gamma ns es (Ok (phi, t, annotatedE))
= tcl2 phi t (tcl tds (tcSub_te phi gamma) ns es) annotatedE
tcl2 phi t (Fail m) annotatedE = Fail m
tcl2 phi t (Ok (psi, ts, annotatedEs)) annotatedE
= Ok (psi `tcScomp` phi, (tcSub_type psi t):ts,
annotatedE:annotatedEs)
tcvar :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
Naam ->
Reply TypeInfo Message
tcvar tds gamma ns x = Ok (tcId_subst, finalType, (finalType, AVar x))
where
scheme = tcCharVal gamma x
finalType = tcNewinstance ns scheme
tcNewinstance :: TypeNameSupply ->
TypeScheme ->
TExpr
tcNewinstance ns (Scheme scvs t) = tcSub_type phi t
where
al = scvs `zip` (tcName_sequence ns)
phi = tcAl_to_subst al
tcAl_to_subst :: AList TVName TVName ->
Subst
tcAl_to_subst al = map2nd TVar al
tcap :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
CExpr ->
CExpr ->
Reply TypeInfo Message
tcap tds gamma ns e1 e2 = tcap1 tvn (tcl tds gamma ns' [e1, e2])
where
tvn = tcNext_name ns
ns' = tcDeplete ns
tcap1 tvn (Fail m)
= Fail m
tcap1 tvn (Ok (phi, [t1, t2], [ae1, ae2]))
= tcap2 tvn (tcUnify phi (t1, t2 `TArr` (TVar tvn))) [ae1, ae2]
tcap2 tvn (Fail m) [ae1, ae2]
= Fail m
tcap2 tvn (Ok phi) [ae1, ae2]
= Ok (phi, finalType, (finalType, AAp ae1 ae2))
where
finalType = tcApply_sub phi tvn
tclambda :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
Naam ->
CExpr ->
Reply TypeInfo Message
tclambda tds gamma ns x e = tclambda1 tvn x (tc tds gamma' ns' e)
where
ns' = tcDeplete ns
gamma' = tcNew_bvar (x, tvn): gamma
tvn = tcNext_name ns
tclambda1 tvn x (Fail m) = Fail m
tclambda1 tvn x (Ok (phi, t, annotatedE)) =
Ok (phi, finalType, (finalType, ALam [x] annotatedE))
where
finalType = (tcApply_sub phi tvn) `TArr` t
tcNew_bvar (x, tvn) = (x, Scheme [] (TVar tvn))
tclet :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
[Naam] ->
[CExpr] ->
CExpr ->
Reply TypeInfo Message
tclet tds gamma ns xs es e
= tclet1 tds gamma ns0 xs e rhsTypes
where
(ns0, ns1) = tcSplit ns
rhsTypes = tcl tds gamma ns1 es
tclet1 tds gamma ns xs e (Fail m) = Fail m
tclet1 tds gamma ns xs e (Ok (phi, ts, rhsAnnExprs))
= tclet2 phi xs False (tc tds gamma'' ns1 e) rhsAnnExprs
where
gamma'' = tcAdd_decls gamma' ns0 xs ts
gamma' = tcSub_te phi gamma
(ns0, ns1) = tcSplit ns
tclet2 phi xs recFlag (Fail m) rhsAnnExprs = Fail m
tclet2 phi xs recFlag (Ok (phi', t, annotatedE)) rhsAnnExprs
= Ok (phi' `tcScomp` phi, t, (t, ALet recFlag (zip xs rhsAnnExprs) annotatedE))
tcAdd_decls :: TcTypeEnv ->
TypeNameSupply ->
[Naam] ->
[TExpr] ->
TcTypeEnv
tcAdd_decls gamma ns xs ts = (xs `zip` schemes) ++ gamma
where
schemes = map (tcGenbar unknowns ns) ts
unknowns = tcUnknowns_te gamma
tcGenbar unknowns ns t = Scheme (map second al) t'
where
al = scvs `zip` (tcName_sequence ns)
scvs = (nub (tcTvars_in t)) `tcBar` unknowns
t' = tcSub_type (tcAl_to_subst al) t
tcletrec :: [TypeDef] ->
TcTypeEnv ->
TypeNameSupply ->
[Naam] ->
[CExpr] ->
CExpr ->
Reply TypeInfo Message
tcletrec tds gamma ns xs es e
= tcletrec1 tds gamma ns0 xs nbvs e
(tcl tds (nbvs ++ gamma) ns1 es)
where
(ns0, ns') = tcSplit ns
(ns1, ns2) = tcSplit ns'
nbvs = tcNew_bvars xs ns2
tcNew_bvars xs ns = map tcNew_bvar (xs `zip` (tcName_sequence ns))
tcletrec1 tds gamma ns xs nbvs e (Fail m) = (Fail m)
tcletrec1 tds gamma ns xs nbvs e (Ok (phi, ts, rhsAnnExprs))
= tcletrec2 tds gamma' ns xs nbvs' e (tcUnifyl phi (ts `zip` ts')) rhsAnnExprs
where
ts' = map tcOld_bvar nbvs'
nbvs' = tcSub_te phi nbvs
gamma' = tcSub_te phi gamma
tcOld_bvar (x, Scheme [] t) = t
tcletrec2 tds gamma ns xs nbvs e (Fail m) rhsAnnExprs = (Fail m)
tcletrec2 tds gamma ns xs nbvs e (Ok phi) rhsAnnExprs
= tclet2 phi xs True (tc tds gamma'' ns1 e) rhsAnnExprs
where
ts = map tcOld_bvar nbvs'
nbvs' = tcSub_te phi nbvs
gamma' = tcSub_te phi gamma
gamma'' = tcAdd_decls gamma' ns0 (map first nbvs) ts
(ns0, ns1) = tcSplit ns
subnames = map first nbvs
|
4e0cb142b90fa3a2fc8fd079ec428d75f858c375b313b59659c4a1fbbe56e1b4 | techascent/tech.datatype | mmap.clj | (ns tech.v2.datatype.mmap
(:require [clojure.java.io :as io]
[tech.resource :as resource]
[tech.v2.datatype.base :as dt-base]
[tech.v2.datatype.protocols :as dtype-proto]
[tech.v2.datatype.casting :as casting]
[tech.v2.datatype.jna :as dtype-jna]
[tech.v2.datatype.typecast :as typecast]
[tech.parallel.for :as parallel-for]
[primitive-math :as pmath]
[clojure.tools.logging :as log])
(:import [xerial.larray.mmap MMapBuffer MMapMode]
[xerial.larray.buffer UnsafeUtil]
[sun.misc Unsafe]
[com.sun.jna Pointer]))
(set! *warn-on-reflection* true)
(defn unsafe
^Unsafe []
UnsafeUtil/unsafe)
(defmacro native-buffer->reader
[datatype advertised-datatype buffer address n-elems]
(let [byte-width (casting/numeric-byte-width datatype)]
`(reify
dtype-proto/PToNativeBuffer
(convertible-to-native-buffer? [this#] true)
(->native-buffer [this#] ~buffer)
;;Forward protocol methods that are efficiently implemented by the buffer
dtype-proto/PClone
(clone [this#]
(-> (dtype-proto/clone ~buffer)
(dtype-proto/->reader {})))
dtype-proto/PBuffer
(sub-buffer [this# offset# length#]
(-> (dtype-proto/sub-buffer ~buffer offset# length#)
(dtype-proto/->reader {})))
dtype-proto/PSetConstant
(set-constant! [buffer# offset# value# elem-count#]
(-> (dtype-proto/set-constant! ~buffer offset# value# elem-count#)
(dtype-proto/->reader {})))
dtype-proto/PToJNAPointer
(convertible-to-data-ptr? [item#] true)
(->jna-ptr [item#] (Pointer. ~address))
dtype-proto/PToNioBuffer
(convertible-to-nio-buffer? [item#] (< ~n-elems Integer/MAX_VALUE))
(->buffer-backing-store [item#]
(dtype-proto/->buffer-backing-store ~buffer))
~(typecast/datatype->reader-type (casting/safe-flatten datatype))
(getDatatype [rdr#] ~advertised-datatype)
(lsize [rdr#] ~n-elems)
(read [rdr# ~'idx]
~(case datatype
:int8 `(.getByte (unsafe) (pmath/+ ~address ~'idx))
:uint8 `(-> (.getByte (unsafe) (pmath/+ ~address ~'idx))
(pmath/byte->ubyte))
:int16 `(.getShort (unsafe) (pmath/+ ~address
(pmath/* ~'idx ~byte-width)))
:uint16 `(-> (.getShort (unsafe) (pmath/+ ~address
(pmath/* ~'idx ~byte-width)))
(pmath/short->ushort))
:int32 `(.getInt (unsafe) (pmath/+ ~address (pmath/* ~'idx ~byte-width)))
:uint32 `(-> (.getInt (unsafe) (pmath/+ ~address
(pmath/* ~'idx ~byte-width)))
(pmath/int->uint))
:int64 `(.getLong (unsafe) (pmath/+ ~address
(pmath/* ~'idx ~byte-width)))
:uint64 `(-> (.getLong (unsafe) (pmath/+ ~address
(pmath/* ~'idx ~byte-width))))
:float32 `(.getFloat (unsafe) (pmath/+ ~address
(pmath/* ~'idx ~byte-width)))
:float64 `(.getDouble (unsafe) (pmath/+ ~address
(pmath/* ~'idx ~byte-width))))))))
(defmacro native-buffer->writer
[datatype advertised-datatype buffer address n-elems]
(let [byte-width (casting/numeric-byte-width datatype)]
`(reify
dtype-proto/PToNativeBuffer
(convertible-to-native-buffer? [this#] true)
(->native-buffer [this#] ~buffer)
;;Forward protocol methods that are efficiently implemented by the buffer
dtype-proto/PClone
(clone [this#]
(-> (dtype-proto/clone ~buffer)
(dtype-proto/->writer {})))
dtype-proto/PBuffer
(sub-buffer [this# offset# length#]
(-> (dtype-proto/sub-buffer ~buffer offset# length#)
(dtype-proto/->writer {})))
dtype-proto/PSetConstant
(set-constant! [buffer# offset# value# elem-count#]
(-> (dtype-proto/set-constant! ~buffer offset# value# elem-count#)
(dtype-proto/->writer {})))
dtype-proto/PToJNAPointer
(convertible-to-data-ptr? [item#] true)
(->jna-ptr [item#] (Pointer. ~address))
dtype-proto/PToNioBuffer
(convertible-to-nio-buffer? [item#] (< ~n-elems Integer/MAX_VALUE))
(->buffer-backing-store [item#]
(dtype-proto/->buffer-backing-store ~buffer))
~(typecast/datatype->writer-type (casting/safe-flatten datatype))
(getDatatype [rdr#] ~advertised-datatype)
(lsize [rdr#] ~n-elems)
(write [rdr# ~'idx ~'value]
~(case datatype
:int8 `(.putByte (unsafe) (pmath/+ ~address ~'idx) ~'value)
:uint8 `(.putByte (unsafe) (pmath/+ ~address ~'idx)
(unchecked-byte ~'value))
:int16 `(.putShort (unsafe) (pmath/+ ~address (pmath/* ~'idx ~byte-width))
~'value)
:uint16 `(.putShort (unsafe) (pmath/+ ~address (pmath/* ~'idx ~byte-width))
(unchecked-short ~'value))
:int32 `(.putInt (unsafe) (pmath/+ ~address (pmath/* ~'idx ~byte-width))
~'value)
:uint32 `(.putInt (unsafe) (pmath/+ ~address (pmath/* ~'idx ~byte-width))
(unchecked-int ~'value))
:int64 `(.putLong (unsafe) (pmath/+ ~address (pmath/* ~'idx ~byte-width))
~'value)
:uint64 `(.putLong (unsafe) (pmath/+ ~address (pmath/* ~'idx ~byte-width))
~'value)
:float32 `(.putFloat (unsafe)
(pmath/+ ~address (pmath/* ~'idx ~byte-width))
~'value)
:float64 `(.putDouble (unsafe)
(pmath/+ ~address (pmath/* ~'idx ~byte-width))
~'value))))))
;;Size is in elements, not in bytes
(defrecord NativeBuffer [^long address ^long n-elems datatype]
dtype-proto/PToNativeBuffer
(convertible-to-native-buffer? [this] true)
(->native-buffer [this] this)
dtype-proto/PDatatype
(get-datatype [this] datatype)
dtype-proto/PCountable
(ecount [this] n-elems)
dtype-proto/PClone
(clone [this]
(dt-base/make-container
(if (casting/unsigned-integer-type? datatype)
:typed-buffer
:java-array)
datatype
this))
dtype-proto/PBuffer
(sub-buffer [this offset length]
(let [offset (long offset)
length (long length)]
(when-not (<= (+ offset length) n-elems)
(throw (Exception.
(format "Offset+length (%s) > n-elems (%s)"
(+ offset length) n-elems))))
(NativeBuffer. (+ address offset) length datatype)))
dtype-proto/PSetConstant
(set-constant! [buffer offset value elem-count]
(if (or (= datatype :int8)
(= (double value) 0.0))
(.setMemory (unsafe) (+ address (long offset))
(* (long elem-count) (casting/numeric-byte-width datatype))
(byte value))
(let [writer (dt-base/->writer (dt-base/sub-buffer buffer offset elem-count))
value (casting/cast value datatype)]
(dotimes [iter elem-count]
(writer iter value)))))
dtype-proto/PToJNAPointer
(convertible-to-data-ptr? [item#] true)
(->jna-ptr [item#] (Pointer. address))
dtype-proto/PToNioBuffer
(convertible-to-nio-buffer? [item#] (< n-elems Integer/MAX_VALUE))
(->buffer-backing-store [item#]
(let [ptr (Pointer. address)
unaliased-dtype (casting/un-alias-datatype datatype)
n-bytes (* n-elems (casting/numeric-byte-width unaliased-dtype))]
(dtype-jna/pointer->nio-buffer ptr unaliased-dtype n-bytes)))
dtype-proto/PToReader
(convertible-to-reader? [this] true)
(->reader [this options]
(-> (case (casting/un-alias-datatype datatype)
:int8 (native-buffer->reader :int8 datatype this address n-elems)
:uint8 (native-buffer->reader :uint8 datatype this address n-elems)
:int16 (native-buffer->reader :int16 datatype this address n-elems)
:uint16 (native-buffer->reader :uint16 datatype this address n-elems)
:int32 (native-buffer->reader :int32 datatype this address n-elems)
:uint32 (native-buffer->reader :uint32 datatype this address n-elems)
:int64 (native-buffer->reader :int64 datatype this address n-elems)
:uint64 (native-buffer->reader :uint64 datatype this address n-elems)
:float32 (native-buffer->reader :float32 datatype this address n-elems)
:float64 (native-buffer->reader :float64 datatype this address n-elems))
(dtype-proto/->reader options)))
dtype-proto/PToWriter
(convertible-to-writer? [this] true)
(->writer [this options]
(-> (case (casting/un-alias-datatype datatype)
:int8 (native-buffer->writer :int8 datatype this address n-elems)
:uint8 (native-buffer->writer :uint8 datatype this address n-elems)
:int16 (native-buffer->writer :int16 datatype this address n-elems)
:uint16 (native-buffer->writer :uint16 datatype this address n-elems)
:int32 (native-buffer->writer :int32 datatype this address n-elems)
:uint32 (native-buffer->writer :uint32 datatype this address n-elems)
:int64 (native-buffer->writer :int64 datatype this address n-elems)
:uint64 (native-buffer->writer :uint64 datatype this address n-elems)
:float32 (native-buffer->writer :float32 datatype this address n-elems)
:float64 (native-buffer->writer :float64 datatype this address n-elems))
(dtype-proto/->writer options))))
(extend-type Object
dtype-proto/PToNativeBuffer
(convertible-to-native-buffer? [item]
(dtype-proto/convertible-to-data-ptr? item))
(->native-buffer [item]
(let [^Pointer data-ptr (dtype-proto/->jna-ptr item)]
(NativeBuffer. (Pointer/nativeValue data-ptr)
(dt-base/ecount item)
(dt-base/get-datatype item)))))
(defn as-native-buffer
^NativeBuffer [item]
(when (dtype-proto/convertible-to-native-buffer? item)
(dtype-proto/->native-buffer item)))
(defn set-native-datatype
^NativeBuffer [item datatype]
(if-let [nb (as-native-buffer item)]
(let [original-size (.n-elems nb)
n-bytes (* original-size (casting/numeric-byte-width
(dt-base/get-datatype item)))
new-byte-width (casting/numeric-byte-width
(casting/un-alias-datatype datatype))]
(NativeBuffer. (.address nb) (quot n-bytes new-byte-width) datatype))))
One off data reading
(defn read-double
(^double [^NativeBuffer native-buffer ^long offset]
(assert (>= (- (.n-elems native-buffer) offset 8) 0))
(.getDouble (unsafe) (+ (.address native-buffer) offset)))
(^double [^NativeBuffer native-buffer]
(assert (>= (- (.n-elems native-buffer) 8) 0))
(.getDouble (unsafe) (.address native-buffer))))
(defn read-float
(^double [^NativeBuffer native-buffer ^long offset]
(assert (>= (- (.n-elems native-buffer) offset 4) 0))
(.getFloat (unsafe) (+ (.address native-buffer) offset)))
(^double [^NativeBuffer native-buffer]
(assert (>= (- (.n-elems native-buffer) 4) 0))
(.getFloat (unsafe) (.address native-buffer))))
(defn read-long
(^long [^NativeBuffer native-buffer ^long offset]
(assert (>= (- (.n-elems native-buffer) offset 8) 0))
(.getLong (unsafe) (+ (.address native-buffer) offset)))
(^long [^NativeBuffer native-buffer]
(assert (>= (- (.n-elems native-buffer) 8) 0))
(.getLong (unsafe) (.address native-buffer))))
(defn read-int
(^long [^NativeBuffer native-buffer ^long offset]
(assert (>= (- (.n-elems native-buffer) offset 4) 0))
(.getInt (unsafe) (+ (.address native-buffer) offset)))
(^long [^NativeBuffer native-buffer]
(assert (>= (- (.n-elems native-buffer) 4) 0))
(.getInt (unsafe) (.address native-buffer))))
(defn read-short
(^long [^NativeBuffer native-buffer ^long offset]
(assert (>= (- (.n-elems native-buffer) offset 2) 0))
(unchecked-long
(.getShort (unsafe) (+ (.address native-buffer) offset))))
(^long [^NativeBuffer native-buffer]
(assert (>= (- (.n-elems native-buffer) 2) 0))
(unchecked-long
(.getShort (unsafe) (.address native-buffer)))))
(defn read-byte
(^long [^NativeBuffer native-buffer ^long offset]
(assert (>= (- (.n-elems native-buffer) offset 1) 0))
(unchecked-long
(.getByte (unsafe) (+ (.address native-buffer) offset))))
(^long [^NativeBuffer native-buffer]
(assert (>= (- (.n-elems native-buffer) 1) 0))
(unchecked-long
(.getByte (unsafe) (.address native-buffer)))))
(defn- unpack-copy-item
[item ^long item-off]
(if (instance? NativeBuffer item)
;;no further offsetting required for native buffers
[nil (+ item-off (.address ^NativeBuffer item))]
(let [ary (:java-array item)
ary-off (:offset item)]
[ary (+ item-off ary-off
(case (dt-base/get-datatype ary)
:boolean Unsafe/ARRAY_BOOLEAN_BASE_OFFSET
:int8 Unsafe/ARRAY_BYTE_BASE_OFFSET
:int16 Unsafe/ARRAY_SHORT_BASE_OFFSET
:int32 Unsafe/ARRAY_INT_BASE_OFFSET
:int64 Unsafe/ARRAY_LONG_BASE_OFFSET
:float32 Unsafe/ARRAY_FLOAT_BASE_OFFSET
:float64 Unsafe/ARRAY_DOUBLE_BASE_OFFSET))])))
(defn copy!
"Src, dst *must* be same unaliased datatype and that datatype must be a primitive
datatype.
src must either be convertible to an array or to a native buffer.
dst must either be convertible to an array or to a native buffer.
Uses Unsafe/copyMemory under the covers *without* safePointPolling.
Returns dst"
([src src-off dst dst-off n-elems]
(let [src-dt (casting/host-flatten (dt-base/get-datatype src))
dst-dt (casting/host-flatten (dt-base/get-datatype dst))
src-ec (dt-base/ecount src)
dst-ec (dt-base/ecount dst)
src-off (long src-off)
dst-off (long dst-off)
n-elems (long n-elems)
_ (when-not (>= (- src-ec src-off) n-elems)
(throw (Exception. (format "Src ecount (%s) - src offset (^%s) is less than op elem count (%s)"
src-ec src-off n-elems))))
_ (when-not (>= (- dst-ec dst-off) n-elems)
(throw (Exception. (format "Dst ecount (%s) - dst offset (^%s) is less than op elem count (%s)"
dst-ec dst-off n-elems))))
_ (when-not (= src-dt dst-dt)
(throw (Exception. (format "src datatype (%s) != dst datatype (%s)"
src-dt dst-dt))))]
;;Check if managed heap or native heap
(let [src (or (dtype-proto/->sub-array src) (dtype-proto/->native-buffer src))
dst (or (dtype-proto/->sub-array dst) (dtype-proto/->native-buffer dst))
_ (when-not (and src dst)
(throw (Exception.
"Src or dst are not convertible to arrays or native buffers")))
[src src-off] (unpack-copy-item src src-off)
[dst dst-off] (unpack-copy-item dst dst-off)]
(if (< n-elems 1024)
(.copyMemory (unsafe) src (long src-off) dst (long dst-off)
(* n-elems (casting/numeric-byte-width
(casting/un-alias-datatype src-dt))))
(parallel-for/indexed-map-reduce
n-elems
(fn [^long start-idx ^long group-len]
(.copyMemory (unsafe)
src (+ (long src-off) start-idx)
dst (+ (long dst-off) start-idx)
(* group-len (casting/numeric-byte-width
(casting/un-alias-datatype src-dt)))))))
dst)))
([src dst n-elems]
(copy! src 0 dst 0 n-elems))
([src dst]
(let [src-ec (dt-base/ecount src)
dst-ec (dt-base/ecount dst)]
(when-not (== src-ec dst-ec)
(throw (Exception. (format "src ecount (%s) != dst ecount (%s)"
src-ec dst-ec))))
(copy! src 0 dst 0 src-ec))))
(defn free
[data]
(let [addr (long (if (instance? NativeBuffer data)
(.address ^NativeBuffer data)
(long data)))]
(when-not (== 0 addr)
(.freeMemory (unsafe) addr))))
(defn malloc
(^NativeBuffer [^long n-bytes {:keys [resource-type]
:or {resource-type :stack}}]
(let [retval (NativeBuffer. (.allocateMemory (unsafe) n-bytes)
n-bytes
:int8)
addr (.address retval)]
(when resource-type
(resource/track retval #(free addr) resource-type))
retval))
(^NativeBuffer [^long n-bytes]
(malloc n-bytes {})))
(defn mmap-file
"Memory map a file returning a native buffer. fpath must resolve to a valid
java.io.File.
Options
* :resource-type - Chose the type of resource management to use with the returned
value:
* `:stack` - default - mmap-file call must be wrapped in a call to
tech.resource/stack-resource-context and will be cleaned up when control leaves
the form.
* `:gc` - The mmaped file will be cleaned up when the garbage collection system
decides to collect the returned native buffer.
* `nil` - The mmaped file will never be cleaned up.
* :mmap-mode
* :read-only - default - map the data as shared read-only.
* :read-write - map the data as shared read-write.
* :private - map a private copy of the data and do not share."
([fpath {:keys [resource-type mmap-mode]
:or {resource-type :stack
mmap-mode :read-only}}]
(let [file (io/file fpath)
_ (when-not (.exists file)
(throw (Exception. (format "%s not found" fpath))))
;;Mapping to read-only means pages can be shared between processes
map-buf (MMapBuffer. file (case mmap-mode
:read-only MMapMode/READ_ONLY
:read-write MMapMode/READ_WRITE
:private MMapMode/PRIVATE))]
(if resource-type
(resource/track map-buf
#(do (log/debugf "closing %s" fpath) (.close map-buf))
resource-type)
(log/debugf "No resource type specified for mmaped file %s" fpath))
(->NativeBuffer (.address map-buf) (.size map-buf) :int8)))
([fpath]
(mmap-file fpath {})))
| null | https://raw.githubusercontent.com/techascent/tech.datatype/8cc83d771d9621d580fd5d4d0625005bd7ab0e0c/src/tech/v2/datatype/mmap.clj | clojure | Forward protocol methods that are efficiently implemented by the buffer
Forward protocol methods that are efficiently implemented by the buffer
Size is in elements, not in bytes
no further offsetting required for native buffers
Check if managed heap or native heap
Mapping to read-only means pages can be shared between processes | (ns tech.v2.datatype.mmap
(:require [clojure.java.io :as io]
[tech.resource :as resource]
[tech.v2.datatype.base :as dt-base]
[tech.v2.datatype.protocols :as dtype-proto]
[tech.v2.datatype.casting :as casting]
[tech.v2.datatype.jna :as dtype-jna]
[tech.v2.datatype.typecast :as typecast]
[tech.parallel.for :as parallel-for]
[primitive-math :as pmath]
[clojure.tools.logging :as log])
(:import [xerial.larray.mmap MMapBuffer MMapMode]
[xerial.larray.buffer UnsafeUtil]
[sun.misc Unsafe]
[com.sun.jna Pointer]))
(set! *warn-on-reflection* true)
(defn unsafe
^Unsafe []
UnsafeUtil/unsafe)
(defmacro native-buffer->reader
[datatype advertised-datatype buffer address n-elems]
(let [byte-width (casting/numeric-byte-width datatype)]
`(reify
dtype-proto/PToNativeBuffer
(convertible-to-native-buffer? [this#] true)
(->native-buffer [this#] ~buffer)
dtype-proto/PClone
(clone [this#]
(-> (dtype-proto/clone ~buffer)
(dtype-proto/->reader {})))
dtype-proto/PBuffer
(sub-buffer [this# offset# length#]
(-> (dtype-proto/sub-buffer ~buffer offset# length#)
(dtype-proto/->reader {})))
dtype-proto/PSetConstant
(set-constant! [buffer# offset# value# elem-count#]
(-> (dtype-proto/set-constant! ~buffer offset# value# elem-count#)
(dtype-proto/->reader {})))
dtype-proto/PToJNAPointer
(convertible-to-data-ptr? [item#] true)
(->jna-ptr [item#] (Pointer. ~address))
dtype-proto/PToNioBuffer
(convertible-to-nio-buffer? [item#] (< ~n-elems Integer/MAX_VALUE))
(->buffer-backing-store [item#]
(dtype-proto/->buffer-backing-store ~buffer))
~(typecast/datatype->reader-type (casting/safe-flatten datatype))
(getDatatype [rdr#] ~advertised-datatype)
(lsize [rdr#] ~n-elems)
(read [rdr# ~'idx]
~(case datatype
:int8 `(.getByte (unsafe) (pmath/+ ~address ~'idx))
:uint8 `(-> (.getByte (unsafe) (pmath/+ ~address ~'idx))
(pmath/byte->ubyte))
:int16 `(.getShort (unsafe) (pmath/+ ~address
(pmath/* ~'idx ~byte-width)))
:uint16 `(-> (.getShort (unsafe) (pmath/+ ~address
(pmath/* ~'idx ~byte-width)))
(pmath/short->ushort))
:int32 `(.getInt (unsafe) (pmath/+ ~address (pmath/* ~'idx ~byte-width)))
:uint32 `(-> (.getInt (unsafe) (pmath/+ ~address
(pmath/* ~'idx ~byte-width)))
(pmath/int->uint))
:int64 `(.getLong (unsafe) (pmath/+ ~address
(pmath/* ~'idx ~byte-width)))
:uint64 `(-> (.getLong (unsafe) (pmath/+ ~address
(pmath/* ~'idx ~byte-width))))
:float32 `(.getFloat (unsafe) (pmath/+ ~address
(pmath/* ~'idx ~byte-width)))
:float64 `(.getDouble (unsafe) (pmath/+ ~address
(pmath/* ~'idx ~byte-width))))))))
(defmacro native-buffer->writer
[datatype advertised-datatype buffer address n-elems]
(let [byte-width (casting/numeric-byte-width datatype)]
`(reify
dtype-proto/PToNativeBuffer
(convertible-to-native-buffer? [this#] true)
(->native-buffer [this#] ~buffer)
dtype-proto/PClone
(clone [this#]
(-> (dtype-proto/clone ~buffer)
(dtype-proto/->writer {})))
dtype-proto/PBuffer
(sub-buffer [this# offset# length#]
(-> (dtype-proto/sub-buffer ~buffer offset# length#)
(dtype-proto/->writer {})))
dtype-proto/PSetConstant
(set-constant! [buffer# offset# value# elem-count#]
(-> (dtype-proto/set-constant! ~buffer offset# value# elem-count#)
(dtype-proto/->writer {})))
dtype-proto/PToJNAPointer
(convertible-to-data-ptr? [item#] true)
(->jna-ptr [item#] (Pointer. ~address))
dtype-proto/PToNioBuffer
(convertible-to-nio-buffer? [item#] (< ~n-elems Integer/MAX_VALUE))
(->buffer-backing-store [item#]
(dtype-proto/->buffer-backing-store ~buffer))
~(typecast/datatype->writer-type (casting/safe-flatten datatype))
(getDatatype [rdr#] ~advertised-datatype)
(lsize [rdr#] ~n-elems)
(write [rdr# ~'idx ~'value]
~(case datatype
:int8 `(.putByte (unsafe) (pmath/+ ~address ~'idx) ~'value)
:uint8 `(.putByte (unsafe) (pmath/+ ~address ~'idx)
(unchecked-byte ~'value))
:int16 `(.putShort (unsafe) (pmath/+ ~address (pmath/* ~'idx ~byte-width))
~'value)
:uint16 `(.putShort (unsafe) (pmath/+ ~address (pmath/* ~'idx ~byte-width))
(unchecked-short ~'value))
:int32 `(.putInt (unsafe) (pmath/+ ~address (pmath/* ~'idx ~byte-width))
~'value)
:uint32 `(.putInt (unsafe) (pmath/+ ~address (pmath/* ~'idx ~byte-width))
(unchecked-int ~'value))
:int64 `(.putLong (unsafe) (pmath/+ ~address (pmath/* ~'idx ~byte-width))
~'value)
:uint64 `(.putLong (unsafe) (pmath/+ ~address (pmath/* ~'idx ~byte-width))
~'value)
:float32 `(.putFloat (unsafe)
(pmath/+ ~address (pmath/* ~'idx ~byte-width))
~'value)
:float64 `(.putDouble (unsafe)
(pmath/+ ~address (pmath/* ~'idx ~byte-width))
~'value))))))
(defrecord NativeBuffer [^long address ^long n-elems datatype]
dtype-proto/PToNativeBuffer
(convertible-to-native-buffer? [this] true)
(->native-buffer [this] this)
dtype-proto/PDatatype
(get-datatype [this] datatype)
dtype-proto/PCountable
(ecount [this] n-elems)
dtype-proto/PClone
(clone [this]
(dt-base/make-container
(if (casting/unsigned-integer-type? datatype)
:typed-buffer
:java-array)
datatype
this))
dtype-proto/PBuffer
(sub-buffer [this offset length]
(let [offset (long offset)
length (long length)]
(when-not (<= (+ offset length) n-elems)
(throw (Exception.
(format "Offset+length (%s) > n-elems (%s)"
(+ offset length) n-elems))))
(NativeBuffer. (+ address offset) length datatype)))
dtype-proto/PSetConstant
(set-constant! [buffer offset value elem-count]
(if (or (= datatype :int8)
(= (double value) 0.0))
(.setMemory (unsafe) (+ address (long offset))
(* (long elem-count) (casting/numeric-byte-width datatype))
(byte value))
(let [writer (dt-base/->writer (dt-base/sub-buffer buffer offset elem-count))
value (casting/cast value datatype)]
(dotimes [iter elem-count]
(writer iter value)))))
dtype-proto/PToJNAPointer
(convertible-to-data-ptr? [item#] true)
(->jna-ptr [item#] (Pointer. address))
dtype-proto/PToNioBuffer
(convertible-to-nio-buffer? [item#] (< n-elems Integer/MAX_VALUE))
(->buffer-backing-store [item#]
(let [ptr (Pointer. address)
unaliased-dtype (casting/un-alias-datatype datatype)
n-bytes (* n-elems (casting/numeric-byte-width unaliased-dtype))]
(dtype-jna/pointer->nio-buffer ptr unaliased-dtype n-bytes)))
dtype-proto/PToReader
(convertible-to-reader? [this] true)
(->reader [this options]
(-> (case (casting/un-alias-datatype datatype)
:int8 (native-buffer->reader :int8 datatype this address n-elems)
:uint8 (native-buffer->reader :uint8 datatype this address n-elems)
:int16 (native-buffer->reader :int16 datatype this address n-elems)
:uint16 (native-buffer->reader :uint16 datatype this address n-elems)
:int32 (native-buffer->reader :int32 datatype this address n-elems)
:uint32 (native-buffer->reader :uint32 datatype this address n-elems)
:int64 (native-buffer->reader :int64 datatype this address n-elems)
:uint64 (native-buffer->reader :uint64 datatype this address n-elems)
:float32 (native-buffer->reader :float32 datatype this address n-elems)
:float64 (native-buffer->reader :float64 datatype this address n-elems))
(dtype-proto/->reader options)))
dtype-proto/PToWriter
(convertible-to-writer? [this] true)
(->writer [this options]
(-> (case (casting/un-alias-datatype datatype)
:int8 (native-buffer->writer :int8 datatype this address n-elems)
:uint8 (native-buffer->writer :uint8 datatype this address n-elems)
:int16 (native-buffer->writer :int16 datatype this address n-elems)
:uint16 (native-buffer->writer :uint16 datatype this address n-elems)
:int32 (native-buffer->writer :int32 datatype this address n-elems)
:uint32 (native-buffer->writer :uint32 datatype this address n-elems)
:int64 (native-buffer->writer :int64 datatype this address n-elems)
:uint64 (native-buffer->writer :uint64 datatype this address n-elems)
:float32 (native-buffer->writer :float32 datatype this address n-elems)
:float64 (native-buffer->writer :float64 datatype this address n-elems))
(dtype-proto/->writer options))))
(extend-type Object
dtype-proto/PToNativeBuffer
(convertible-to-native-buffer? [item]
(dtype-proto/convertible-to-data-ptr? item))
(->native-buffer [item]
(let [^Pointer data-ptr (dtype-proto/->jna-ptr item)]
(NativeBuffer. (Pointer/nativeValue data-ptr)
(dt-base/ecount item)
(dt-base/get-datatype item)))))
(defn as-native-buffer
^NativeBuffer [item]
(when (dtype-proto/convertible-to-native-buffer? item)
(dtype-proto/->native-buffer item)))
(defn set-native-datatype
^NativeBuffer [item datatype]
(if-let [nb (as-native-buffer item)]
(let [original-size (.n-elems nb)
n-bytes (* original-size (casting/numeric-byte-width
(dt-base/get-datatype item)))
new-byte-width (casting/numeric-byte-width
(casting/un-alias-datatype datatype))]
(NativeBuffer. (.address nb) (quot n-bytes new-byte-width) datatype))))
One off data reading
(defn read-double
(^double [^NativeBuffer native-buffer ^long offset]
(assert (>= (- (.n-elems native-buffer) offset 8) 0))
(.getDouble (unsafe) (+ (.address native-buffer) offset)))
(^double [^NativeBuffer native-buffer]
(assert (>= (- (.n-elems native-buffer) 8) 0))
(.getDouble (unsafe) (.address native-buffer))))
(defn read-float
(^double [^NativeBuffer native-buffer ^long offset]
(assert (>= (- (.n-elems native-buffer) offset 4) 0))
(.getFloat (unsafe) (+ (.address native-buffer) offset)))
(^double [^NativeBuffer native-buffer]
(assert (>= (- (.n-elems native-buffer) 4) 0))
(.getFloat (unsafe) (.address native-buffer))))
(defn read-long
(^long [^NativeBuffer native-buffer ^long offset]
(assert (>= (- (.n-elems native-buffer) offset 8) 0))
(.getLong (unsafe) (+ (.address native-buffer) offset)))
(^long [^NativeBuffer native-buffer]
(assert (>= (- (.n-elems native-buffer) 8) 0))
(.getLong (unsafe) (.address native-buffer))))
(defn read-int
(^long [^NativeBuffer native-buffer ^long offset]
(assert (>= (- (.n-elems native-buffer) offset 4) 0))
(.getInt (unsafe) (+ (.address native-buffer) offset)))
(^long [^NativeBuffer native-buffer]
(assert (>= (- (.n-elems native-buffer) 4) 0))
(.getInt (unsafe) (.address native-buffer))))
(defn read-short
(^long [^NativeBuffer native-buffer ^long offset]
(assert (>= (- (.n-elems native-buffer) offset 2) 0))
(unchecked-long
(.getShort (unsafe) (+ (.address native-buffer) offset))))
(^long [^NativeBuffer native-buffer]
(assert (>= (- (.n-elems native-buffer) 2) 0))
(unchecked-long
(.getShort (unsafe) (.address native-buffer)))))
(defn read-byte
(^long [^NativeBuffer native-buffer ^long offset]
(assert (>= (- (.n-elems native-buffer) offset 1) 0))
(unchecked-long
(.getByte (unsafe) (+ (.address native-buffer) offset))))
(^long [^NativeBuffer native-buffer]
(assert (>= (- (.n-elems native-buffer) 1) 0))
(unchecked-long
(.getByte (unsafe) (.address native-buffer)))))
(defn- unpack-copy-item
[item ^long item-off]
(if (instance? NativeBuffer item)
[nil (+ item-off (.address ^NativeBuffer item))]
(let [ary (:java-array item)
ary-off (:offset item)]
[ary (+ item-off ary-off
(case (dt-base/get-datatype ary)
:boolean Unsafe/ARRAY_BOOLEAN_BASE_OFFSET
:int8 Unsafe/ARRAY_BYTE_BASE_OFFSET
:int16 Unsafe/ARRAY_SHORT_BASE_OFFSET
:int32 Unsafe/ARRAY_INT_BASE_OFFSET
:int64 Unsafe/ARRAY_LONG_BASE_OFFSET
:float32 Unsafe/ARRAY_FLOAT_BASE_OFFSET
:float64 Unsafe/ARRAY_DOUBLE_BASE_OFFSET))])))
(defn copy!
"Src, dst *must* be same unaliased datatype and that datatype must be a primitive
datatype.
src must either be convertible to an array or to a native buffer.
dst must either be convertible to an array or to a native buffer.
Uses Unsafe/copyMemory under the covers *without* safePointPolling.
Returns dst"
([src src-off dst dst-off n-elems]
(let [src-dt (casting/host-flatten (dt-base/get-datatype src))
dst-dt (casting/host-flatten (dt-base/get-datatype dst))
src-ec (dt-base/ecount src)
dst-ec (dt-base/ecount dst)
src-off (long src-off)
dst-off (long dst-off)
n-elems (long n-elems)
_ (when-not (>= (- src-ec src-off) n-elems)
(throw (Exception. (format "Src ecount (%s) - src offset (^%s) is less than op elem count (%s)"
src-ec src-off n-elems))))
_ (when-not (>= (- dst-ec dst-off) n-elems)
(throw (Exception. (format "Dst ecount (%s) - dst offset (^%s) is less than op elem count (%s)"
dst-ec dst-off n-elems))))
_ (when-not (= src-dt dst-dt)
(throw (Exception. (format "src datatype (%s) != dst datatype (%s)"
src-dt dst-dt))))]
(let [src (or (dtype-proto/->sub-array src) (dtype-proto/->native-buffer src))
dst (or (dtype-proto/->sub-array dst) (dtype-proto/->native-buffer dst))
_ (when-not (and src dst)
(throw (Exception.
"Src or dst are not convertible to arrays or native buffers")))
[src src-off] (unpack-copy-item src src-off)
[dst dst-off] (unpack-copy-item dst dst-off)]
(if (< n-elems 1024)
(.copyMemory (unsafe) src (long src-off) dst (long dst-off)
(* n-elems (casting/numeric-byte-width
(casting/un-alias-datatype src-dt))))
(parallel-for/indexed-map-reduce
n-elems
(fn [^long start-idx ^long group-len]
(.copyMemory (unsafe)
src (+ (long src-off) start-idx)
dst (+ (long dst-off) start-idx)
(* group-len (casting/numeric-byte-width
(casting/un-alias-datatype src-dt)))))))
dst)))
([src dst n-elems]
(copy! src 0 dst 0 n-elems))
([src dst]
(let [src-ec (dt-base/ecount src)
dst-ec (dt-base/ecount dst)]
(when-not (== src-ec dst-ec)
(throw (Exception. (format "src ecount (%s) != dst ecount (%s)"
src-ec dst-ec))))
(copy! src 0 dst 0 src-ec))))
(defn free
[data]
(let [addr (long (if (instance? NativeBuffer data)
(.address ^NativeBuffer data)
(long data)))]
(when-not (== 0 addr)
(.freeMemory (unsafe) addr))))
(defn malloc
(^NativeBuffer [^long n-bytes {:keys [resource-type]
:or {resource-type :stack}}]
(let [retval (NativeBuffer. (.allocateMemory (unsafe) n-bytes)
n-bytes
:int8)
addr (.address retval)]
(when resource-type
(resource/track retval #(free addr) resource-type))
retval))
(^NativeBuffer [^long n-bytes]
(malloc n-bytes {})))
(defn mmap-file
"Memory map a file returning a native buffer. fpath must resolve to a valid
java.io.File.
Options
* :resource-type - Chose the type of resource management to use with the returned
value:
* `:stack` - default - mmap-file call must be wrapped in a call to
tech.resource/stack-resource-context and will be cleaned up when control leaves
the form.
* `:gc` - The mmaped file will be cleaned up when the garbage collection system
decides to collect the returned native buffer.
* `nil` - The mmaped file will never be cleaned up.
* :mmap-mode
* :read-only - default - map the data as shared read-only.
* :read-write - map the data as shared read-write.
* :private - map a private copy of the data and do not share."
([fpath {:keys [resource-type mmap-mode]
:or {resource-type :stack
mmap-mode :read-only}}]
(let [file (io/file fpath)
_ (when-not (.exists file)
(throw (Exception. (format "%s not found" fpath))))
map-buf (MMapBuffer. file (case mmap-mode
:read-only MMapMode/READ_ONLY
:read-write MMapMode/READ_WRITE
:private MMapMode/PRIVATE))]
(if resource-type
(resource/track map-buf
#(do (log/debugf "closing %s" fpath) (.close map-buf))
resource-type)
(log/debugf "No resource type specified for mmaped file %s" fpath))
(->NativeBuffer (.address map-buf) (.size map-buf) :int8)))
([fpath]
(mmap-file fpath {})))
|
8857fa634932e57af1dcc7a70121ac1e289d207230061d3b2bea8807880a5078 | bradlucas/ads-txt-crawler | project.clj | (defproject com.bradlucas/ads-txt-crawler "0.0.9"
:description "An implementation of a crawler for Ads.txt files written in Clojure"
:url "-txt-crawler"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/tools.cli "0.3.5"]
[clojurewerkz/urly "1.0.0"]
[http-kit "2.3.0-alpha4"]
[org.clojure/java.jdbc "0.7.2"]
[org.xerial/sqlite-jdbc "3.20.0"]]
:target-path "target/%s"
:profiles {:uberjar {:uberjar-name "ads-txt-crawler-standalone.jar" :aot :all}}
:deploy-repositories [["releases" {:url ""
:creds :gpg}]]
:main ^:skip-aot ads-txt-crawler.core)
| null | https://raw.githubusercontent.com/bradlucas/ads-txt-crawler/1deae9e8d976280b2aa01a41f7db06777b9e69b5/project.clj | clojure | (defproject com.bradlucas/ads-txt-crawler "0.0.9"
:description "An implementation of a crawler for Ads.txt files written in Clojure"
:url "-txt-crawler"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/tools.cli "0.3.5"]
[clojurewerkz/urly "1.0.0"]
[http-kit "2.3.0-alpha4"]
[org.clojure/java.jdbc "0.7.2"]
[org.xerial/sqlite-jdbc "3.20.0"]]
:target-path "target/%s"
:profiles {:uberjar {:uberjar-name "ads-txt-crawler-standalone.jar" :aot :all}}
:deploy-repositories [["releases" {:url ""
:creds :gpg}]]
:main ^:skip-aot ads-txt-crawler.core)
|
|
b3cda4d152a20c479888ebb037a1127c8805ac0eaf784bee4e7c82dd5a531a36 | nikita-volkov/rerebase | Internal.hs | module Data.ByteString.Builder.Internal
(
module Rebase.Data.ByteString.Builder.Internal
)
where
import Rebase.Data.ByteString.Builder.Internal
| null | https://raw.githubusercontent.com/nikita-volkov/rerebase/25895e6d8b0c515c912c509ad8dd8868780a74b6/library/Data/ByteString/Builder/Internal.hs | haskell | module Data.ByteString.Builder.Internal
(
module Rebase.Data.ByteString.Builder.Internal
)
where
import Rebase.Data.ByteString.Builder.Internal
|
|
89f190b20b8107dc273adba8358888179f32df64834dee19248514a2aab076af | vaclavsvejcar/headroom | FileSupport.hs | {-# LANGUAGE MultiWayIf #-}
# LANGUAGE RecordWildCards #
# LANGUAGE ViewPatterns #
# LANGUAGE NoImplicitPrelude #
-- |
Module : Headroom . FileSupport
-- Description : Support for handling various source code file types
Copyright : ( c ) 2019 - 2022
-- License : BSD-3-Clause
-- Maintainer :
-- Stability : experimental
-- Portability : POSIX
--
-- /Headroom/ currently supports working with file types defined in 'FileType'
-- type, and because every type of source code file requires different handling of
-- some aspects, this file type specific support is implemented for every supported
file type and exposed as instance of ' FileSupport ' data type .
module Headroom.FileSupport
( fileSupport
, analyzeSourceCode
)
where
import Control.Monad.State
( get
, put
)
import qualified Headroom.FileSupport.C as C
import qualified Headroom.FileSupport.CPP as CPP
import qualified Headroom.FileSupport.CSS as CSS
import qualified Headroom.FileSupport.Dart as Dart
import qualified Headroom.FileSupport.Go as Go
import qualified Headroom.FileSupport.HTML as HTML
import qualified Headroom.FileSupport.Haskell as Haskell
import qualified Headroom.FileSupport.JS as JS
import qualified Headroom.FileSupport.Java as Java
import qualified Headroom.FileSupport.Kotlin as Kotlin
import qualified Headroom.FileSupport.PHP as PHP
import qualified Headroom.FileSupport.PureScript as PureScript
import qualified Headroom.FileSupport.Python as Python
import qualified Headroom.FileSupport.Rust as Rust
import qualified Headroom.FileSupport.Scala as Scala
import qualified Headroom.FileSupport.Shell as Shell
import Headroom.FileSupport.Types
( FileSupport (..)
, SyntaxAnalysis (..)
)
import qualified Headroom.FileSupport.XML as XML
import Headroom.FileType.Types (FileType (..))
import Headroom.SourceCode
( LineType (..)
, SourceCode
, fromText
)
import RIO
import qualified RIO.Text as T
------------------------------ PUBLIC FUNCTIONS ------------------------------
| Returns ' FileSupport ' for corresponding ' FileType ' .
fileSupport :: FileType -> FileSupport
fileSupport C = C.fileSupport
fileSupport CPP = CPP.fileSupport
fileSupport CSS = CSS.fileSupport
fileSupport Dart = Dart.fileSupport
fileSupport Go = Go.fileSupport
fileSupport Haskell = Haskell.fileSupport
fileSupport HTML = HTML.fileSupport
fileSupport Java = Java.fileSupport
fileSupport JS = JS.fileSupport
fileSupport Kotlin = Kotlin.fileSupport
fileSupport PHP = PHP.fileSupport
fileSupport PureScript = PureScript.fileSupport
fileSupport Python = Python.fileSupport
fileSupport Rust = Rust.fileSupport
fileSupport Scala = Scala.fileSupport
fileSupport Shell = Shell.fileSupport
fileSupport XML = XML.fileSupport
| Analyzes the raw source code of given type using provided ' FileSupport ' .
analyzeSourceCode
:: FileSupport
^ ' FileSupport ' implementation used for analysis
-> Text
-- ^ raw source code to analyze
-> SourceCode
-- ^ analyzed source code
analyzeSourceCode fs = fromText state0 process
where
SyntaxAnalysis{..} = fsSyntaxAnalysis fs
state0 = 0 :: Int
process (T.strip -> l) = do
cs <- get
let isStart = saIsCommentStart
isEnd = saIsCommentEnd
tpe = \c -> if c > 0 then Comment else Code
(ns, res) =
if
| isStart l && isEnd l -> (cs, Comment)
| isStart l -> (cs + 1, Comment)
| isEnd l -> (cs - 1, tpe cs)
| cs > 0 -> (cs, Comment)
| otherwise -> (0, Code)
put ns
pure res
| null | https://raw.githubusercontent.com/vaclavsvejcar/headroom/3b20a89568248259d59f83f274f60f6e13d16f93/src/Headroom/FileSupport.hs | haskell | # LANGUAGE MultiWayIf #
|
Description : Support for handling various source code file types
License : BSD-3-Clause
Maintainer :
Stability : experimental
Portability : POSIX
/Headroom/ currently supports working with file types defined in 'FileType'
type, and because every type of source code file requires different handling of
some aspects, this file type specific support is implemented for every supported
---------------------------- PUBLIC FUNCTIONS ------------------------------
^ raw source code to analyze
^ analyzed source code | # LANGUAGE RecordWildCards #
# LANGUAGE ViewPatterns #
# LANGUAGE NoImplicitPrelude #
Module : Headroom . FileSupport
Copyright : ( c ) 2019 - 2022
file type and exposed as instance of ' FileSupport ' data type .
module Headroom.FileSupport
( fileSupport
, analyzeSourceCode
)
where
import Control.Monad.State
( get
, put
)
import qualified Headroom.FileSupport.C as C
import qualified Headroom.FileSupport.CPP as CPP
import qualified Headroom.FileSupport.CSS as CSS
import qualified Headroom.FileSupport.Dart as Dart
import qualified Headroom.FileSupport.Go as Go
import qualified Headroom.FileSupport.HTML as HTML
import qualified Headroom.FileSupport.Haskell as Haskell
import qualified Headroom.FileSupport.JS as JS
import qualified Headroom.FileSupport.Java as Java
import qualified Headroom.FileSupport.Kotlin as Kotlin
import qualified Headroom.FileSupport.PHP as PHP
import qualified Headroom.FileSupport.PureScript as PureScript
import qualified Headroom.FileSupport.Python as Python
import qualified Headroom.FileSupport.Rust as Rust
import qualified Headroom.FileSupport.Scala as Scala
import qualified Headroom.FileSupport.Shell as Shell
import Headroom.FileSupport.Types
( FileSupport (..)
, SyntaxAnalysis (..)
)
import qualified Headroom.FileSupport.XML as XML
import Headroom.FileType.Types (FileType (..))
import Headroom.SourceCode
( LineType (..)
, SourceCode
, fromText
)
import RIO
import qualified RIO.Text as T
| Returns ' FileSupport ' for corresponding ' FileType ' .
fileSupport :: FileType -> FileSupport
fileSupport C = C.fileSupport
fileSupport CPP = CPP.fileSupport
fileSupport CSS = CSS.fileSupport
fileSupport Dart = Dart.fileSupport
fileSupport Go = Go.fileSupport
fileSupport Haskell = Haskell.fileSupport
fileSupport HTML = HTML.fileSupport
fileSupport Java = Java.fileSupport
fileSupport JS = JS.fileSupport
fileSupport Kotlin = Kotlin.fileSupport
fileSupport PHP = PHP.fileSupport
fileSupport PureScript = PureScript.fileSupport
fileSupport Python = Python.fileSupport
fileSupport Rust = Rust.fileSupport
fileSupport Scala = Scala.fileSupport
fileSupport Shell = Shell.fileSupport
fileSupport XML = XML.fileSupport
| Analyzes the raw source code of given type using provided ' FileSupport ' .
analyzeSourceCode
:: FileSupport
^ ' FileSupport ' implementation used for analysis
-> Text
-> SourceCode
analyzeSourceCode fs = fromText state0 process
where
SyntaxAnalysis{..} = fsSyntaxAnalysis fs
state0 = 0 :: Int
process (T.strip -> l) = do
cs <- get
let isStart = saIsCommentStart
isEnd = saIsCommentEnd
tpe = \c -> if c > 0 then Comment else Code
(ns, res) =
if
| isStart l && isEnd l -> (cs, Comment)
| isStart l -> (cs + 1, Comment)
| isEnd l -> (cs - 1, tpe cs)
| cs > 0 -> (cs, Comment)
| otherwise -> (0, Code)
put ns
pure res
|
cd554c3ee6b769d1909eadc80f70c05af772c21b333035bb5b9c9a8a87b898c0 | janestreet/krb | tgt0.ml | open Core
open Async
open Import
module Cache_type = Internal.Cache_type
module Credentials = Internal.Credentials
module Cross_realm = struct
empirically it seems tgts must be valid for more than 122 seconds .
let check_expiration ?(valid_for_at_least = Time.Span.of_min 10.) tgt =
let tgt_expiration = Credentials.endtime tgt in
let time_now = Time.now () in
if Time.(add time_now valid_for_at_least >= tgt_expiration)
then
Or_error.error_s
[%message
"The cred cache's tgt expires too soon"
~should_be_valid_for_at_least:(valid_for_at_least : Time.Span.t)
(tgt_expiration : Time.t)
(time_now : Time.t)]
else Ok ()
;;
let get_cached_tgt ?valid_for_at_least ~cred_cache principal_name =
Cred_cache0.Cross_realm.principal cred_cache
>>=? fun cred_cache_principal_name ->
if not
([%compare.equal: Cross_realm_principal_name.t]
principal_name
cred_cache_principal_name)
then
Deferred.Or_error.error_s
[%message
"The cred cache's principal does not match the supplied principal"
(principal_name : Cross_realm_principal_name.t)
(cred_cache_principal_name : Cross_realm_principal_name.t)]
else
Internal.Cred_cache.get_cached_tgt
?ensure_valid_for_at_least:valid_for_at_least
cred_cache
;;
let check_valid ?valid_for_at_least ~cred_cache principal_name =
get_cached_tgt ?valid_for_at_least ~cred_cache principal_name
>>|? fun (_ : Internal.Credentials.t) -> ()
;;
let get_from_keytab ~keytab principal =
Keytab.load keytab
>>=? fun keytab ->
Principal.Cross_realm.create principal
>>=? fun principal ->
Keytab.validate keytab principal >>=? fun () -> Credentials.of_keytab principal keytab
;;
let get_from_default_cred_cache ?valid_for_at_least principal =
Cred_cache0.default ()
>>=? fun default_cred_cache ->
get_cached_tgt ?valid_for_at_least ~cred_cache:default_cred_cache principal
;;
let get_from_renewal ?valid_for_at_least ~cred_cache principal =
(* Intentionally don't pass along [valid_for_at_least] to [get_cached_tgt] - we don't
care how long it is valid for because we're going to immediately renew it. Instead,
we check the time of the credentials after renewal. *)
get_cached_tgt ~valid_for_at_least:Time.Span.zero ~cred_cache principal
>>=? fun tgt ->
Internal.Cred_cache.renew cred_cache tgt
>>=? fun tgt' ->
return (check_expiration ?valid_for_at_least tgt') >>|? fun () -> tgt'
;;
let get_tgt ?valid_for_at_least ?keytab ~cred_cache principal =
let sources =
[ Some ("default cred cache", get_from_default_cred_cache ?valid_for_at_least)
; Option.map keytab ~f:(fun keytab -> "keytab", get_from_keytab ~keytab)
; Some ("renewal", get_from_renewal ?valid_for_at_least ~cred_cache)
]
|> List.filter_opt
in
let%map result =
Deferred.Or_error.find_map_ok sources ~f:(fun (source, get) ->
get principal >>| Or_error.tag ~tag:(sprintf "while getting TGT from %s" source))
in
match result with
| Error _ when not Config.verbose_errors ->
Or_error.errorf
"Unable to acquire new TGT from any of %s. You can enable more verbose error \
messages with OCAML_KRB_CONFIG."
(List.map sources ~f:fst |> String.concat ~sep:", ")
| _ -> result
;;
let initialize_with_tgt ?valid_for_at_least ?keytab ~cred_cache principal =
get_tgt ?valid_for_at_least ?keytab ~cred_cache principal
>>=? fun creds ->
Principal.Cross_realm.create principal
>>=? fun principal -> Cred_cache0.initialize_with_creds cred_cache principal [ creds ]
;;
let ensure_valid ?valid_for_at_least ?keytab ~cred_cache principal =
check_valid ~cred_cache ?valid_for_at_least principal
>>= function
| Ok () -> Deferred.Or_error.ok_unit
| Error e ->
initialize_with_tgt ?valid_for_at_least ?keytab ~cred_cache principal
>>| Result.map_error ~f:(fun e2 -> Error.of_list [ e; e2 ])
;;
let initialize_in_new_cred_cache
?(cache_type = Cache_type.MEMORY)
?keytab
principal_name
=
Principal.Cross_realm.create principal_name
>>=? fun principal ->
Internal.Cred_cache.create cache_type principal
>>=? fun cred_cache ->
ensure_valid ?keytab ~cred_cache principal_name >>|? fun () -> cred_cache
;;
end
open Deferred.Or_error.Let_syntax
let check_valid ?valid_for_at_least ~cred_cache principal_name =
Principal.Name.with_default_realm principal_name
>>= Cross_realm.check_valid ?valid_for_at_least ~cred_cache
;;
let ensure_valid ?valid_for_at_least ?keytab ~cred_cache principal =
Principal.Name.with_default_realm principal
>>= Cross_realm.ensure_valid ?valid_for_at_least ?keytab ~cred_cache
;;
let initialize_in_new_cred_cache ?cache_type ?keytab principal_name =
Principal.Name.with_default_realm principal_name
>>= Cross_realm.initialize_in_new_cred_cache ?cache_type ?keytab
;;
let get_cached_tgt ?valid_for_at_least ~cred_cache principal_name =
Principal.Name.with_default_realm principal_name
>>= Cross_realm.get_cached_tgt ?valid_for_at_least ~cred_cache
;;
| null | https://raw.githubusercontent.com/janestreet/krb/8fdd7ca4f18973555e37237c140a2704b1963415/src/tgt0.ml | ocaml | Intentionally don't pass along [valid_for_at_least] to [get_cached_tgt] - we don't
care how long it is valid for because we're going to immediately renew it. Instead,
we check the time of the credentials after renewal. | open Core
open Async
open Import
module Cache_type = Internal.Cache_type
module Credentials = Internal.Credentials
module Cross_realm = struct
empirically it seems tgts must be valid for more than 122 seconds .
let check_expiration ?(valid_for_at_least = Time.Span.of_min 10.) tgt =
let tgt_expiration = Credentials.endtime tgt in
let time_now = Time.now () in
if Time.(add time_now valid_for_at_least >= tgt_expiration)
then
Or_error.error_s
[%message
"The cred cache's tgt expires too soon"
~should_be_valid_for_at_least:(valid_for_at_least : Time.Span.t)
(tgt_expiration : Time.t)
(time_now : Time.t)]
else Ok ()
;;
let get_cached_tgt ?valid_for_at_least ~cred_cache principal_name =
Cred_cache0.Cross_realm.principal cred_cache
>>=? fun cred_cache_principal_name ->
if not
([%compare.equal: Cross_realm_principal_name.t]
principal_name
cred_cache_principal_name)
then
Deferred.Or_error.error_s
[%message
"The cred cache's principal does not match the supplied principal"
(principal_name : Cross_realm_principal_name.t)
(cred_cache_principal_name : Cross_realm_principal_name.t)]
else
Internal.Cred_cache.get_cached_tgt
?ensure_valid_for_at_least:valid_for_at_least
cred_cache
;;
let check_valid ?valid_for_at_least ~cred_cache principal_name =
get_cached_tgt ?valid_for_at_least ~cred_cache principal_name
>>|? fun (_ : Internal.Credentials.t) -> ()
;;
let get_from_keytab ~keytab principal =
Keytab.load keytab
>>=? fun keytab ->
Principal.Cross_realm.create principal
>>=? fun principal ->
Keytab.validate keytab principal >>=? fun () -> Credentials.of_keytab principal keytab
;;
let get_from_default_cred_cache ?valid_for_at_least principal =
Cred_cache0.default ()
>>=? fun default_cred_cache ->
get_cached_tgt ?valid_for_at_least ~cred_cache:default_cred_cache principal
;;
let get_from_renewal ?valid_for_at_least ~cred_cache principal =
get_cached_tgt ~valid_for_at_least:Time.Span.zero ~cred_cache principal
>>=? fun tgt ->
Internal.Cred_cache.renew cred_cache tgt
>>=? fun tgt' ->
return (check_expiration ?valid_for_at_least tgt') >>|? fun () -> tgt'
;;
let get_tgt ?valid_for_at_least ?keytab ~cred_cache principal =
let sources =
[ Some ("default cred cache", get_from_default_cred_cache ?valid_for_at_least)
; Option.map keytab ~f:(fun keytab -> "keytab", get_from_keytab ~keytab)
; Some ("renewal", get_from_renewal ?valid_for_at_least ~cred_cache)
]
|> List.filter_opt
in
let%map result =
Deferred.Or_error.find_map_ok sources ~f:(fun (source, get) ->
get principal >>| Or_error.tag ~tag:(sprintf "while getting TGT from %s" source))
in
match result with
| Error _ when not Config.verbose_errors ->
Or_error.errorf
"Unable to acquire new TGT from any of %s. You can enable more verbose error \
messages with OCAML_KRB_CONFIG."
(List.map sources ~f:fst |> String.concat ~sep:", ")
| _ -> result
;;
let initialize_with_tgt ?valid_for_at_least ?keytab ~cred_cache principal =
get_tgt ?valid_for_at_least ?keytab ~cred_cache principal
>>=? fun creds ->
Principal.Cross_realm.create principal
>>=? fun principal -> Cred_cache0.initialize_with_creds cred_cache principal [ creds ]
;;
let ensure_valid ?valid_for_at_least ?keytab ~cred_cache principal =
check_valid ~cred_cache ?valid_for_at_least principal
>>= function
| Ok () -> Deferred.Or_error.ok_unit
| Error e ->
initialize_with_tgt ?valid_for_at_least ?keytab ~cred_cache principal
>>| Result.map_error ~f:(fun e2 -> Error.of_list [ e; e2 ])
;;
let initialize_in_new_cred_cache
?(cache_type = Cache_type.MEMORY)
?keytab
principal_name
=
Principal.Cross_realm.create principal_name
>>=? fun principal ->
Internal.Cred_cache.create cache_type principal
>>=? fun cred_cache ->
ensure_valid ?keytab ~cred_cache principal_name >>|? fun () -> cred_cache
;;
end
open Deferred.Or_error.Let_syntax
let check_valid ?valid_for_at_least ~cred_cache principal_name =
Principal.Name.with_default_realm principal_name
>>= Cross_realm.check_valid ?valid_for_at_least ~cred_cache
;;
let ensure_valid ?valid_for_at_least ?keytab ~cred_cache principal =
Principal.Name.with_default_realm principal
>>= Cross_realm.ensure_valid ?valid_for_at_least ?keytab ~cred_cache
;;
let initialize_in_new_cred_cache ?cache_type ?keytab principal_name =
Principal.Name.with_default_realm principal_name
>>= Cross_realm.initialize_in_new_cred_cache ?cache_type ?keytab
;;
let get_cached_tgt ?valid_for_at_least ~cred_cache principal_name =
Principal.Name.with_default_realm principal_name
>>= Cross_realm.get_cached_tgt ?valid_for_at_least ~cred_cache
;;
|
cd562c21acc45266712379cd9dc953bf347fe5017a3498cd125fa97e9bfa8889 | nikita-volkov/rebase | Arr.hs | module Rebase.GHC.Arr
(
module GHC.Arr
)
where
import GHC.Arr
| null | https://raw.githubusercontent.com/nikita-volkov/rebase/7c77a0443e80bdffd4488a4239628177cac0761b/library/Rebase/GHC/Arr.hs | haskell | module Rebase.GHC.Arr
(
module GHC.Arr
)
where
import GHC.Arr
|
|
81e667a3f22e67942a490c7a1151ab2522442e398a135cda2ddf7d5fe2395d31 | ocheron/cryptostore | Instances.hs | # OPTIONS_GHC -fno - warn - orphans #
-- | Orphan instances.
module PKCS12.Instances
( arbitraryPassword
, arbitraryAlias
, arbitraryIntegrityParams
, arbitraryPKCS12
) where
import qualified Data.ByteArray as B
import Data.ByteString (ByteString)
import Data.Semigroup
import Test.Tasty.QuickCheck
import Crypto.Store.PKCS12
import Crypto.Store.PKCS5
import CMS.Instances
import PKCS8.Instances ()
arbitrarySmall :: Gen ByteString
arbitrarySmall = resize 10 (B.pack <$> arbitrary)
arbitraryAlias :: Gen String
arbitraryAlias = resize 16 asciiChar
where asciiChar = listOf $ choose ('\x20','\x7f')
arbitraryIntegrityParams :: Gen IntegrityParams
arbitraryIntegrityParams = (,) <$> arbitraryIntegrityDigest <*> arbitrary
arbitraryPKCS12 :: ProtectionPassword -> Gen PKCS12
arbitraryPKCS12 pwd = do
p <- one
ps <- listOf one
return (foldr (<>) p ps)
where
one = oneof [ unencrypted <$> arbitrary
, arbitrary >>= arbitraryEncrypted
]
arbitraryEncrypted sc = do
alg <- arbitrary
case encrypted alg pwd sc of
Left e -> error ("failed generating PKCS12: " ++ show e)
Right aSafe -> return aSafe
instance Arbitrary SafeContents where
arbitrary = SafeContents <$> arbitrary
instance Arbitrary info => Arbitrary (Bag info) where
arbitrary = do
info <- arbitrary
attrs <- arbitraryAttributes
return Bag { bagInfo = info, bagAttributes = attrs }
instance Arbitrary CertInfo where
arbitrary = CertX509 <$> arbitrary
instance Arbitrary CRLInfo where
arbitrary = CRLX509 <$> arbitrary
instance Arbitrary SafeInfo where
arbitrary = oneof [ KeyBag <$> arbitrary
, PKCS8ShroudedKeyBag <$> arbitraryShrouded
, CertBag <$> arbitrary
, CRLBag <$> arbitrary
, SecretBag < $ > arbitrary
, SafeContentsBag <$> arbitrary
]
arbitraryShrouded :: Gen PKCS5
arbitraryShrouded = do
alg <- arbitrary
bs <- arbitrarySmall -- fake content, tested with PKCS8
return PKCS5 { encryptionAlgorithm = alg, encryptedData = bs }
| null | https://raw.githubusercontent.com/ocheron/cryptostore/5ed61ad9566f4a7ce3ab8d8d58eecd77b158e32b/tests/PKCS12/Instances.hs | haskell | | Orphan instances.
fake content, tested with PKCS8 | # OPTIONS_GHC -fno - warn - orphans #
module PKCS12.Instances
( arbitraryPassword
, arbitraryAlias
, arbitraryIntegrityParams
, arbitraryPKCS12
) where
import qualified Data.ByteArray as B
import Data.ByteString (ByteString)
import Data.Semigroup
import Test.Tasty.QuickCheck
import Crypto.Store.PKCS12
import Crypto.Store.PKCS5
import CMS.Instances
import PKCS8.Instances ()
arbitrarySmall :: Gen ByteString
arbitrarySmall = resize 10 (B.pack <$> arbitrary)
arbitraryAlias :: Gen String
arbitraryAlias = resize 16 asciiChar
where asciiChar = listOf $ choose ('\x20','\x7f')
arbitraryIntegrityParams :: Gen IntegrityParams
arbitraryIntegrityParams = (,) <$> arbitraryIntegrityDigest <*> arbitrary
arbitraryPKCS12 :: ProtectionPassword -> Gen PKCS12
arbitraryPKCS12 pwd = do
p <- one
ps <- listOf one
return (foldr (<>) p ps)
where
one = oneof [ unencrypted <$> arbitrary
, arbitrary >>= arbitraryEncrypted
]
arbitraryEncrypted sc = do
alg <- arbitrary
case encrypted alg pwd sc of
Left e -> error ("failed generating PKCS12: " ++ show e)
Right aSafe -> return aSafe
instance Arbitrary SafeContents where
arbitrary = SafeContents <$> arbitrary
instance Arbitrary info => Arbitrary (Bag info) where
arbitrary = do
info <- arbitrary
attrs <- arbitraryAttributes
return Bag { bagInfo = info, bagAttributes = attrs }
instance Arbitrary CertInfo where
arbitrary = CertX509 <$> arbitrary
instance Arbitrary CRLInfo where
arbitrary = CRLX509 <$> arbitrary
instance Arbitrary SafeInfo where
arbitrary = oneof [ KeyBag <$> arbitrary
, PKCS8ShroudedKeyBag <$> arbitraryShrouded
, CertBag <$> arbitrary
, CRLBag <$> arbitrary
, SecretBag < $ > arbitrary
, SafeContentsBag <$> arbitrary
]
arbitraryShrouded :: Gen PKCS5
arbitraryShrouded = do
alg <- arbitrary
return PKCS5 { encryptionAlgorithm = alg, encryptedData = bs }
|
eb89e85d7730c01f908a73903cdacc28ba608d1f837b2857de7f95003b35ab72 | ijvcms/chuanqi_dev | loop_notice_config.erl | %%%-------------------------------------------------------------------
@author zhengsiying
%%% @doc
%%% 自动生成文件,不要手动修改
%%% @end
Created : 2016/10/12
%%%-------------------------------------------------------------------
-module(loop_notice_config).
-include("common.hrl").
-include("config.hrl").
-compile([export_all]).
get_list_conf() ->
[ loop_notice_config:get(X) || X <- get_list() ].
get_list() ->
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18].
get(1) ->
#loop_notice_conf{
key = 1,
notice_id = 5,
time_rule = {3, 6, {12,0}}
};
get(2) ->
#loop_notice_conf{
key = 2,
notice_id = 5,
time_rule = {3, 6, {16,0}}
};
get(3) ->
#loop_notice_conf{
key = 3,
notice_id = 6,
time_rule = {3, 6, {20,30}}
};
get(4) ->
#loop_notice_conf{
key = 4,
notice_id = 7,
time_rule = {3, 6, {21,0}}
};
get(5) ->
#loop_notice_conf{
key = 5,
notice_id = 21,
time_rule = {0, 0, {18,00}}
};
get(6) ->
#loop_notice_conf{
key = 6,
notice_id = 22,
time_rule = {0, 0, {18,30}}
};
get(7) ->
#loop_notice_conf{
key = 7,
notice_id = 24,
time_rule = {0, 0, {15,0}}
};
get(8) ->
#loop_notice_conf{
key = 8,
notice_id = 26,
time_rule = {0, 0, {15,30}}
};
get(9) ->
#loop_notice_conf{
key = 9,
notice_id = 35,
time_rule = {0, 0, {19,00}}
};
get(10) ->
#loop_notice_conf{
key = 10,
notice_id = 35,
time_rule = {9999, 0, {19,00}}
};
get(11) ->
#loop_notice_conf{
key = 11,
notice_id = 63,
time_rule = {0, 7, {17,00}}
};
get(12) ->
#loop_notice_conf{
key = 12,
notice_id = 64,
time_rule = {0, 7, {18,00}}
};
get(13) ->
#loop_notice_conf{
key = 13,
notice_id = 68,
time_rule = {0, 0, {22,00}}
};
get(14) ->
#loop_notice_conf{
key = 14,
notice_id = 69,
time_rule = {0, 0, {23,59}}
};
get(15) ->
#loop_notice_conf{
key = 15,
notice_id = 68,
time_rule = {0, 0, {12,00}}
};
get(16) ->
#loop_notice_conf{
key = 16,
notice_id = 69,
time_rule = {0, 0, {12,59}}
};
get(17) ->
#loop_notice_conf{
key = 17,
notice_id = 74,
time_rule = {0, 0, {21,00}}
};
get(18) ->
#loop_notice_conf{
key = 18,
notice_id = 75,
time_rule = {0, 0, {21,45}}
};
get(_Key) ->
?ERR("undefined key from loop_notice_config ~p", [_Key]). | null | https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/config/loop_notice_config.erl | erlang | -------------------------------------------------------------------
@doc
自动生成文件,不要手动修改
@end
------------------------------------------------------------------- | @author zhengsiying
Created : 2016/10/12
-module(loop_notice_config).
-include("common.hrl").
-include("config.hrl").
-compile([export_all]).
get_list_conf() ->
[ loop_notice_config:get(X) || X <- get_list() ].
get_list() ->
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18].
get(1) ->
#loop_notice_conf{
key = 1,
notice_id = 5,
time_rule = {3, 6, {12,0}}
};
get(2) ->
#loop_notice_conf{
key = 2,
notice_id = 5,
time_rule = {3, 6, {16,0}}
};
get(3) ->
#loop_notice_conf{
key = 3,
notice_id = 6,
time_rule = {3, 6, {20,30}}
};
get(4) ->
#loop_notice_conf{
key = 4,
notice_id = 7,
time_rule = {3, 6, {21,0}}
};
get(5) ->
#loop_notice_conf{
key = 5,
notice_id = 21,
time_rule = {0, 0, {18,00}}
};
get(6) ->
#loop_notice_conf{
key = 6,
notice_id = 22,
time_rule = {0, 0, {18,30}}
};
get(7) ->
#loop_notice_conf{
key = 7,
notice_id = 24,
time_rule = {0, 0, {15,0}}
};
get(8) ->
#loop_notice_conf{
key = 8,
notice_id = 26,
time_rule = {0, 0, {15,30}}
};
get(9) ->
#loop_notice_conf{
key = 9,
notice_id = 35,
time_rule = {0, 0, {19,00}}
};
get(10) ->
#loop_notice_conf{
key = 10,
notice_id = 35,
time_rule = {9999, 0, {19,00}}
};
get(11) ->
#loop_notice_conf{
key = 11,
notice_id = 63,
time_rule = {0, 7, {17,00}}
};
get(12) ->
#loop_notice_conf{
key = 12,
notice_id = 64,
time_rule = {0, 7, {18,00}}
};
get(13) ->
#loop_notice_conf{
key = 13,
notice_id = 68,
time_rule = {0, 0, {22,00}}
};
get(14) ->
#loop_notice_conf{
key = 14,
notice_id = 69,
time_rule = {0, 0, {23,59}}
};
get(15) ->
#loop_notice_conf{
key = 15,
notice_id = 68,
time_rule = {0, 0, {12,00}}
};
get(16) ->
#loop_notice_conf{
key = 16,
notice_id = 69,
time_rule = {0, 0, {12,59}}
};
get(17) ->
#loop_notice_conf{
key = 17,
notice_id = 74,
time_rule = {0, 0, {21,00}}
};
get(18) ->
#loop_notice_conf{
key = 18,
notice_id = 75,
time_rule = {0, 0, {21,45}}
};
get(_Key) ->
?ERR("undefined key from loop_notice_config ~p", [_Key]). |
1b9dd9074660e6aac1d271662e4a49fdc8b56760a7dcec9b961854e6324fd845 | paf31/typescript-docs | Comments.hs | -----------------------------------------------------------------------------
--
-- Module : Language.TypeScript.Docs.Comments
Copyright : ( c ) DICOM Grid Inc. 2013
License : MIT
--
Maintainer : < >
-- Stability : experimental
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module Language.TypeScript.Docs.Comments (
appendComments
) where
import Data.Data
import Data.Generics
import Text.Parsec
import Text.Parsec.Pos
import qualified Data.Map as M
import Control.Applicative (Applicative(..), (<$>), (<*>))
import Control.Monad (when, (>=>))
import Language.TypeScript
import Data.List (intercalate, break)
import Data.Maybe (mapMaybe, fromMaybe)
import Data.Char (isSpace)
import System.IO.Unsafe (unsafePerformIO)
findComments :: String -> (Int, Int) -> CommentPlaceholder
findComments s pos@(line, col) =
let
before = unlines $ toString (line - 1) col $ lines s
in
maybe (Left pos) (Right . parseComment . getContent) (findCommentBlock before)
where
findCommentBlock s = do
let reversed = reverse s
s1 <- findEndOfComment reversed
findStartOfComment [] s1
findEndOfComment (c:s) | isSpace c = findEndOfComment s
findEndOfComment ('/':'*':s) = Just s
findEndOfComment _ = Nothing
findStartOfComment s (c:'*':'*':'/':_) | isSpace c = Just s
findStartOfComment s (c:'*':'/':_) = Nothing
findStartOfComment s (c:s1) = findStartOfComment (c:s) s1
findStartOfComment s [] = Nothing
toString line col (s:_) | line <= 0 = [take (col - 1) s]
toString line _ [] | line <= 0 = []
toString line col (s:ss) = s:toString (line - 1) col ss
getContent :: String -> [String]
getContent = map dropStar . lines
where
dropStar :: String -> String
dropStar ('*':c:s) | isSpace c = s
dropStar ('*':s) = s
dropStar (c:s) | isSpace c = dropStar s
dropStar s = s
parseComment :: [String] -> Comment
parseComment = fst . foldr go (Comment [] [], True)
where
go ('@':rest) (comment, _) =
let
(key, value) = break (== ' ') rest
in
(comment { commentOther = (key, dropWhile isSpace value):commentOther comment}, True)
go line (comment, _) | all isSpace line = (comment, True)
go line (comment, True) =
(comment { commentText = line:commentText comment }, False)
go line (comment@Comment{ commentText = init:tail }, False) =
(comment { commentText = (line ++ " " ++ init):tail }, False)
appendComments :: String -> [DeclarationElement] -> [DeclarationElement]
appendComments source = everywhere (mkT appendComments')
where
appendComments' (Left pos) = findComments source pos
appendComments' r = r
| null | https://raw.githubusercontent.com/paf31/typescript-docs/d7fb77e3ffa7eb61a58835377b63aa6cc83d450d/src/Language/TypeScript/Docs/Comments.hs | haskell | ---------------------------------------------------------------------------
Module : Language.TypeScript.Docs.Comments
Stability : experimental
Portability :
|
--------------------------------------------------------------------------- | Copyright : ( c ) DICOM Grid Inc. 2013
License : MIT
Maintainer : < >
module Language.TypeScript.Docs.Comments (
appendComments
) where
import Data.Data
import Data.Generics
import Text.Parsec
import Text.Parsec.Pos
import qualified Data.Map as M
import Control.Applicative (Applicative(..), (<$>), (<*>))
import Control.Monad (when, (>=>))
import Language.TypeScript
import Data.List (intercalate, break)
import Data.Maybe (mapMaybe, fromMaybe)
import Data.Char (isSpace)
import System.IO.Unsafe (unsafePerformIO)
findComments :: String -> (Int, Int) -> CommentPlaceholder
findComments s pos@(line, col) =
let
before = unlines $ toString (line - 1) col $ lines s
in
maybe (Left pos) (Right . parseComment . getContent) (findCommentBlock before)
where
findCommentBlock s = do
let reversed = reverse s
s1 <- findEndOfComment reversed
findStartOfComment [] s1
findEndOfComment (c:s) | isSpace c = findEndOfComment s
findEndOfComment ('/':'*':s) = Just s
findEndOfComment _ = Nothing
findStartOfComment s (c:'*':'*':'/':_) | isSpace c = Just s
findStartOfComment s (c:'*':'/':_) = Nothing
findStartOfComment s (c:s1) = findStartOfComment (c:s) s1
findStartOfComment s [] = Nothing
toString line col (s:_) | line <= 0 = [take (col - 1) s]
toString line _ [] | line <= 0 = []
toString line col (s:ss) = s:toString (line - 1) col ss
getContent :: String -> [String]
getContent = map dropStar . lines
where
dropStar :: String -> String
dropStar ('*':c:s) | isSpace c = s
dropStar ('*':s) = s
dropStar (c:s) | isSpace c = dropStar s
dropStar s = s
parseComment :: [String] -> Comment
parseComment = fst . foldr go (Comment [] [], True)
where
go ('@':rest) (comment, _) =
let
(key, value) = break (== ' ') rest
in
(comment { commentOther = (key, dropWhile isSpace value):commentOther comment}, True)
go line (comment, _) | all isSpace line = (comment, True)
go line (comment, True) =
(comment { commentText = line:commentText comment }, False)
go line (comment@Comment{ commentText = init:tail }, False) =
(comment { commentText = (line ++ " " ++ init):tail }, False)
appendComments :: String -> [DeclarationElement] -> [DeclarationElement]
appendComments source = everywhere (mkT appendComments')
where
appendComments' (Left pos) = findComments source pos
appendComments' r = r
|
78aeefc7d539e0468c8a9a39c76443f746a8b81ca1623b076699b665f8bb4168 | Tyruiop/syncretism | project.clj | (defproject datops-backend "0.1.0-SNAPSHOT"
:description "Minimal backend to serve live option data"
:license {:name "GNU AGPL-V3 or later"
:url "-3.0.html"}
:url ""
:min-lein-version "2.0.0"
:dependencies [[org.clojure/clojure "1.10.0"]
[org.clojure/data.json "1.0.0"]
[org.clojure/java.jdbc "0.7.12"]
[seancorfield/next.jdbc "1.1.613"]
[com.taoensso/timbre "5.1.2"]
[mysql/mysql-connector-java "8.0.23"]
[compojure "1.6.1"]
[ring/ring-defaults "0.3.2"]
[ring-cors "0.1.13"]
[org.clojars.tyruiop/syncretism "0.1.0"]]
:plugins [[lein-ring "0.12.5"]]
:ring {:handler datops-backend.handler/app}
:profiles
{:dev {:dependencies [[javax.servlet/servlet-api "2.5"]
[ring/ring-mock "0.3.2"]]}})
| null | https://raw.githubusercontent.com/Tyruiop/syncretism/ef15736f246e9c2bd4b76328cc63345987efc93a/datops-backend/project.clj | clojure | (defproject datops-backend "0.1.0-SNAPSHOT"
:description "Minimal backend to serve live option data"
:license {:name "GNU AGPL-V3 or later"
:url "-3.0.html"}
:url ""
:min-lein-version "2.0.0"
:dependencies [[org.clojure/clojure "1.10.0"]
[org.clojure/data.json "1.0.0"]
[org.clojure/java.jdbc "0.7.12"]
[seancorfield/next.jdbc "1.1.613"]
[com.taoensso/timbre "5.1.2"]
[mysql/mysql-connector-java "8.0.23"]
[compojure "1.6.1"]
[ring/ring-defaults "0.3.2"]
[ring-cors "0.1.13"]
[org.clojars.tyruiop/syncretism "0.1.0"]]
:plugins [[lein-ring "0.12.5"]]
:ring {:handler datops-backend.handler/app}
:profiles
{:dev {:dependencies [[javax.servlet/servlet-api "2.5"]
[ring/ring-mock "0.3.2"]]}})
|
|
9e895778e314886390ce2678326a91189b714b8072a22c989cf5e908d3ef7255 | chrisdone/sandbox | finite-list.hs | # LANGUAGE ViewPatterns #
# LANGUAGE NamedFieldPuns #
# LANGUAGE PatternSynonyms #
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
-- | Lists that are of finite length.
module Data.List.Finite
( FiniteList(Empty, (:%))
, maxed
, cons
, empty
) where
-- | A list of finite length.
data FiniteList a =
FiniteList
{ finiteListMaxLength :: !Int
, finiteList :: ![a]
}
deriving (Functor, Foldable, Traversable)
-- | Make a finite list.
empty :: Int -> FiniteList a
empty size =
FiniteList {finiteListMaxLength = size, finiteListLength = 0, finiteList = []}
-- | Is the list maxed out?
maxed :: FiniteList a -> Bool
maxed (FiniteList {finiteListMaxLength, finiteListLength}) =
finiteListLength == finiteListMaxLength
| Cons onto the list . Ignores if we reached the already .
cons :: a -> FiniteList a -> FiniteList a
cons a list =
if maxed list
then list
else list
{ finiteListLength = finiteListLength list + 1
, finiteList = a : finiteList list
}
| Uncons from the list .
uncons :: FiniteList a -> Maybe (a, FiniteList a)
uncons list =
case finiteList list of
(x:xs) ->
let !len = finiteListLength list - 1
in Just (x, list {finiteList = xs, finiteListLength = len})
_ -> Nothing
-- | A bidirectional pattern synonym matching an empty sequence.
pattern Empty :: Int -> FiniteList a
pattern Empty a =
FiniteList {finiteListMaxLength = a, finiteListLength = 0, finiteList = []}
-- | A bidirectional pattern synonym viewing the front of a finite list.
pattern (:%) :: a -> FiniteList a -> FiniteList a
pattern x :% xs <- (uncons -> Just (x, xs))
| null | https://raw.githubusercontent.com/chrisdone/sandbox/c43975a01119a7c70ffe83c49a629c45f7f2543a/finite-list.hs | haskell | # LANGUAGE DeriveTraversable #
| Lists that are of finite length.
| A list of finite length.
| Make a finite list.
| Is the list maxed out?
| A bidirectional pattern synonym matching an empty sequence.
| A bidirectional pattern synonym viewing the front of a finite list. | # LANGUAGE ViewPatterns #
# LANGUAGE NamedFieldPuns #
# LANGUAGE PatternSynonyms #
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
module Data.List.Finite
( FiniteList(Empty, (:%))
, maxed
, cons
, empty
) where
data FiniteList a =
FiniteList
{ finiteListMaxLength :: !Int
, finiteList :: ![a]
}
deriving (Functor, Foldable, Traversable)
empty :: Int -> FiniteList a
empty size =
FiniteList {finiteListMaxLength = size, finiteListLength = 0, finiteList = []}
maxed :: FiniteList a -> Bool
maxed (FiniteList {finiteListMaxLength, finiteListLength}) =
finiteListLength == finiteListMaxLength
| Cons onto the list . Ignores if we reached the already .
cons :: a -> FiniteList a -> FiniteList a
cons a list =
if maxed list
then list
else list
{ finiteListLength = finiteListLength list + 1
, finiteList = a : finiteList list
}
| Uncons from the list .
uncons :: FiniteList a -> Maybe (a, FiniteList a)
uncons list =
case finiteList list of
(x:xs) ->
let !len = finiteListLength list - 1
in Just (x, list {finiteList = xs, finiteListLength = len})
_ -> Nothing
pattern Empty :: Int -> FiniteList a
pattern Empty a =
FiniteList {finiteListMaxLength = a, finiteListLength = 0, finiteList = []}
pattern (:%) :: a -> FiniteList a -> FiniteList a
pattern x :% xs <- (uncons -> Just (x, xs))
|
1f4b6366558e22fb6ae7d5b8b983b30a9ca7cf9b17f701f8a47e8f8caf281b66 | sansarip/owlbear | rules.cljs | (ns owlbear.parse.rules
"General utility tooling around any Tree-sitter tree")
(defn range-in-node?
"Given a node, a start offset, and a stop offset,
returns true if the range is within the given node (inclusive)"
([^js node start]
(range-in-node? node start start))
([^js node start stop]
{:pre [(<= start stop)]}
(if node
(<= (.-startIndex node)
start
stop
(dec (.-endIndex node)))
false)))
(defn node->descendants
"Given a node,
returns a flattened, depth-first traversed, lazy sequence
of all of the node's descendants"
[^js node]
(tree-seq #(.-children %) #(.-children %) node))
(defn node->ancestors
"Given a node,
returns a list of the node's ancestors
i.e. parents and parents of parents etc."
[^js node]
(when node
(some->> (.-parent node) ; Start at parent
(iterate #(.-parent (or % #js {})))
(take-while some?))))
(defn nodes->current-nodes
"Given a list of nodes and a character offset,
returns a lazy sequence of only the nodes containing the given offset"
[offset nodes]
{:pre [(<= 0 offset)]}
(filter #(range-in-node? % offset) nodes))
(defn filter-current-nodes
"Given a sequence of nodes and a character offset,
returns the lazy sequence of nodes that contain the given offset"
[nodes offset]
{:pre [(<= 0 offset)]}
(filter #(range-in-node? % offset) nodes))
(defn node->current-nodes
"Given a node and a character offset,
return a lazy sequence of the child nodes containing the given offset"
[node offset]
{:pre [(<= 0 offset)]}
(filter-current-nodes (node->descendants node) offset))
(defn node->backward-sibling-nodes
"Given a node,
returns a lazy sequence of the node's backward sibling nodes"
[^js node]
(when node
(some->> (.-previousSibling node) ; Start at previous sibling
(iterate #(.-previousSibling (or % #js {})))
(take-while some?))))
(defn node->forward-sibling-nodes
"Given a node,
returns a lazy sequence of the node's forward sibling nodes"
[^js node]
(when node
(some->> (.-nextSibling node) ; Start at next sibling
(iterate #(.-nextSibling (or % #js {})))
(take-while some?))))
(defn some-forward-sibling-node
"Given a predicate function, `pred`, and a `node`,
returns the first forward sibling node that fulfills the predicate function"
[pred node]
{:pre [(fn? pred)]}
(some pred (node->forward-sibling-nodes node)))
(defn some-backward-sibling-node
"Given a predicate function, `pred`, and a `node`,
returns the first backward sibling node that fulfills the predicate function"
[pred node]
{:pre [(fn? pred)]}
(some pred (node->backward-sibling-nodes node)))
(defn some-child-node
"Given a predicate function, `pred`, and a `node`,
returns the first child node that fulfills the predicate function"
[pred ^js node]
{:pre [(fn? pred)]}
(when node
(some pred (.-children node))))
(defn some-descendant-node
"Given a predicate function, `pred`, and a `node`,
returns the first truthy value of the predicate function
applied to the node's descendants"
[pred node]
{:pre [(fn? pred)]}
(some pred (rest (node->descendants node))))
(defn filter-children
"Given a predicate function, `pred`, and a `node`,
returns a lazy seq of all the child nodes
that fulfill the predicate function"
[pred ^js node]
{:pre [(fn? pred)]}
(when node
(filter pred (.-children node))))
(defn filter-descendants
"Given a predicate function, `pred`, and a `node`,
returns a lazy seq of all the descendant nodes
that fulfill the predicate function"
[pred node]
{:pre [(fn? pred)]}
(filter pred (rest (node->descendants node))))
(defn every-descendant?
"Given a predicate function, `pred`, and a `node`,
returns true if every descendant node fulfills the predicate function"
[pred node]
{:pre [(fn? pred)]}
(every? pred (rest (node->descendants node))))
(defn some-ancestor-node
"Given a predicate function, `pred`, and a `node`,
returns the first truthy value of the predicate
function applied to the node's descendants"
[pred node]
{:pre [(fn? pred)]}
(some pred (node->ancestors node)))
(defn all-white-space-chars
"Given a `node`,
returns the `node` if the node contains only whitespace chars"
[^js node]
(when (some-> node
.-text
(->> (re-matches #"\s+")))
node))
(defn distinct-by-start-index
"Given a sequence of nodes,
returns a sequence of the nodes
deduped by their start indices"
[nodes]
(vals
(reduce
(fn [coll ^js node]
(if node
(assoc coll (.-startIndex node) node)
node))
{}
nodes)))
(defn node->same-start-ancestors
"Given a `node`,
returns a lazy sequence of the `node`'s ancestors
that have the same start index"
[^js node]
(let [start-index (.-startIndex node)]
(->> node
(iterate #(.-parent (or % #js {})))
(take-while
#(= (.-startIndex ^js %) start-index))
rest)))
(defn node->boundary-offsets
"Given a `node`,
return a vector of the node's start and end offsets"
[^js node]
(when node
[(.-startIndex node) (.-endIndex node)]))
(defn in-nodes?
"Given a `node` and a sequence of `nodes`,
returns true if the `node` is in the `nodes`"
[^js node nodes]
(boolean (some #(.equals node %) nodes))) | null | https://raw.githubusercontent.com/sansarip/owlbear/55cea7550a564ce8bf90db10e07ddd47d7f293e9/src/cljs/owlbear/parse/rules.cljs | clojure | Start at parent
Start at previous sibling
Start at next sibling | (ns owlbear.parse.rules
"General utility tooling around any Tree-sitter tree")
(defn range-in-node?
"Given a node, a start offset, and a stop offset,
returns true if the range is within the given node (inclusive)"
([^js node start]
(range-in-node? node start start))
([^js node start stop]
{:pre [(<= start stop)]}
(if node
(<= (.-startIndex node)
start
stop
(dec (.-endIndex node)))
false)))
(defn node->descendants
"Given a node,
returns a flattened, depth-first traversed, lazy sequence
of all of the node's descendants"
[^js node]
(tree-seq #(.-children %) #(.-children %) node))
(defn node->ancestors
"Given a node,
returns a list of the node's ancestors
i.e. parents and parents of parents etc."
[^js node]
(when node
(iterate #(.-parent (or % #js {})))
(take-while some?))))
(defn nodes->current-nodes
"Given a list of nodes and a character offset,
returns a lazy sequence of only the nodes containing the given offset"
[offset nodes]
{:pre [(<= 0 offset)]}
(filter #(range-in-node? % offset) nodes))
(defn filter-current-nodes
"Given a sequence of nodes and a character offset,
returns the lazy sequence of nodes that contain the given offset"
[nodes offset]
{:pre [(<= 0 offset)]}
(filter #(range-in-node? % offset) nodes))
(defn node->current-nodes
"Given a node and a character offset,
return a lazy sequence of the child nodes containing the given offset"
[node offset]
{:pre [(<= 0 offset)]}
(filter-current-nodes (node->descendants node) offset))
(defn node->backward-sibling-nodes
"Given a node,
returns a lazy sequence of the node's backward sibling nodes"
[^js node]
(when node
(iterate #(.-previousSibling (or % #js {})))
(take-while some?))))
(defn node->forward-sibling-nodes
"Given a node,
returns a lazy sequence of the node's forward sibling nodes"
[^js node]
(when node
(iterate #(.-nextSibling (or % #js {})))
(take-while some?))))
(defn some-forward-sibling-node
"Given a predicate function, `pred`, and a `node`,
returns the first forward sibling node that fulfills the predicate function"
[pred node]
{:pre [(fn? pred)]}
(some pred (node->forward-sibling-nodes node)))
(defn some-backward-sibling-node
"Given a predicate function, `pred`, and a `node`,
returns the first backward sibling node that fulfills the predicate function"
[pred node]
{:pre [(fn? pred)]}
(some pred (node->backward-sibling-nodes node)))
(defn some-child-node
"Given a predicate function, `pred`, and a `node`,
returns the first child node that fulfills the predicate function"
[pred ^js node]
{:pre [(fn? pred)]}
(when node
(some pred (.-children node))))
(defn some-descendant-node
"Given a predicate function, `pred`, and a `node`,
returns the first truthy value of the predicate function
applied to the node's descendants"
[pred node]
{:pre [(fn? pred)]}
(some pred (rest (node->descendants node))))
(defn filter-children
"Given a predicate function, `pred`, and a `node`,
returns a lazy seq of all the child nodes
that fulfill the predicate function"
[pred ^js node]
{:pre [(fn? pred)]}
(when node
(filter pred (.-children node))))
(defn filter-descendants
"Given a predicate function, `pred`, and a `node`,
returns a lazy seq of all the descendant nodes
that fulfill the predicate function"
[pred node]
{:pre [(fn? pred)]}
(filter pred (rest (node->descendants node))))
(defn every-descendant?
"Given a predicate function, `pred`, and a `node`,
returns true if every descendant node fulfills the predicate function"
[pred node]
{:pre [(fn? pred)]}
(every? pred (rest (node->descendants node))))
(defn some-ancestor-node
"Given a predicate function, `pred`, and a `node`,
returns the first truthy value of the predicate
function applied to the node's descendants"
[pred node]
{:pre [(fn? pred)]}
(some pred (node->ancestors node)))
(defn all-white-space-chars
"Given a `node`,
returns the `node` if the node contains only whitespace chars"
[^js node]
(when (some-> node
.-text
(->> (re-matches #"\s+")))
node))
(defn distinct-by-start-index
"Given a sequence of nodes,
returns a sequence of the nodes
deduped by their start indices"
[nodes]
(vals
(reduce
(fn [coll ^js node]
(if node
(assoc coll (.-startIndex node) node)
node))
{}
nodes)))
(defn node->same-start-ancestors
"Given a `node`,
returns a lazy sequence of the `node`'s ancestors
that have the same start index"
[^js node]
(let [start-index (.-startIndex node)]
(->> node
(iterate #(.-parent (or % #js {})))
(take-while
#(= (.-startIndex ^js %) start-index))
rest)))
(defn node->boundary-offsets
"Given a `node`,
return a vector of the node's start and end offsets"
[^js node]
(when node
[(.-startIndex node) (.-endIndex node)]))
(defn in-nodes?
"Given a `node` and a sequence of `nodes`,
returns true if the `node` is in the `nodes`"
[^js node nodes]
(boolean (some #(.equals node %) nodes))) |
bc0d081f0cc16fe59fb08f8ccae21b6f7c91f9465b8ff6878cf1ee58ea23236c | royneary/mod_push | mod_push_SUITE.erl | %%==============================================================================
Copyright 2010 Erlang Solutions Ltd.
%%
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.
%%==============================================================================
-module(mod_push_SUITE).
-compile(export_all).
-include_lib("escalus/include/escalus.hrl").
-include_lib("common_test/include/ct.hrl").
-include_lib("exml/include/exml_stream.hrl").
%%--------------------------------------------------------------------
%% Suite configuration
%%--------------------------------------------------------------------
all() ->
[{group, tests}].
groups() ->
[{tests, [sequence], [register_story,
disco_stream_story,
disco_appserver_story,
disco_pubsub_story,
enable_story,
disable_story,
unregister_story
]}].
suite() ->
escalus:suite().
%%--------------------------------------------------------------------
Init & teardown
%%--------------------------------------------------------------------
ets_owner() ->
receive
stop -> exit(normal);
_ -> ets_owner()
end.
init_per_suite(Config) ->
Pid = spawn(fun ets_owner/0),
TabId =
ets:new(mod_push_registrations, [bag, public, {heir, Pid, []}]),
escalus:init_per_suite(Config),
[{table, TabId}, {table_owner, Pid} | Config].
end_per_suite(Config) ->
?config(table_owner, Config) ! stop,
escalus:end_per_suite(Config).
init_per_group(_GroupName, Config) ->
escalus:create_users(Config).
end_per_group(_GroupName, Config) ->
escalus:delete_users(Config).
init_per_testcase(CaseName, Config) ->
escalus:init_per_testcase(CaseName, Config).
end_per_testcase(CaseName, Config) ->
escalus:end_per_testcase(CaseName, Config).
%%--------------------------------------------------------------------
%% stories
%%--------------------------------------------------------------------
register_story(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
AppServer = get_option(escalus_server, Config),
DeviceName = get_option(device_name, Config, alice),
%% list registrations before registering
ListRegistrationsRequest =
adhoc_request(<<"list-push-registrations">>, AppServer, []),
escalus:send(Alice, ListRegistrationsRequest),
ListReply1 = escalus:wait_for_stanza(Alice),
escalus:assert(is_adhoc_response,
[<<"list-push-registrations">>, <<"completed">>],
ListReply1),
escalus:assert(fun adhoc_without_form/1, ListReply1),
%% register with valid payload
ApnsPayloadOk =
[{<<"token">>, get_option(apns_token, Config, alice)},
{<<"device-name">>, get_option(device_name, Config, alice)}],
UbuntuPayloadOk =
[{<<"token">>, get_option(ubuntu_token, Config, alice)},
{<<"application-id">>, get_option(application_id, Config, alice)},
{<<"device-name">>, get_option(device_name, Config, alice)}],
TestPayloadOk =
fun({Node, Payload}) ->
Request = adhoc_request(Node, AppServer, Payload),
escalus:send(Alice, Request),
Reply = escalus:wait_for_stanza(Alice),
escalus:assert(is_adhoc_response, [Node, <<"completed">>],
Reply),
XData = get_adhoc_payload(Reply),
escalus:assert(fun valid_response_form/1, XData),
XDataValueOk = fun(Key, XDataForm) ->
is_valid_xdata_value(get_xdata_value(Key, XDataForm))
end,
escalus:assert(XDataValueOk, [<<"jid">>], XData),
escalus:assert(XDataValueOk, [<<"node">>], XData),
escalus:assert(XDataValueOk, [<<"secret">>], XData),
ets:insert(?config(table, Config),
{alice,
get_xdata_value(<<"jid">>, XData),
get_xdata_value(<<"node">>, XData),
get_xdata_value(<<"secret">>, XData),
DeviceName})
end,
lists:foreach(
TestPayloadOk,
filtermap_by_backend(
[{apns, {<<"register-push-apns">>, ApnsPayloadOk}},
{ubuntu, {<<"register-push-ubuntu">>, UbuntuPayloadOk}}],
Config
)
),
%% list registrations after registering
escalus:send(Alice, ListRegistrationsRequest),
ListReply2 = escalus:wait_for_stanza(Alice),
escalus:assert(is_adhoc_response,
[<<"list-push-registrations">>, <<"completed">>],
ListReply2),
Regs = ets:select(?config(table, Config),
[{{alice, '$1', '$2', '$3', '$4'}, [], [{{'$2', '$4'}}]}]),
XData = get_adhoc_payload(ListReply2),
escalus:assert(fun valid_response_form/1, XData),
escalus:assert(fun has_registrations/2, [Regs], XData)
end).
disco_stream_story(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
Request = escalus_stanza:disco_info(escalus_utils:get_short_jid(Alice)),
escalus:send(Alice, Request),
escalus:assert(has_feature, [<<"urn:xmpp:push:0">>],
escalus:wait_for_stanza(Alice))
end).
disco_appserver_story(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
AppServer = get_option(escalus_server, Config),
AppName = get_option(app_name, Config, alice),
Request = escalus_stanza:disco_info(AppServer),
escalus:send(Alice, Request),
Reply = escalus:wait_for_stanza(Alice),
escalus:assert(has_identity, [<<"app-server">>, AppName], Reply)
end).
disco_pubsub_story(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
{alice, PubsubServer, _, _, _} = hd(ets:lookup(?config(table, Config), alice)),
Request = escalus_stanza:disco_info(PubsubServer),
escalus:send(Alice, Request),
Reply = escalus:wait_for_stanza(Alice),
escalus:assert(has_feature, [<<"urn:xmpp:push:0">>], Reply),
escalus:assert(has_identity, [<<"pubsub">>, <<"push">>], Reply)
end).
enable_story(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
ok
end).
disable_story(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
ok
end).
unregister_story(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
AppServer = get_option(escalus_server, Config),
UnregRequestOk =
adhoc_request(<<"unregister-push">>, AppServer, []),
escalus:send(Alice, UnregRequestOk),
Reply = escalus:wait_for_stanza(Alice),
escalus:assert(is_adhoc_response, [<<"unregister-push">>, <<"completed">>],
Reply),
escalus:assert(fun adhoc_without_form/1, Reply),
ets:delete(?config(table, Config), alice)
end).
%%--------------------------------------------------------------------
%% helpers
%%--------------------------------------------------------------------
get_option(Key, Config) ->
escalus_config:get_config(Key, Config).
get_option(Key, Config, User) ->
GenericOption = list_to_atom("escalus_" ++ atom_to_list(Key)),
UserSpec = escalus_users:get_userspec(Config, User),
escalus_config:get_config(Key, UserSpec, GenericOption, Config, undefined).
adhoc_request(Node, Host, Payload) ->
Form = case Payload of
[] -> [];
_ ->
escalus_stanza:x_data_form(<<"submit">>,
escalus_stanza:search_fields(Payload))
end,
Request = escalus_stanza:adhoc_request(Node, Form),
escalus_stanza:to(Request, Host).
filtermap_by_backend(List, Config) ->
filtermap_by_backend(List, Config, []).
filtermap_by_backend([], _, Acc) -> Acc;
filtermap_by_backend([{Backend, Entry}|T], Config, Acc) ->
case lists:member(Backend, get_option(push_backends, Config)) of
true -> filtermap_by_backend(T, Config, [Entry|Acc]);
false -> filtermap_by_backend(T, Config, Acc)
end.
get_adhoc_payload(Stanza) ->
exml_query:path(Stanza, [{element, <<"command">>}, {element, <<"x">>}]).
valid_response_form(#xmlel{name = <<"x">>} = Element) ->
Ns = exml_query:attr(Element, <<"xmlns">>),
Type = exml_query:attr(Element, <<"type">>),
(Ns =:= <<"jabber:x:data">>) and (Type =:= <<"result">>).
has_registrations(Regs, Element) ->
Items =
exml_query:paths(Element, [{element, <<"item">>}]),
ItemFields =
lists:map(
fun(Item) -> [exml_query:paths(Item, [{element, <<"field">>}])] end, Items),
GetValues =
fun
F([El|T], {NodeAcc, DeviceNameAcc}) ->
case exml_query:attr(El, <<"var">>) of
<<"node">> ->
Node = exml_query:path(El, [{element, <<"value">>}, cdata]),
F(T, {Node, DeviceNameAcc});
<<"device-name">> ->
DeviceName = exml_query:path(El, [{element, <<"value">>}, cdata]),
F(T, {NodeAcc, DeviceName});
_ -> F(T, {NodeAcc, DeviceNameAcc})
end;
F([], Result) -> Result
end,
Values =
lists:foldl(
fun(Fs, Acc) ->
[lists:foldl(GetValues, {undefined, undefined}, Fs) | Acc]
end,
[],
ItemFields),
io:format("Regs = ~p, Values = ~p", [Regs, Values]),
(length(Regs) =:= length(Values)) and (Regs -- Values =:= []).
adhoc_without_form(Stanza) ->
get_adhoc_payload(Stanza) =:= undefined.
is_valid_xdata_value(Value) ->
is_binary(Value) and (Value =/= <<"">>).
get_xdata_value(Key, XData) ->
Fields = exml_query:paths(XData, [{element, <<"field">>}]),
FindValue =
fun
F([Field|T]) ->
case exml_query:attr(Field, <<"var">>) of
Key -> exml_query:path(Field, [{element, <<"value">>}, cdata]);
_ -> F(T)
end;
F([]) -> undefined
end,
FindValue(Fields).
| null | https://raw.githubusercontent.com/royneary/mod_push/d43e9c6efd6a9f5eda691ca4aac0577eeb6413e3/test/mod_push_SUITE.erl | erlang | ==============================================================================
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.
==============================================================================
--------------------------------------------------------------------
Suite configuration
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
stories
--------------------------------------------------------------------
list registrations before registering
register with valid payload
list registrations after registering
--------------------------------------------------------------------
helpers
-------------------------------------------------------------------- | Copyright 2010 Erlang Solutions Ltd.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(mod_push_SUITE).
-compile(export_all).
-include_lib("escalus/include/escalus.hrl").
-include_lib("common_test/include/ct.hrl").
-include_lib("exml/include/exml_stream.hrl").
all() ->
[{group, tests}].
groups() ->
[{tests, [sequence], [register_story,
disco_stream_story,
disco_appserver_story,
disco_pubsub_story,
enable_story,
disable_story,
unregister_story
]}].
suite() ->
escalus:suite().
Init & teardown
ets_owner() ->
receive
stop -> exit(normal);
_ -> ets_owner()
end.
init_per_suite(Config) ->
Pid = spawn(fun ets_owner/0),
TabId =
ets:new(mod_push_registrations, [bag, public, {heir, Pid, []}]),
escalus:init_per_suite(Config),
[{table, TabId}, {table_owner, Pid} | Config].
end_per_suite(Config) ->
?config(table_owner, Config) ! stop,
escalus:end_per_suite(Config).
init_per_group(_GroupName, Config) ->
escalus:create_users(Config).
end_per_group(_GroupName, Config) ->
escalus:delete_users(Config).
init_per_testcase(CaseName, Config) ->
escalus:init_per_testcase(CaseName, Config).
end_per_testcase(CaseName, Config) ->
escalus:end_per_testcase(CaseName, Config).
register_story(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
AppServer = get_option(escalus_server, Config),
DeviceName = get_option(device_name, Config, alice),
ListRegistrationsRequest =
adhoc_request(<<"list-push-registrations">>, AppServer, []),
escalus:send(Alice, ListRegistrationsRequest),
ListReply1 = escalus:wait_for_stanza(Alice),
escalus:assert(is_adhoc_response,
[<<"list-push-registrations">>, <<"completed">>],
ListReply1),
escalus:assert(fun adhoc_without_form/1, ListReply1),
ApnsPayloadOk =
[{<<"token">>, get_option(apns_token, Config, alice)},
{<<"device-name">>, get_option(device_name, Config, alice)}],
UbuntuPayloadOk =
[{<<"token">>, get_option(ubuntu_token, Config, alice)},
{<<"application-id">>, get_option(application_id, Config, alice)},
{<<"device-name">>, get_option(device_name, Config, alice)}],
TestPayloadOk =
fun({Node, Payload}) ->
Request = adhoc_request(Node, AppServer, Payload),
escalus:send(Alice, Request),
Reply = escalus:wait_for_stanza(Alice),
escalus:assert(is_adhoc_response, [Node, <<"completed">>],
Reply),
XData = get_adhoc_payload(Reply),
escalus:assert(fun valid_response_form/1, XData),
XDataValueOk = fun(Key, XDataForm) ->
is_valid_xdata_value(get_xdata_value(Key, XDataForm))
end,
escalus:assert(XDataValueOk, [<<"jid">>], XData),
escalus:assert(XDataValueOk, [<<"node">>], XData),
escalus:assert(XDataValueOk, [<<"secret">>], XData),
ets:insert(?config(table, Config),
{alice,
get_xdata_value(<<"jid">>, XData),
get_xdata_value(<<"node">>, XData),
get_xdata_value(<<"secret">>, XData),
DeviceName})
end,
lists:foreach(
TestPayloadOk,
filtermap_by_backend(
[{apns, {<<"register-push-apns">>, ApnsPayloadOk}},
{ubuntu, {<<"register-push-ubuntu">>, UbuntuPayloadOk}}],
Config
)
),
escalus:send(Alice, ListRegistrationsRequest),
ListReply2 = escalus:wait_for_stanza(Alice),
escalus:assert(is_adhoc_response,
[<<"list-push-registrations">>, <<"completed">>],
ListReply2),
Regs = ets:select(?config(table, Config),
[{{alice, '$1', '$2', '$3', '$4'}, [], [{{'$2', '$4'}}]}]),
XData = get_adhoc_payload(ListReply2),
escalus:assert(fun valid_response_form/1, XData),
escalus:assert(fun has_registrations/2, [Regs], XData)
end).
disco_stream_story(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
Request = escalus_stanza:disco_info(escalus_utils:get_short_jid(Alice)),
escalus:send(Alice, Request),
escalus:assert(has_feature, [<<"urn:xmpp:push:0">>],
escalus:wait_for_stanza(Alice))
end).
disco_appserver_story(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
AppServer = get_option(escalus_server, Config),
AppName = get_option(app_name, Config, alice),
Request = escalus_stanza:disco_info(AppServer),
escalus:send(Alice, Request),
Reply = escalus:wait_for_stanza(Alice),
escalus:assert(has_identity, [<<"app-server">>, AppName], Reply)
end).
disco_pubsub_story(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
{alice, PubsubServer, _, _, _} = hd(ets:lookup(?config(table, Config), alice)),
Request = escalus_stanza:disco_info(PubsubServer),
escalus:send(Alice, Request),
Reply = escalus:wait_for_stanza(Alice),
escalus:assert(has_feature, [<<"urn:xmpp:push:0">>], Reply),
escalus:assert(has_identity, [<<"pubsub">>, <<"push">>], Reply)
end).
enable_story(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
ok
end).
disable_story(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
ok
end).
unregister_story(Config) ->
escalus:story(Config, [{alice, 1}], fun(Alice) ->
AppServer = get_option(escalus_server, Config),
UnregRequestOk =
adhoc_request(<<"unregister-push">>, AppServer, []),
escalus:send(Alice, UnregRequestOk),
Reply = escalus:wait_for_stanza(Alice),
escalus:assert(is_adhoc_response, [<<"unregister-push">>, <<"completed">>],
Reply),
escalus:assert(fun adhoc_without_form/1, Reply),
ets:delete(?config(table, Config), alice)
end).
get_option(Key, Config) ->
escalus_config:get_config(Key, Config).
get_option(Key, Config, User) ->
GenericOption = list_to_atom("escalus_" ++ atom_to_list(Key)),
UserSpec = escalus_users:get_userspec(Config, User),
escalus_config:get_config(Key, UserSpec, GenericOption, Config, undefined).
adhoc_request(Node, Host, Payload) ->
Form = case Payload of
[] -> [];
_ ->
escalus_stanza:x_data_form(<<"submit">>,
escalus_stanza:search_fields(Payload))
end,
Request = escalus_stanza:adhoc_request(Node, Form),
escalus_stanza:to(Request, Host).
filtermap_by_backend(List, Config) ->
filtermap_by_backend(List, Config, []).
filtermap_by_backend([], _, Acc) -> Acc;
filtermap_by_backend([{Backend, Entry}|T], Config, Acc) ->
case lists:member(Backend, get_option(push_backends, Config)) of
true -> filtermap_by_backend(T, Config, [Entry|Acc]);
false -> filtermap_by_backend(T, Config, Acc)
end.
get_adhoc_payload(Stanza) ->
exml_query:path(Stanza, [{element, <<"command">>}, {element, <<"x">>}]).
valid_response_form(#xmlel{name = <<"x">>} = Element) ->
Ns = exml_query:attr(Element, <<"xmlns">>),
Type = exml_query:attr(Element, <<"type">>),
(Ns =:= <<"jabber:x:data">>) and (Type =:= <<"result">>).
has_registrations(Regs, Element) ->
Items =
exml_query:paths(Element, [{element, <<"item">>}]),
ItemFields =
lists:map(
fun(Item) -> [exml_query:paths(Item, [{element, <<"field">>}])] end, Items),
GetValues =
fun
F([El|T], {NodeAcc, DeviceNameAcc}) ->
case exml_query:attr(El, <<"var">>) of
<<"node">> ->
Node = exml_query:path(El, [{element, <<"value">>}, cdata]),
F(T, {Node, DeviceNameAcc});
<<"device-name">> ->
DeviceName = exml_query:path(El, [{element, <<"value">>}, cdata]),
F(T, {NodeAcc, DeviceName});
_ -> F(T, {NodeAcc, DeviceNameAcc})
end;
F([], Result) -> Result
end,
Values =
lists:foldl(
fun(Fs, Acc) ->
[lists:foldl(GetValues, {undefined, undefined}, Fs) | Acc]
end,
[],
ItemFields),
io:format("Regs = ~p, Values = ~p", [Regs, Values]),
(length(Regs) =:= length(Values)) and (Regs -- Values =:= []).
adhoc_without_form(Stanza) ->
get_adhoc_payload(Stanza) =:= undefined.
is_valid_xdata_value(Value) ->
is_binary(Value) and (Value =/= <<"">>).
get_xdata_value(Key, XData) ->
Fields = exml_query:paths(XData, [{element, <<"field">>}]),
FindValue =
fun
F([Field|T]) ->
case exml_query:attr(Field, <<"var">>) of
Key -> exml_query:path(Field, [{element, <<"value">>}, cdata]);
_ -> F(T)
end;
F([]) -> undefined
end,
FindValue(Fields).
|
f9867a2ca4fd853570a32f192d02fd7f524f927c1f24852cdb2592d3c91e346c | quark-lang/quark | Quark.hs | module Core.Quark (module Quark) where
import Core.Parser.Parser as Quark
import Core.Macro.Compiler as Quark
import Core.Macro.Initializing as Quark
import Core.Macro.Definition as Quark
import Core.Import.Duplicates as Quark
import Core.Import.Remover as Quark | null | https://raw.githubusercontent.com/quark-lang/quark/e3dc7fff4e4dfba3e5c9ab71f10ede8bc5a30a44/app/Core/Quark.hs | haskell | module Core.Quark (module Quark) where
import Core.Parser.Parser as Quark
import Core.Macro.Compiler as Quark
import Core.Macro.Initializing as Quark
import Core.Macro.Definition as Quark
import Core.Import.Duplicates as Quark
import Core.Import.Remover as Quark |
|
d86ffd8a1644454ce59250fee4c4fd2d4f56d33f10febb9d7790fbaf1a2e5b54 | jrh13/hol-light | forster.ml | (* ======== translation of "The shortest?" from Examples/forster.ml ======== *)
horizon := 0;;
let FORSTER_PUZZLE_1 = thm `;
let f be num->num;
thus (!n. f(n + 1) > f(f(n))) ==> !n. f(n) = n
proof
assume !n. f(n + 1) > f(f(n));
!n. f(f(n)) < f(SUC n) [1] by -,GT,ADD1;
!m n. m <= f(n + m) [2]
proof
!n. 0 <= f(n + 0) [3] by LE_0,ADD_CLAUSES,LE_SUC_LT;
now let m be num;
assume !n. m <= f(n + m);
!n. m < f(SUC (n + m)) by -,1,LET_TRANS,SUB_ADD;
thus !n. SUC m <= f(n + SUC m) by -,LE_0,ADD_CLAUSES,LE_SUC_LT;
end;
qed by INDUCT_TAC,-,3;
!n. f(n) < f(SUC n) [4] by -,1,LET_TRANS,LE_TRANS,ADD_CLAUSES;
!m n. f(m) < f(n) ==> m < n
proof
!n. f(0) < f(n) ==> 0 < n [5] by LT_LE,LE_0,LTE_TRANS,LE_SUC_LT;
now let m be num;
assume !n. f(m) < f(n) ==> m < n;
thus !n. f(SUC m) < f(n) ==> SUC m < n
by -,4,LT_LE,LE_0,LTE_TRANS,LE_SUC_LT;
end;
qed by INDUCT_TAC,-,5;
qed by -,1,2,LE_ANTISYM,ADD_CLAUSES,LT_SUC_LE`;;
(* ======== long-winded informal proof ===================================== *)
Suppose that f(f(n ) ) < f(n + 1 ) for all n. We want to
show that f has to be the identity . We will do this by
successively establishing two properties of f ( both in a
certain sense being " monotonicity of f " ):
n < = f(n )
m < n = = > f(m ) < f(n )
The first is the harder one to prove . The second is easy ,
but the proof uses the first . Once we know the second
property we know so much about f that the result easily
follows .
To prove the first , suppose by contradiction that there is a
counterexample , so there is an n with f " going backwards " ,
i.e. , with f(n ) < n. Take such a counterexample with f(n )
minimal . ( That this minimality is the right one to focus
on is the key to the whole proof for me . Of course one can
present this proof the other way around -- as an induction --
but the intuition of a descending chain of counterexamples
I find much easier to remember . ) Now from the relation
f(f(n - 1 ) ) < f(n )
it seems reasonable to look for an n ' with f going backwards
that has an image less than f(n ) . So look at
n - 1 |- > f(n - 1 ) |- > f(f(n - 1 ) )
and distinguish how f(n - 1 ) compares to f(n ) . If it 's less ,
then the left mapping goes backward to an image < f(n ) .
( To see that it goes backward , use that f(n ) < n , so that
f(n ) < = n - 1 . ) If it 's not less , then the right mapping
goes backward to an image < f(n ) . In both cases we have
a contradiction with the minimality of our choice of n.
The second kind of monoticity now follows using a trivial
transitivity :
f(n ) < = f(f(n ) ) < f(n + 1 )
This shows that f(n ) < f(n + 1 ) for all n , from with the
monotonicity of the whole function directly follows .
Finally to show that f has to be the identity , notice that
a strictly monotonic function always has the property that
n < = f(n )
( Of course we knew this already , but I like to just think
about the strict monotonicity of f at this point . )
However we also can get an upper bound on f(n ) . A strictly
monototic function always has a strictly monotonic inverse ,
and so from the key property
f(f(n ) ) < f(n + 1 )
it follows that
f(n ) < n + 1
Together this means that we have to have that f(n ) = n.
Suppose that f(f(n)) < f(n + 1) for all n. We want to
show that f has to be the identity. We will do this by
successively establishing two properties of f (both in a
certain sense being "monotonicity of f"):
n <= f(n)
m < n ==> f(m) < f(n)
The first is the harder one to prove. The second is easy,
but the proof uses the first. Once we know the second
property we know so much about f that the result easily
follows.
To prove the first, suppose by contradiction that there is a
counterexample, so there is an n with f "going backwards",
i.e., with f(n) < n. Take such a counterexample with f(n)
minimal. (That this minimality is the right one to focus
on is the key to the whole proof for me. Of course one can
present this proof the other way around -- as an induction --
but the intuition of a descending chain of counterexamples
I find much easier to remember.) Now from the relation
f(f(n - 1)) < f(n)
it seems reasonable to look for an n' with f going backwards
that has an image less than f(n). So look at
n - 1 |-> f(n - 1) |-> f(f(n - 1))
and distinguish how f(n - 1) compares to f(n). If it's less,
then the left mapping goes backward to an image < f(n).
(To see that it goes backward, use that f(n) < n, so that
f(n) <= n - 1.) If it's not less, then the right mapping
goes backward to an image < f(n). In both cases we have
a contradiction with the minimality of our choice of n.
The second kind of monoticity now follows using a trivial
transitivity:
f(n) <= f(f(n)) < f(n + 1)
This shows that f(n) < f(n + 1) for all n, from with the
monotonicity of the whole function directly follows.
Finally to show that f has to be the identity, notice that
a strictly monotonic function always has the property that
n <= f(n)
(Of course we knew this already, but I like to just think
about the strict monotonicity of f at this point.)
However we also can get an upper bound on f(n). A strictly
monototic function always has a strictly monotonic inverse,
and so from the key property
f(f(n)) < f(n + 1)
it follows that
f(n) < n + 1
Together this means that we have to have that f(n) = n.
*)
(* ======== formal proof sketch of this proof ============================== *)
horizon := -1;;
sketch_mode := true;;
let FORSTER_PUZZLE_SKETCH = ref None;;
FORSTER_PUZZLE_SKETCH := Some `;
let f be num->num;
assume !n. f(f(n)) < f(n + 1);
thus !n. f(n) = n
proof
!n. n <= f(n)
proof
assume ~thesis;
?n. f(n) < n;
consider n such that f(n) < n /\
!m. f(m) < m ==> f(n) <= f(m);
cases;
suppose f(n - 1) < f(n);
f(n - 1) < n - 1 /\ f(n - 1) < f(n)
proof
f(n) < n;
f(n) <= n - 1;
qed;
thus F;
end;
suppose f(n) <= f(n - 1);
f(f(n - 1)) < f(n - 1) /\ f(f(n - 1)) < f(n);
thus F;
end;
end;
!m n. m < n ==> f(m) < f(n)
proof
now
let n be num;
f(n) <= f(f(n)) /\ f(f(n)) < f(n + 1);
thus f(n) < f(n + 1);
end;
qed;
let n be num;
n <= f(n);
!m n. f(m) < f(n) ==> m < n;
f(f(n)) < f(n + 1);
f(n) < n + 1;
thus f(n) = n;
end`;;
sketch_mode := false;;
(* ======== formalization from this formal proof sketch ==================== *)
horizon := 1;;
let FORSTER_PUZZLE_2 = thm `;
let f be num->num;
assume !n. f(f(n)) < f(n + 1) [1];
thus !n. f(n) = n
proof
!n. n <= f(n) [2]
proof
assume ~thesis;
?n. f(n) < n by NOT_LE;
?fn n. f(n) = fn /\ f(n) < n;
consider fn such that (?n. f(n) = fn /\ f(n) < n) /\
!fm. fm < fn ==> ~(?m. f(m) = fm /\ f(m) < m) [3]
by REWRITE_TAC,GSYM num_WOP;
consider n such that f(n) = fn /\ f(n) < n;
f(n) < n /\ !m. f(m) < m ==> f(n) <= f(m) [4] by 3,NOT_LE;
cases;
suppose f(n - 1) < f(n) [5];
f(n - 1) < n - 1 /\ f(n - 1) < f(n)
proof
f(n) < n by 4;
f(n) <= n - 1 by ARITH_TAC;
qed by 5,LTE_TRANS;
thus F by 4,NOT_LE;
end;
suppose f(n) <= f(n - 1) [6];
0 < n by ARITH_TAC,4;
(n - 1) + 1 = n by ARITH_TAC;
f(f(n - 1)) < f(n) by 1;
f(f(n - 1)) < f(n - 1) /\ f(f(n - 1)) < f(n) by ARITH_TAC,6;
thus F by 4,NOT_LE;
end;
end;
!m n. m < n ==> f(m) < f(n) [7]
proof
now
let n be num;
f(n) <= f(f(n)) /\ f(f(n)) < f(n + 1) by 1,2;
thus f(n) < f(SUC n) by ARITH_TAC; // modified from f(n) < f(n + 1)
end;
qed by LT_TRANS,
SPEC (parse_term "\\m n. (f:num->num)(m) < f(n)") TRANSITIVE_STEPWISE_LT;
let n be num;
n <= f(n) [8] by 2; // really should be an induction proof from 7
!m n. f(m) < f(n) ==> m < n [9] by 7,LE_LT,NOT_LE;
f(f(n)) < f(n + 1) by 1;
f(n) < n + 1 by 9;
thus f(n) = n by ARITH_TAC,8;
end`;;
(* ======== ... and a slightly compressed version ========================== *)
horizon := 1;;
let FORSTER_PUZZLE_3 = thm `;
let f be num->num;
assume !n. f(f(n)) < f(n + 1) [1];
!n. n <= f(n) [2]
proof
assume ~thesis;
?fn n. f(n) = fn /\ f(n) < n by NOT_LE;
consider fn such that (?n. f(n) = fn /\ f(n) < n) /\
!fm. fm < fn ==> ~(?m. f(m) = fm /\ f(m) < m) [3]
by REWRITE_TAC,GSYM num_WOP;
consider n such that f(n) = fn /\ f(n) < n [4];
cases;
suppose f(n - 1) < f(n) [5];
f(n - 1) < n - 1 by ARITH_TAC,4;
thus F by 3,4,5;
end;
suppose f(n) <= f(n - 1) [6];
(n - 1) + 1 = n by ARITH_TAC,4;
thus F by 1,3,4,6,LTE_TRANS;
end;
end;
!n. f(n) < f(SUC n) by 1,2,ADD1,LET_TRANS;
!m n. m < n ==> f(m) < f(n) by LT_TRANS,
SPEC (parse_term "\\m n. (f:num->num)(m) < f(n)") TRANSITIVE_STEPWISE_LT;
!m n. f(m) < f(n) ==> m < n by LE_LT,NOT_LE;
thus !n. f(n) = n by 1,2,ADD1,LE_ANTISYM,LT_SUC_LE`;;
= = = = = = = = formalization from the formal proof sketch = = = = = = = = = = = = = = =
environ
vocabularies , , ARYTM , ARYTM_1 , ;
notations ORDINAL1 , RELSET_1 , FUNCT_2 , NUMBERS , , XXREAL_0 , ,
VALUED_0 ;
constructors XXREAL_0 , INT_1 , PARTFUN1 , VALUED_0 , MEMBERED , RELSET_1 ;
registrations XBOOLE_0 , , FUNCT_1 , ORDINAL1 , XXREAL_0 , XREAL_0 ,
NAT_1 , INT_1 , VALUED_0 , MEMBERED ;
requirements NUMERALS , REAL , SUBSET , ARITHM ;
theorems XXREAL_0 , XREAL_1 , INT_1 , , VALUED_0 , VALUED_1 , FUNCT_2 ,
ORDINAL1 ;
schemes NAT_1 ;
begin
reserve n , m , fn , fm for natural number ;
reserve f for Function of NAT , NAT ;
theorem
( for n holds f.(f.n ) < f.(n + 1 ) ) implies for n holds f.n = n
proof
assume
A1 : for n holds f.(f.n ) < f.(n + 1 ) ;
A2 : for n holds n < = f.n
proof
assume
A3 : not thesis ;
defpred P[Nat ] means ex n st f.n < n & f.n = $ 1 ;
A4 : ex fn st P[fn ] by A3 ;
consider fn being such that
A5 : P[fn ] & for fm being ] holds fn < = fm from : sch 5(A4 ) ;
consider n such that
A6 : f.n < n & f.n = fn by A5 ;
n > = 0 + 1 by A6,NAT_1:13 ;
then n - 1 > = 0 by XREAL_1:21 ;
then n - 1 in NAT by INT_1:16 ;
then reconsider m = n - 1 as natural number ;
per cases ;
suppose
A7 : f.m < f.n ;
f.n < m + 1 by A6 ;
then f.n < = m by NAT_1:13 ;
then f.m < m by A7,XXREAL_0:2 ;
hence contradiction by A5,A6,A7 ;
end ;
suppose
A8 : f.n < = f.m ;
A9 : f.(f.m ) < f.(m + 1 ) by A1 ;
then f.(f.m ) < f.m by A8,XXREAL_0:2 ;
hence contradiction by A5,A6,A9 ;
end ;
end ;
now
let n ;
f.n < = f.(f.n ) & f.(f.n ) < f.(n + 1 ) by A1,A2 ;
hence f.n < f.(n + 1 ) by XXREAL_0:2 ;
end ;
then reconsider f as increasing Function of NAT , NAT by VALUED_1 : def 13 ;
A10 : now
let m , n ;
dom f = NAT & m in NAT & n in NAT by FUNCT_2 : def 1,ORDINAL1 : def 13 ;
hence f.m < f.n implies m < n by VALUED_0 : def 15 ;
end ;
let n ;
f.(f.n ) < f.(n + 1 ) by A1 ;
then f.n < n + 1 by A10 ;
then n < = f.n & f.n < = n by A2,NAT_1:13 ;
hence thesis by XXREAL_0:1 ;
end ;
environ
vocabularies RELAT_1, FUNCT_1, ARYTM, ARYTM_1, ORDINAL2;
notations ORDINAL1, RELSET_1, FUNCT_2, NUMBERS, XCMPLX_0, XXREAL_0, NAT_1,
VALUED_0;
constructors XXREAL_0, INT_1, PARTFUN1, VALUED_0, MEMBERED, RELSET_1;
registrations XBOOLE_0, RELAT_1, FUNCT_1, ORDINAL1, XXREAL_0, XREAL_0,
NAT_1, INT_1, VALUED_0, MEMBERED;
requirements NUMERALS, REAL, SUBSET, ARITHM;
theorems XXREAL_0, XREAL_1, INT_1, NAT_1, VALUED_0, VALUED_1, FUNCT_2,
ORDINAL1;
schemes NAT_1;
begin
reserve n,m,fn,fm for natural number;
reserve f for Function of NAT,NAT;
theorem
(for n holds f.(f.n) < f.(n + 1)) implies for n holds f.n = n
proof
assume
A1: for n holds f.(f.n) < f.(n + 1);
A2: for n holds n <= f.n
proof
assume
A3: not thesis;
defpred P[Nat] means ex n st f.n < n & f.n = $1;
A4: ex fn st P[fn] by A3;
consider fn being Nat such that
A5: P[fn] & for fm being Nat st P[fm] holds fn <= fm from NAT_1:sch 5(A4);
consider n such that
A6: f.n < n & f.n = fn by A5;
n >= 0 + 1 by A6,NAT_1:13;
then n - 1 >= 0 by XREAL_1:21;
then n - 1 in NAT by INT_1:16;
then reconsider m = n - 1 as natural number;
per cases;
suppose
A7: f.m < f.n;
f.n < m + 1 by A6;
then f.n <= m by NAT_1:13;
then f.m < m by A7,XXREAL_0:2;
hence contradiction by A5,A6,A7;
end;
suppose
A8: f.n <= f.m;
A9: f.(f.m) < f.(m + 1) by A1;
then f.(f.m) < f.m by A8,XXREAL_0:2;
hence contradiction by A5,A6,A9;
end;
end;
now
let n;
f.n <= f.(f.n) & f.(f.n) < f.(n + 1) by A1,A2;
hence f.n < f.(n + 1) by XXREAL_0:2;
end;
then reconsider f as increasing Function of NAT,NAT by VALUED_1:def 13;
A10: now
let m,n;
dom f = NAT & m in NAT & n in NAT by FUNCT_2:def 1,ORDINAL1:def 13;
hence f.m < f.n implies m < n by VALUED_0:def 15;
end;
let n;
f.(f.n) < f.(n + 1) by A1;
then f.n < n + 1 by A10;
then n <= f.n & f.n <= n by A2,NAT_1:13;
hence thesis by XXREAL_0:1;
end;
*)
= = = = = = = = miz3 formalization close to the formalization = = = = = = = = = = = =
horizon := 0;;
let FORSTER_PUZZLE_4 = thm `;
!f. (!n. f(f(n)) < f(n + 1)) ==> !n. f(n) = n
proof
let f be num->num;
assume !n. f(f(n)) < f(n + 1) [1];
!n. n <= f(n) [2]
proof
assume ~thesis [3];
set P = \fn. ?n. f(n) < n /\ f(n) = fn [P];
?fn. P(fn) [4] by 3,P,NOT_LE;
consider fn such that P(fn) /\ !fm. P(fm) ==> fn <= fm [5]
by 4,num_WOP,NOT_LE;
consider n such that f(n) < n /\ f(n) = fn [6] by P,5;
set m = n - 1;
n = m + 1 [m] by ARITH_TAC,6; // replaces the reconsider
cases;
suppose f(m) < f(n) [7];
f(n) < m + 1 by ARITH_TAC,6;
f(n) <= m by ARITH_TAC,-;
f(m) < m by ARITH_TAC,-,7;
f(n) <= f(m) by -,P,5,6; // extra step
thus F by ARITH_TAC,-,7;
end;
suppose f(n) <= f(m) [8];
f(f(m)) < f(m + 1) [9] by 1;
f(f(m)) < f(m) by -,m,8,LTE_TRANS;
f(n) <= f(f(m)) by -,P,5,6; // extra step
thus F by -,m,9,NOT_LE;
end;
end;
now
let n be num;
f(n) <= f(f(n)) /\ f(f(n)) < f(n + 1) by 1,2;
thus f(n) < f(n + 1) by ARITH_TAC,-;
end;
!n. f(n) < f(SUC n) by -,ADD1; // extra step
!m n. m < n ==> f(m) < f(n) by -,LT_TRANS,
SPEC (parse_term "\\m n. (f:num->num)(m) < f(n)") TRANSITIVE_STEPWISE_LT;
// replaces the reconsider
now [10]
let m n be num;
thus f(m) < f(n) ==> m < n by -,LE_LT,NOT_LE;
end;
let n be num;
f(f(n)) < f(n + 1) by 1;
f(n) < n + 1 by -,10;
n <= f(n) /\ f(n) <= n by -,2,ADD1,LT_SUC_LE;
thus thesis by ARITH_TAC,-;
end`;;
= = = = = = = = formalization following Tobias & Sean 's version = = = = = = = = = = = = = = = =
horizon := 3;;
let num_MONO_LT_SUC = thm `;
let f be num->num;
assume !n. f(n) < f(SUC n);
!n m. m < n ==> f(m) < f(n) by LT_TRANS,
SPEC (parse_term "\\m n. (f:num->num)(m) < f(n)") TRANSITIVE_STEPWISE_LT;
thus !n m. m < n <=> f(m) < f(n) by LE_LT,NOT_LE`;;
let FORSTER_PUZZLE_5 = thm `;
let f be num->num;
assume !n. f(f(n)) < f(SUC(n));
!n m. n <= m ==> n <= f(m)
proof
now let n be num; assume !m. n <= m ==> n <= f(m);
!m. SUC n <= m ==> ?k. m = SUC k by num_CASES,LT,LE_SUC_LT;
thus !m. SUC n <= m ==> SUC n <= f(m) by LE_SUC,LET_TRANS,LE_SUC_LT;
end;
!m. 0 <= m ==> 0 <= f(m);
qed by INDUCT_TAC;
!n. f(n) < f(SUC n) by LE_REFL,LET_TRANS;
thus !n. f(n) = n by num_MONO_LT_SUC,LT_SUC_LE,LE_ANTISYM`;;
| null | https://raw.githubusercontent.com/jrh13/hol-light/d125b0ae73e546a63ed458a7891f4e14ae0409e2/miz3/Samples/forster.ml | ocaml | ======== translation of "The shortest?" from Examples/forster.ml ========
======== long-winded informal proof =====================================
======== formal proof sketch of this proof ==============================
======== formalization from this formal proof sketch ====================
======== ... and a slightly compressed version ========================== |
horizon := 0;;
let FORSTER_PUZZLE_1 = thm `;
let f be num->num;
thus (!n. f(n + 1) > f(f(n))) ==> !n. f(n) = n
proof
assume !n. f(n + 1) > f(f(n));
!n. f(f(n)) < f(SUC n) [1] by -,GT,ADD1;
!m n. m <= f(n + m) [2]
proof
!n. 0 <= f(n + 0) [3] by LE_0,ADD_CLAUSES,LE_SUC_LT;
now let m be num;
assume !n. m <= f(n + m);
!n. m < f(SUC (n + m)) by -,1,LET_TRANS,SUB_ADD;
thus !n. SUC m <= f(n + SUC m) by -,LE_0,ADD_CLAUSES,LE_SUC_LT;
end;
qed by INDUCT_TAC,-,3;
!n. f(n) < f(SUC n) [4] by -,1,LET_TRANS,LE_TRANS,ADD_CLAUSES;
!m n. f(m) < f(n) ==> m < n
proof
!n. f(0) < f(n) ==> 0 < n [5] by LT_LE,LE_0,LTE_TRANS,LE_SUC_LT;
now let m be num;
assume !n. f(m) < f(n) ==> m < n;
thus !n. f(SUC m) < f(n) ==> SUC m < n
by -,4,LT_LE,LE_0,LTE_TRANS,LE_SUC_LT;
end;
qed by INDUCT_TAC,-,5;
qed by -,1,2,LE_ANTISYM,ADD_CLAUSES,LT_SUC_LE`;;
Suppose that f(f(n ) ) < f(n + 1 ) for all n. We want to
show that f has to be the identity . We will do this by
successively establishing two properties of f ( both in a
certain sense being " monotonicity of f " ):
n < = f(n )
m < n = = > f(m ) < f(n )
The first is the harder one to prove . The second is easy ,
but the proof uses the first . Once we know the second
property we know so much about f that the result easily
follows .
To prove the first , suppose by contradiction that there is a
counterexample , so there is an n with f " going backwards " ,
i.e. , with f(n ) < n. Take such a counterexample with f(n )
minimal . ( That this minimality is the right one to focus
on is the key to the whole proof for me . Of course one can
present this proof the other way around -- as an induction --
but the intuition of a descending chain of counterexamples
I find much easier to remember . ) Now from the relation
f(f(n - 1 ) ) < f(n )
it seems reasonable to look for an n ' with f going backwards
that has an image less than f(n ) . So look at
n - 1 |- > f(n - 1 ) |- > f(f(n - 1 ) )
and distinguish how f(n - 1 ) compares to f(n ) . If it 's less ,
then the left mapping goes backward to an image < f(n ) .
( To see that it goes backward , use that f(n ) < n , so that
f(n ) < = n - 1 . ) If it 's not less , then the right mapping
goes backward to an image < f(n ) . In both cases we have
a contradiction with the minimality of our choice of n.
The second kind of monoticity now follows using a trivial
transitivity :
f(n ) < = f(f(n ) ) < f(n + 1 )
This shows that f(n ) < f(n + 1 ) for all n , from with the
monotonicity of the whole function directly follows .
Finally to show that f has to be the identity , notice that
a strictly monotonic function always has the property that
n < = f(n )
( Of course we knew this already , but I like to just think
about the strict monotonicity of f at this point . )
However we also can get an upper bound on f(n ) . A strictly
monototic function always has a strictly monotonic inverse ,
and so from the key property
f(f(n ) ) < f(n + 1 )
it follows that
f(n ) < n + 1
Together this means that we have to have that f(n ) = n.
Suppose that f(f(n)) < f(n + 1) for all n. We want to
show that f has to be the identity. We will do this by
successively establishing two properties of f (both in a
certain sense being "monotonicity of f"):
n <= f(n)
m < n ==> f(m) < f(n)
The first is the harder one to prove. The second is easy,
but the proof uses the first. Once we know the second
property we know so much about f that the result easily
follows.
To prove the first, suppose by contradiction that there is a
counterexample, so there is an n with f "going backwards",
i.e., with f(n) < n. Take such a counterexample with f(n)
minimal. (That this minimality is the right one to focus
on is the key to the whole proof for me. Of course one can
present this proof the other way around -- as an induction --
but the intuition of a descending chain of counterexamples
I find much easier to remember.) Now from the relation
f(f(n - 1)) < f(n)
it seems reasonable to look for an n' with f going backwards
that has an image less than f(n). So look at
n - 1 |-> f(n - 1) |-> f(f(n - 1))
and distinguish how f(n - 1) compares to f(n). If it's less,
then the left mapping goes backward to an image < f(n).
(To see that it goes backward, use that f(n) < n, so that
f(n) <= n - 1.) If it's not less, then the right mapping
goes backward to an image < f(n). In both cases we have
a contradiction with the minimality of our choice of n.
The second kind of monoticity now follows using a trivial
transitivity:
f(n) <= f(f(n)) < f(n + 1)
This shows that f(n) < f(n + 1) for all n, from with the
monotonicity of the whole function directly follows.
Finally to show that f has to be the identity, notice that
a strictly monotonic function always has the property that
n <= f(n)
(Of course we knew this already, but I like to just think
about the strict monotonicity of f at this point.)
However we also can get an upper bound on f(n). A strictly
monototic function always has a strictly monotonic inverse,
and so from the key property
f(f(n)) < f(n + 1)
it follows that
f(n) < n + 1
Together this means that we have to have that f(n) = n.
*)
horizon := -1;;
sketch_mode := true;;
let FORSTER_PUZZLE_SKETCH = ref None;;
FORSTER_PUZZLE_SKETCH := Some `;
let f be num->num;
assume !n. f(f(n)) < f(n + 1);
thus !n. f(n) = n
proof
!n. n <= f(n)
proof
assume ~thesis;
?n. f(n) < n;
consider n such that f(n) < n /\
!m. f(m) < m ==> f(n) <= f(m);
cases;
suppose f(n - 1) < f(n);
f(n - 1) < n - 1 /\ f(n - 1) < f(n)
proof
f(n) < n;
f(n) <= n - 1;
qed;
thus F;
end;
suppose f(n) <= f(n - 1);
f(f(n - 1)) < f(n - 1) /\ f(f(n - 1)) < f(n);
thus F;
end;
end;
!m n. m < n ==> f(m) < f(n)
proof
now
let n be num;
f(n) <= f(f(n)) /\ f(f(n)) < f(n + 1);
thus f(n) < f(n + 1);
end;
qed;
let n be num;
n <= f(n);
!m n. f(m) < f(n) ==> m < n;
f(f(n)) < f(n + 1);
f(n) < n + 1;
thus f(n) = n;
end`;;
sketch_mode := false;;
horizon := 1;;
let FORSTER_PUZZLE_2 = thm `;
let f be num->num;
assume !n. f(f(n)) < f(n + 1) [1];
thus !n. f(n) = n
proof
!n. n <= f(n) [2]
proof
assume ~thesis;
?n. f(n) < n by NOT_LE;
?fn n. f(n) = fn /\ f(n) < n;
consider fn such that (?n. f(n) = fn /\ f(n) < n) /\
!fm. fm < fn ==> ~(?m. f(m) = fm /\ f(m) < m) [3]
by REWRITE_TAC,GSYM num_WOP;
consider n such that f(n) = fn /\ f(n) < n;
f(n) < n /\ !m. f(m) < m ==> f(n) <= f(m) [4] by 3,NOT_LE;
cases;
suppose f(n - 1) < f(n) [5];
f(n - 1) < n - 1 /\ f(n - 1) < f(n)
proof
f(n) < n by 4;
f(n) <= n - 1 by ARITH_TAC;
qed by 5,LTE_TRANS;
thus F by 4,NOT_LE;
end;
suppose f(n) <= f(n - 1) [6];
0 < n by ARITH_TAC,4;
(n - 1) + 1 = n by ARITH_TAC;
f(f(n - 1)) < f(n) by 1;
f(f(n - 1)) < f(n - 1) /\ f(f(n - 1)) < f(n) by ARITH_TAC,6;
thus F by 4,NOT_LE;
end;
end;
!m n. m < n ==> f(m) < f(n) [7]
proof
now
let n be num;
f(n) <= f(f(n)) /\ f(f(n)) < f(n + 1) by 1,2;
thus f(n) < f(SUC n) by ARITH_TAC; // modified from f(n) < f(n + 1)
end;
qed by LT_TRANS,
SPEC (parse_term "\\m n. (f:num->num)(m) < f(n)") TRANSITIVE_STEPWISE_LT;
let n be num;
n <= f(n) [8] by 2; // really should be an induction proof from 7
!m n. f(m) < f(n) ==> m < n [9] by 7,LE_LT,NOT_LE;
f(f(n)) < f(n + 1) by 1;
f(n) < n + 1 by 9;
thus f(n) = n by ARITH_TAC,8;
end`;;
horizon := 1;;
let FORSTER_PUZZLE_3 = thm `;
let f be num->num;
assume !n. f(f(n)) < f(n + 1) [1];
!n. n <= f(n) [2]
proof
assume ~thesis;
?fn n. f(n) = fn /\ f(n) < n by NOT_LE;
consider fn such that (?n. f(n) = fn /\ f(n) < n) /\
!fm. fm < fn ==> ~(?m. f(m) = fm /\ f(m) < m) [3]
by REWRITE_TAC,GSYM num_WOP;
consider n such that f(n) = fn /\ f(n) < n [4];
cases;
suppose f(n - 1) < f(n) [5];
f(n - 1) < n - 1 by ARITH_TAC,4;
thus F by 3,4,5;
end;
suppose f(n) <= f(n - 1) [6];
(n - 1) + 1 = n by ARITH_TAC,4;
thus F by 1,3,4,6,LTE_TRANS;
end;
end;
!n. f(n) < f(SUC n) by 1,2,ADD1,LET_TRANS;
!m n. m < n ==> f(m) < f(n) by LT_TRANS,
SPEC (parse_term "\\m n. (f:num->num)(m) < f(n)") TRANSITIVE_STEPWISE_LT;
!m n. f(m) < f(n) ==> m < n by LE_LT,NOT_LE;
thus !n. f(n) = n by 1,2,ADD1,LE_ANTISYM,LT_SUC_LE`;;
= = = = = = = = formalization from the formal proof sketch = = = = = = = = = = = = = = =
environ
vocabularies , , ARYTM , ARYTM_1 , ;
notations ORDINAL1 , RELSET_1 , FUNCT_2 , NUMBERS , , XXREAL_0 , ,
VALUED_0 ;
constructors XXREAL_0 , INT_1 , PARTFUN1 , VALUED_0 , MEMBERED , RELSET_1 ;
registrations XBOOLE_0 , , FUNCT_1 , ORDINAL1 , XXREAL_0 , XREAL_0 ,
NAT_1 , INT_1 , VALUED_0 , MEMBERED ;
requirements NUMERALS , REAL , SUBSET , ARITHM ;
theorems XXREAL_0 , XREAL_1 , INT_1 , , VALUED_0 , VALUED_1 , FUNCT_2 ,
ORDINAL1 ;
schemes NAT_1 ;
begin
reserve n , m , fn , fm for natural number ;
reserve f for Function of NAT , NAT ;
theorem
( for n holds f.(f.n ) < f.(n + 1 ) ) implies for n holds f.n = n
proof
assume
A1 : for n holds f.(f.n ) < f.(n + 1 ) ;
A2 : for n holds n < = f.n
proof
assume
A3 : not thesis ;
defpred P[Nat ] means ex n st f.n < n & f.n = $ 1 ;
A4 : ex fn st P[fn ] by A3 ;
consider fn being such that
A5 : P[fn ] & for fm being ] holds fn < = fm from : sch 5(A4 ) ;
consider n such that
A6 : f.n < n & f.n = fn by A5 ;
n > = 0 + 1 by A6,NAT_1:13 ;
then n - 1 > = 0 by XREAL_1:21 ;
then n - 1 in NAT by INT_1:16 ;
then reconsider m = n - 1 as natural number ;
per cases ;
suppose
A7 : f.m < f.n ;
f.n < m + 1 by A6 ;
then f.n < = m by NAT_1:13 ;
then f.m < m by A7,XXREAL_0:2 ;
hence contradiction by A5,A6,A7 ;
end ;
suppose
A8 : f.n < = f.m ;
A9 : f.(f.m ) < f.(m + 1 ) by A1 ;
then f.(f.m ) < f.m by A8,XXREAL_0:2 ;
hence contradiction by A5,A6,A9 ;
end ;
end ;
now
let n ;
f.n < = f.(f.n ) & f.(f.n ) < f.(n + 1 ) by A1,A2 ;
hence f.n < f.(n + 1 ) by XXREAL_0:2 ;
end ;
then reconsider f as increasing Function of NAT , NAT by VALUED_1 : def 13 ;
A10 : now
let m , n ;
dom f = NAT & m in NAT & n in NAT by FUNCT_2 : def 1,ORDINAL1 : def 13 ;
hence f.m < f.n implies m < n by VALUED_0 : def 15 ;
end ;
let n ;
f.(f.n ) < f.(n + 1 ) by A1 ;
then f.n < n + 1 by A10 ;
then n < = f.n & f.n < = n by A2,NAT_1:13 ;
hence thesis by XXREAL_0:1 ;
end ;
environ
vocabularies RELAT_1, FUNCT_1, ARYTM, ARYTM_1, ORDINAL2;
notations ORDINAL1, RELSET_1, FUNCT_2, NUMBERS, XCMPLX_0, XXREAL_0, NAT_1,
VALUED_0;
constructors XXREAL_0, INT_1, PARTFUN1, VALUED_0, MEMBERED, RELSET_1;
registrations XBOOLE_0, RELAT_1, FUNCT_1, ORDINAL1, XXREAL_0, XREAL_0,
NAT_1, INT_1, VALUED_0, MEMBERED;
requirements NUMERALS, REAL, SUBSET, ARITHM;
theorems XXREAL_0, XREAL_1, INT_1, NAT_1, VALUED_0, VALUED_1, FUNCT_2,
ORDINAL1;
schemes NAT_1;
begin
reserve n,m,fn,fm for natural number;
reserve f for Function of NAT,NAT;
theorem
(for n holds f.(f.n) < f.(n + 1)) implies for n holds f.n = n
proof
assume
A1: for n holds f.(f.n) < f.(n + 1);
A2: for n holds n <= f.n
proof
assume
A3: not thesis;
defpred P[Nat] means ex n st f.n < n & f.n = $1;
A4: ex fn st P[fn] by A3;
consider fn being Nat such that
A5: P[fn] & for fm being Nat st P[fm] holds fn <= fm from NAT_1:sch 5(A4);
consider n such that
A6: f.n < n & f.n = fn by A5;
n >= 0 + 1 by A6,NAT_1:13;
then n - 1 >= 0 by XREAL_1:21;
then n - 1 in NAT by INT_1:16;
then reconsider m = n - 1 as natural number;
per cases;
suppose
A7: f.m < f.n;
f.n < m + 1 by A6;
then f.n <= m by NAT_1:13;
then f.m < m by A7,XXREAL_0:2;
hence contradiction by A5,A6,A7;
end;
suppose
A8: f.n <= f.m;
A9: f.(f.m) < f.(m + 1) by A1;
then f.(f.m) < f.m by A8,XXREAL_0:2;
hence contradiction by A5,A6,A9;
end;
end;
now
let n;
f.n <= f.(f.n) & f.(f.n) < f.(n + 1) by A1,A2;
hence f.n < f.(n + 1) by XXREAL_0:2;
end;
then reconsider f as increasing Function of NAT,NAT by VALUED_1:def 13;
A10: now
let m,n;
dom f = NAT & m in NAT & n in NAT by FUNCT_2:def 1,ORDINAL1:def 13;
hence f.m < f.n implies m < n by VALUED_0:def 15;
end;
let n;
f.(f.n) < f.(n + 1) by A1;
then f.n < n + 1 by A10;
then n <= f.n & f.n <= n by A2,NAT_1:13;
hence thesis by XXREAL_0:1;
end;
*)
= = = = = = = = miz3 formalization close to the formalization = = = = = = = = = = = =
horizon := 0;;
let FORSTER_PUZZLE_4 = thm `;
!f. (!n. f(f(n)) < f(n + 1)) ==> !n. f(n) = n
proof
let f be num->num;
assume !n. f(f(n)) < f(n + 1) [1];
!n. n <= f(n) [2]
proof
assume ~thesis [3];
set P = \fn. ?n. f(n) < n /\ f(n) = fn [P];
?fn. P(fn) [4] by 3,P,NOT_LE;
consider fn such that P(fn) /\ !fm. P(fm) ==> fn <= fm [5]
by 4,num_WOP,NOT_LE;
consider n such that f(n) < n /\ f(n) = fn [6] by P,5;
set m = n - 1;
n = m + 1 [m] by ARITH_TAC,6; // replaces the reconsider
cases;
suppose f(m) < f(n) [7];
f(n) < m + 1 by ARITH_TAC,6;
f(n) <= m by ARITH_TAC,-;
f(m) < m by ARITH_TAC,-,7;
f(n) <= f(m) by -,P,5,6; // extra step
thus F by ARITH_TAC,-,7;
end;
suppose f(n) <= f(m) [8];
f(f(m)) < f(m + 1) [9] by 1;
f(f(m)) < f(m) by -,m,8,LTE_TRANS;
f(n) <= f(f(m)) by -,P,5,6; // extra step
thus F by -,m,9,NOT_LE;
end;
end;
now
let n be num;
f(n) <= f(f(n)) /\ f(f(n)) < f(n + 1) by 1,2;
thus f(n) < f(n + 1) by ARITH_TAC,-;
end;
!n. f(n) < f(SUC n) by -,ADD1; // extra step
!m n. m < n ==> f(m) < f(n) by -,LT_TRANS,
SPEC (parse_term "\\m n. (f:num->num)(m) < f(n)") TRANSITIVE_STEPWISE_LT;
// replaces the reconsider
now [10]
let m n be num;
thus f(m) < f(n) ==> m < n by -,LE_LT,NOT_LE;
end;
let n be num;
f(f(n)) < f(n + 1) by 1;
f(n) < n + 1 by -,10;
n <= f(n) /\ f(n) <= n by -,2,ADD1,LT_SUC_LE;
thus thesis by ARITH_TAC,-;
end`;;
= = = = = = = = formalization following Tobias & Sean 's version = = = = = = = = = = = = = = = =
horizon := 3;;
let num_MONO_LT_SUC = thm `;
let f be num->num;
assume !n. f(n) < f(SUC n);
!n m. m < n ==> f(m) < f(n) by LT_TRANS,
SPEC (parse_term "\\m n. (f:num->num)(m) < f(n)") TRANSITIVE_STEPWISE_LT;
thus !n m. m < n <=> f(m) < f(n) by LE_LT,NOT_LE`;;
let FORSTER_PUZZLE_5 = thm `;
let f be num->num;
assume !n. f(f(n)) < f(SUC(n));
!n m. n <= m ==> n <= f(m)
proof
now let n be num; assume !m. n <= m ==> n <= f(m);
!m. SUC n <= m ==> ?k. m = SUC k by num_CASES,LT,LE_SUC_LT;
thus !m. SUC n <= m ==> SUC n <= f(m) by LE_SUC,LET_TRANS,LE_SUC_LT;
end;
!m. 0 <= m ==> 0 <= f(m);
qed by INDUCT_TAC;
!n. f(n) < f(SUC n) by LE_REFL,LET_TRANS;
thus !n. f(n) = n by num_MONO_LT_SUC,LT_SUC_LE,LE_ANTISYM`;;
|
bc5bba60abe806ca53f7c107783234a9f890b1baaab8de00f4d207e35c62dd5b | biocaml/phylogenetics | nelder_mead.ml | *
Implements method as described in
some tests from original publication :
A simplex method for function minimization
and
Implements method as described in
some tests from original publication:
A simplex method for function minimization
J. A. Nelder and R. Mead
*)
open Core
let centroid xs =
let n = Array.length xs in
if n = 0 then raise (Invalid_argument "Nelder_mead.centroid: empty array") ;
let d = Array.length xs.(0) in
Array.init d ~f:(fun i ->
Array.fold xs ~init:0. ~f:(fun acc x -> acc +. x.(i))
/. float n
)
let update ~from:c alpha ~towards:x =
let d = Array.length c in
Array.init d ~f:(fun i -> c.(i) +. alpha *. (x.(i) -. c.(i)))
let minimize ?(tol = 1e-8) ?(maxit = 100_000) ?(debug = false) ~f ~sample () =
let alpha = 1. in
let gamma = 2. in
let rho = 0.5 in
let sigma = 0.5 in
let x0 = sample () in
let n = Array.length x0 in
if n = 0 then raise (Invalid_argument "Nelder_mead.minimize: sample returns empty vectors") ;
let sample () =
let y = sample () in
if Array.length y <> n then raise (Invalid_argument "Nelder_mead.minimize: sample returns vectors of varying lengths") ;
y
in
let points = Array.init (n + 1) ~f:(fun _ -> sample ()) in
let obj = Array.map points ~f in
let rec loop i =
let ranks = Utils.array_order ~compare:Float.compare obj in
if debug then (
printf "\n\nIteration %d: %f\n%!" i obj.(ranks.(0)) ;
printf "Delta: %g\n%!" (obj.(ranks.(n)) -. obj.(ranks.(0)))
) ;
let c =
Array.sub ranks ~pos:0 ~len:n
|> Array.map ~f:(Array.get points)
|> centroid
in
let x_r = update ~from:c (-. alpha) ~towards:points.(ranks.(n)) in
let f_r = f x_r in
if debug then (
printf "Candidate: %f\n" f_r ;
) ;
(
match Float.(f_r < obj.(ranks.(0)), f_r < obj.(ranks.(Int.(n - 1)))) with
| false, true ->
if debug then printf "Reflection\n" ;
points.(ranks.(n)) <- x_r ;
obj.(ranks.(n)) <- f_r ;
| true, _ ->
if debug then printf "Expansion\n" ;
let x_e = update ~from:c gamma ~towards:x_r in
let f_e = f x_e in
points.(ranks.(n)) <- if Float.(f_e < f_r) then x_e else x_r ;
obj.(ranks.(n)) <- Float.min f_r f_e ;
| false, false ->
let x_c, f_c, candidate_accepted =
if Float.(f_r < obj.(ranks.(n))) then (* outside contraction *)
let x_c = update ~from:c rho ~towards:x_r in
let f_c = f x_c in
x_c, f_c, Float.(f_c <= f_r)
else (* inside contraction *)
let x_cc = update ~from:c ~towards:points.(ranks.(n)) rho in
let f_cc = f x_cc in
x_cc, f_cc, Float.(f_cc < obj.(ranks.(n)))
in
if candidate_accepted then (
if debug then printf "Contraction, f_c = %f\n" f_c ;
points.(ranks.(n)) <- x_c ;
obj.(ranks.(n)) <- f_c ;
)
else (
if debug then printf "Shrink\n" ;
Array.iteri points ~f:(fun i x_i ->
if i <> ranks.(0) then (
let x_i = update ~from:points.(ranks.(0)) sigma ~towards:x_i in
points.(i) <- x_i ;
obj.(i) <- f x_i
)
)
)
) ;
let sigma = Gsl.Stats.sd obj in
if debug then (
printf "Sigma: %f\n" sigma ;
printf "Values: %s\n" (Utils.show_float_array (Array.init (n + 1) ~f:(fun i -> obj.(ranks.(i)))))
) ;
if Float.(sigma < tol) || i >= maxit
then obj.(ranks.(0)), points.(ranks.(0)), i
else loop (i + 1)
in
loop 0
let%test "Parabola" =
let f x = x.(0) ** 2. in
let sample () = [| Random.float 200. -. 100. |] in
let obj, _, _ = minimize ~f ~tol:1e-3 ~sample () in
Float.(abs obj < 1e-3)
let%test "Rosenbrock" =
let f x = 100. *. (x.(1) -. x.(0) ** 2.) ** 2. +. (1. -. x.(0)) ** 2. in
let rfloat _ = Random.float 200. -. 100. in
let sample () = Array.init 2 ~f:rfloat in
let obj, _, _ = minimize ~f ~sample () in
Float.(abs obj < 1e-3)
let%test "Powell quartic" =
let f x =
let open Float in
(x.(0) + 10. * x.(1)) ** 2. + 5. *. (x.(2) - x.(3)) ** 2.
+ (x.(1) - 2. *. x.(2)) ** 4. + 10. * (x.(0) - x.(3)) ** 4.
in
let rfloat _ = Random.float 200. -. 100. in
let sample () = Array.init 4 ~f:rfloat in
let obj, _, _ = minimize ~f ~sample () in
Float.(abs obj < 1e-3)
| null | https://raw.githubusercontent.com/biocaml/phylogenetics/e225616a700b03c429c16f760dbe8c363fb4c79d/lib/nelder_mead.ml | ocaml | outside contraction
inside contraction | *
Implements method as described in
some tests from original publication :
A simplex method for function minimization
and
Implements method as described in
some tests from original publication:
A simplex method for function minimization
J. A. Nelder and R. Mead
*)
open Core
let centroid xs =
let n = Array.length xs in
if n = 0 then raise (Invalid_argument "Nelder_mead.centroid: empty array") ;
let d = Array.length xs.(0) in
Array.init d ~f:(fun i ->
Array.fold xs ~init:0. ~f:(fun acc x -> acc +. x.(i))
/. float n
)
let update ~from:c alpha ~towards:x =
let d = Array.length c in
Array.init d ~f:(fun i -> c.(i) +. alpha *. (x.(i) -. c.(i)))
let minimize ?(tol = 1e-8) ?(maxit = 100_000) ?(debug = false) ~f ~sample () =
let alpha = 1. in
let gamma = 2. in
let rho = 0.5 in
let sigma = 0.5 in
let x0 = sample () in
let n = Array.length x0 in
if n = 0 then raise (Invalid_argument "Nelder_mead.minimize: sample returns empty vectors") ;
let sample () =
let y = sample () in
if Array.length y <> n then raise (Invalid_argument "Nelder_mead.minimize: sample returns vectors of varying lengths") ;
y
in
let points = Array.init (n + 1) ~f:(fun _ -> sample ()) in
let obj = Array.map points ~f in
let rec loop i =
let ranks = Utils.array_order ~compare:Float.compare obj in
if debug then (
printf "\n\nIteration %d: %f\n%!" i obj.(ranks.(0)) ;
printf "Delta: %g\n%!" (obj.(ranks.(n)) -. obj.(ranks.(0)))
) ;
let c =
Array.sub ranks ~pos:0 ~len:n
|> Array.map ~f:(Array.get points)
|> centroid
in
let x_r = update ~from:c (-. alpha) ~towards:points.(ranks.(n)) in
let f_r = f x_r in
if debug then (
printf "Candidate: %f\n" f_r ;
) ;
(
match Float.(f_r < obj.(ranks.(0)), f_r < obj.(ranks.(Int.(n - 1)))) with
| false, true ->
if debug then printf "Reflection\n" ;
points.(ranks.(n)) <- x_r ;
obj.(ranks.(n)) <- f_r ;
| true, _ ->
if debug then printf "Expansion\n" ;
let x_e = update ~from:c gamma ~towards:x_r in
let f_e = f x_e in
points.(ranks.(n)) <- if Float.(f_e < f_r) then x_e else x_r ;
obj.(ranks.(n)) <- Float.min f_r f_e ;
| false, false ->
let x_c, f_c, candidate_accepted =
let x_c = update ~from:c rho ~towards:x_r in
let f_c = f x_c in
x_c, f_c, Float.(f_c <= f_r)
let x_cc = update ~from:c ~towards:points.(ranks.(n)) rho in
let f_cc = f x_cc in
x_cc, f_cc, Float.(f_cc < obj.(ranks.(n)))
in
if candidate_accepted then (
if debug then printf "Contraction, f_c = %f\n" f_c ;
points.(ranks.(n)) <- x_c ;
obj.(ranks.(n)) <- f_c ;
)
else (
if debug then printf "Shrink\n" ;
Array.iteri points ~f:(fun i x_i ->
if i <> ranks.(0) then (
let x_i = update ~from:points.(ranks.(0)) sigma ~towards:x_i in
points.(i) <- x_i ;
obj.(i) <- f x_i
)
)
)
) ;
let sigma = Gsl.Stats.sd obj in
if debug then (
printf "Sigma: %f\n" sigma ;
printf "Values: %s\n" (Utils.show_float_array (Array.init (n + 1) ~f:(fun i -> obj.(ranks.(i)))))
) ;
if Float.(sigma < tol) || i >= maxit
then obj.(ranks.(0)), points.(ranks.(0)), i
else loop (i + 1)
in
loop 0
let%test "Parabola" =
let f x = x.(0) ** 2. in
let sample () = [| Random.float 200. -. 100. |] in
let obj, _, _ = minimize ~f ~tol:1e-3 ~sample () in
Float.(abs obj < 1e-3)
let%test "Rosenbrock" =
let f x = 100. *. (x.(1) -. x.(0) ** 2.) ** 2. +. (1. -. x.(0)) ** 2. in
let rfloat _ = Random.float 200. -. 100. in
let sample () = Array.init 2 ~f:rfloat in
let obj, _, _ = minimize ~f ~sample () in
Float.(abs obj < 1e-3)
let%test "Powell quartic" =
let f x =
let open Float in
(x.(0) + 10. * x.(1)) ** 2. + 5. *. (x.(2) - x.(3)) ** 2.
+ (x.(1) - 2. *. x.(2)) ** 4. + 10. * (x.(0) - x.(3)) ** 4.
in
let rfloat _ = Random.float 200. -. 100. in
let sample () = Array.init 4 ~f:rfloat in
let obj, _, _ = minimize ~f ~sample () in
Float.(abs obj < 1e-3)
|
f319699673e2229e9b316da4b99ba31a4c5badcdfd688d6d3d14cddb6e2bd869 | mzp/coq-ruby | lexer.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(*i $Id: lexer.mli 7732 2005-12-26 13:51:24Z herbelin $ i*)
open Pp
open Util
type error =
| Illegal_character
| Unterminated_comment
| Unterminated_string
| Undefined_token
| Bad_token of string
exception Error of error
val add_token : string * string -> unit
val is_keyword : string -> bool
val func : char Stream.t -> (string * string) Stream.t * (int -> loc)
val location_function : int -> loc
(* for coqdoc *)
type location_table
val location_table : unit -> location_table
val restore_location_table : location_table -> unit
val check_ident : string -> unit
val check_keyword : string -> unit
val tparse : string * string -> ((string * string) Stream.t -> string) option
val token_text : string * string -> string
type frozen_t
val freeze : unit -> frozen_t
val unfreeze : frozen_t -> unit
val init : unit -> unit
type com_state
val com_state: unit -> com_state
val restore_com_state: com_state -> unit
val set_xml_output_comment : (string -> unit) -> unit
val terminal : string -> string * string
| null | https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/parsing/lexer.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i $Id: lexer.mli 7732 2005-12-26 13:51:24Z herbelin $ i
for coqdoc | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Pp
open Util
type error =
| Illegal_character
| Unterminated_comment
| Unterminated_string
| Undefined_token
| Bad_token of string
exception Error of error
val add_token : string * string -> unit
val is_keyword : string -> bool
val func : char Stream.t -> (string * string) Stream.t * (int -> loc)
val location_function : int -> loc
type location_table
val location_table : unit -> location_table
val restore_location_table : location_table -> unit
val check_ident : string -> unit
val check_keyword : string -> unit
val tparse : string * string -> ((string * string) Stream.t -> string) option
val token_text : string * string -> string
type frozen_t
val freeze : unit -> frozen_t
val unfreeze : frozen_t -> unit
val init : unit -> unit
type com_state
val com_state: unit -> com_state
val restore_com_state: com_state -> unit
val set_xml_output_comment : (string -> unit) -> unit
val terminal : string -> string * string
|
947979c0ad85a1d162e92b2ff75f3fae23e1450a3d219ac2997c6858715d2da4 | opencog/opencog | filter-#17.scm | ;; anaphor is reflexive
;; The parse tree structure is:
;; verb
;; to / \ by
;; / \
;; antecedent anaphor
;; This antecedent should be rejected
;; Examples:
" went to the party by himself . "
;; "himself" should not refer to "party"
(define filter-#17
(BindLink
(VariableList
(TypedVariableLink
(VariableNode "$word-inst-antecedent")
(TypeNode "WordInstanceNode")
)
(TypedVariableLink
(VariableNode "$word-inst-anaphor")
(TypeNode "WordInstanceNode")
)
(TypedVariableLink
(VariableNode "$verb")
(TypeNode "WordInstanceNode")
)
)
(AndLink
Connection between two clauses
(ListLink
(AnchorNode "CurrentResolution")
(VariableNode "$word-inst-anaphor")
(VariableNode "$word-inst-antecedent")
)
(ListLink
(AnchorNode "CurrentPronoun")
(VariableNode "$word-inst-anaphor")
)
(ListLink
(AnchorNode "CurrentProposal")
(VariableNode "$word-inst-antecedent")
)
;; filter
(InheritanceLink
(VariableNode "$word-inst-anaphor")
(DefinedLinguisticConceptNode "reflexive")
)
(EvaluationLink
(PrepositionalRelationshipNode "to")
(ListLink
(VariableNode "$verb")
(VariableNode "$word-inst-antecedent")
)
)
(EvaluationLink
(PrepositionalRelationshipNode "by")
(ListLink
(VariableNode "$verb")
(VariableNode "$word-inst-anaphor")
)
)
)
(ListLink
(AnchorNode "CurrentResult")
(VariableNode "$word-inst-antecedent")
)
)
)
| null | https://raw.githubusercontent.com/opencog/opencog/53f2c2c8e26160e3321b399250afb0e3dbc64d4c/opencog/nlp/anaphora/rules/filters/filter-%2317.scm | scheme | anaphor is reflexive
The parse tree structure is:
verb
to / \ by
/ \
antecedent anaphor
This antecedent should be rejected
Examples:
"himself" should not refer to "party"
filter |
" went to the party by himself . "
(define filter-#17
(BindLink
(VariableList
(TypedVariableLink
(VariableNode "$word-inst-antecedent")
(TypeNode "WordInstanceNode")
)
(TypedVariableLink
(VariableNode "$word-inst-anaphor")
(TypeNode "WordInstanceNode")
)
(TypedVariableLink
(VariableNode "$verb")
(TypeNode "WordInstanceNode")
)
)
(AndLink
Connection between two clauses
(ListLink
(AnchorNode "CurrentResolution")
(VariableNode "$word-inst-anaphor")
(VariableNode "$word-inst-antecedent")
)
(ListLink
(AnchorNode "CurrentPronoun")
(VariableNode "$word-inst-anaphor")
)
(ListLink
(AnchorNode "CurrentProposal")
(VariableNode "$word-inst-antecedent")
)
(InheritanceLink
(VariableNode "$word-inst-anaphor")
(DefinedLinguisticConceptNode "reflexive")
)
(EvaluationLink
(PrepositionalRelationshipNode "to")
(ListLink
(VariableNode "$verb")
(VariableNode "$word-inst-antecedent")
)
)
(EvaluationLink
(PrepositionalRelationshipNode "by")
(ListLink
(VariableNode "$verb")
(VariableNode "$word-inst-anaphor")
)
)
)
(ListLink
(AnchorNode "CurrentResult")
(VariableNode "$word-inst-antecedent")
)
)
)
|
56f7227fe6ab0e6afdad3aefbfa0b2fa8b3a8fb665e930d97ad7a05eb40b3686 | takikawa/racket-ppa | info.rkt | (module info setup/infotab (#%module-begin (define collection (quote multi)) (define deps (quote ("scheme-lib" ("base" #:version "8.2.0.7") "at-exp-lib"))) (define pkg-desc "Language for text with embedded Racket code") (define pkg-authors (quote (mflatt eli))) (define version "1.1") (define license (quote (Apache-2.0 OR MIT)))))
| null | https://raw.githubusercontent.com/takikawa/racket-ppa/26d6ae74a1b19258c9789b7c14c074d867a4b56b/share/pkgs/scribble-text-lib/info.rkt | racket | (module info setup/infotab (#%module-begin (define collection (quote multi)) (define deps (quote ("scheme-lib" ("base" #:version "8.2.0.7") "at-exp-lib"))) (define pkg-desc "Language for text with embedded Racket code") (define pkg-authors (quote (mflatt eli))) (define version "1.1") (define license (quote (Apache-2.0 OR MIT)))))
|
|
a1752565f9f6a40867389e2979a6087f0fc79764f682cbed0cfdc51d0fbe8ed7 | yrashk/erlang | ts.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1997 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
%%%-------------------------------------------------------------------
%%% File : ts.erl
%%% Purpose : Frontend for running tests.
%%%-------------------------------------------------------------------
-module(ts).
-export([run/0, run/1, run/2, run/3, run/4,
clean/0, clean/1,
tests/0, tests/1,
install/0, install/1, install/2, index/0,
estone/0, estone/1,
cross_cover_analyse/1,
help/0]).
-export([i/0, l/1, r/0, r/1, r/2, r/3]).
%%%----------------------------------------------------------------------
%%% This module, ts, is the interface to all of the functionality of
%%% the TS framework. The picture below shows the relationship of
%%% the modules:
%%%
%%% +-- ts_install --+------ ts_autoconf_win32
%%% | |
%%% | +------ ts_autoconf_vxworks
%%% |
%%% ts ---+ +------ ts_erl_config
%%% | | ts_lib
%%% | +------ ts_make
%%% | |
%%% +-- ts_run -----+
%%% | ts_filelib
%%% +------ ts_make_erl
%%% |
%%% +------ ts_reports (indirectly)
%%%
%%%
%%%
%%% The modules ts_lib and ts_filelib contains utilities used by
%%% the other modules.
%%%
%%% Module Description
%%% ------ -----------
%%% ts Frontend to the test server framework. Contains all
%%% interface functions.
ts_install Installs the test suite . On Unix , ` autoconf ' is
is used ; on Windows , ts_autoconf_win32 is used ,
on , ts_autoconf_vxworks is used .
%%% The result is written to the file `variables'.
%%% ts_run Supervises running of the tests.
ts_autconf_win32 An ` autoconf ' for Windows .
ts_autconf_cross_env ` autoconf ' for other platforms ( cross environment )
ts_erl_config Finds out information about the Erlang system ,
%%% for instance the location of erl_interface.
This works for either an installed OTP or an Erlang
system running from Clearcase .
%%% ts_make Interface to run the `make' program on Unix
%%% and other platforms.
ts_make_erl A corrected version of the standar Erlang module
%%% make (used for rebuilding test suites).
%%% ts_reports Generates index pages in HTML, providing a summary
%%% of the tests run.
%%% ts_lib Miscellanous utility functions, each used by several
%%% other modules.
%%%----------------------------------------------------------------------
-include_lib("kernel/include/file.hrl").
-include("ts.hrl").
-define(
install_help,
[
" ts:install() - Install TS for local target with no Options.\n"
" ts:install([Options])\n",
" - Install TS for local target with Options\n"
" ts:install({Architecture, Target_name})\n",
" - Install TS for a remote target architecture.\n",
" and target network name (e.g. {vxworks_cpu32, sauron}).\n",
" ts:install({Architecture, Target_name}, [Options])\n",
" - Install TS as above, and with Options.\n",
"\n",
"Installation options supported:\n",
" {longnames, true} - Use fully qualified hostnames\n",
" {hosts, [HostList]}\n"
" - Use theese hosts for distributed testing.\n"
" {verbose, Level} - Sets verbosity level for TS output (0,1,2), 0 is\n"
" quiet(default).\n"
" {slavetargets, SlaveTarges}\n"
" - Available hosts for starting slave nodes for\n"
" platforms which cannot have more than one erlang\n"
" node per host.\n"
" {crossroot, TargetErlRoot}\n"
" - Erlang root directory on target host\n"
" Mandatory for remote targets\n"
" {master, {MasterHost, MasterCookie}}\n"
" - Master host and cookie for targets which are\n"
" started as slave nodes (i.e. OSE/Delta targets\n"
" erl_boot_server must be started on master before\n"
" test is run.\n"
" Optional, default is controller host and then\n"
" erl_boot_server is started autmatically\n"
]).
help() ->
case filelib:is_file(?variables) of
false -> help(uninstalled);
true -> help(installed)
end.
help(uninstalled) ->
H = ["TS is not installed yet. To install use:\n\n"],
show_help([H,?install_help]);
help(installed) ->
H = ["Run functions:\n",
" ts:run() - Run all available tests.\n",
" ts:run(Spec) - Run all tests in given test spec file.\n",
" The spec file is actually ../*_test/Spec.spec\n",
" ts:run([Specs]) - Run all tests in all given test spec files.\n",
" ts:run(Spec, Mod) - Run a single test suite.\n",
" ts:run(Spec, Mod, Case)\n",
" - Run a single test case.\n",
" All above run functions can have the additional Options argument\n",
" which is a list of options.\n",
"\n",
"Run options supported:\n",
" batch - Do not start a new xterm\n",
" {verbose, Level} - Same as the verbosity option for install\n",
" verbose - Same as {verbose, 1}\n",
" {vars, Vars} - Variables in addition to the 'variables' file\n",
" Can be any of the install options\n",
" {trace, TraceSpec}- Start call trace on target and slave nodes\n",
" TraceSpec is the name of a file containing\n",
" trace specifications or a list of trace\n",
" specification elements.\n",
"\n",
"Supported trace information elements\n",
" {tp | tpl, Mod, [] | match_spec()}\n",
" {tp | tpl, Mod, Func, [] | match_spec()}\n",
" {tp | tpl, Mod, Func, Arity, [] | match_spec()}\n",
" {ctp | ctpl, Mod}\n",
" {ctp | ctpl, Mod, Func}\n",
" {ctp | ctpl, Mod, Func, Arity}\n",
"\n",
"Support functions\n",
" ts:tests() - Shows all available families of tests.\n",
" ts:tests(Spec) - Shows all available test modules in Spec,\n",
" i.e. ../Spec_test/*_SUITE.erl\n",
" ts:index() - Updates local index page.\n",
" ts:clean() - Cleans up all but the last tests run.\n",
" ts:clean(all) - Cleans up all test runs found.\n",
" ts:estone() - Run estone_SUITE in kernel application with\n"
" no run options\n",
" ts:estone(Opts) - Run estone_SUITE in kernel application with\n"
" the given run options\n",
" ts:cross_cover_analyse(Level)\n"
" - Used after ts:run with option cover or \n"
" cover_details. Analyses modules specified in\n"
" cross.cover.\n"
" Level can be 'overview' or 'details'.\n",
" \n"
"Installation (already done):\n"
],
show_help([H,?install_help]).
show_help(H) ->
io:put_chars(lists:flatten(H)).
Installs tests .
install() ->
ts_install:install(install_local,[]).
install({Architecture, Target_name}) ->
ts_install:install({ts_lib:maybe_atom_to_list(Architecture),
ts_lib:maybe_atom_to_list(Target_name)}, []);
install(Options) when is_list(Options) ->
ts_install:install(install_local,Options).
install({Architecture, Target_name}, Options) when is_list(Options)->
ts_install:install({ts_lib:maybe_atom_to_list(Architecture),
ts_lib:maybe_atom_to_list(Target_name)}, Options).
%% Updates the local index page.
index() ->
check_and_run(fun(_Vars) -> ts_reports:make_index(), ok end).
%%
%% clean(all)
%% Deletes all logfiles.
%%
clean(all) ->
delete_files(filelib:wildcard("*" ++ ?logdir_ext)).
%% clean/0
%%
%% Cleans up run logfiles, all but the last run.
clean() ->
clean1(filelib:wildcard("*" ++ ?logdir_ext)).
clean1([Dir|Dirs]) ->
List0 = filelib:wildcard(filename:join(Dir, "run.*")),
case lists:reverse(lists:sort(List0)) of
[] -> ok;
[_Last|Rest] -> delete_files(Rest)
end,
clean1(Dirs);
clean1([]) -> ok.
%% run/0
%% Runs all specs found by ts:tests(), if any, or returns
%% {error, no_tests_available}. (batch)
run() ->
case ts:tests() of
[] ->
{error, no_tests_available};
_ ->
check_and_run(fun(Vars) -> run_all(Vars) end)
end.
run_all(_Vars) ->
run_some(tests(), [batch]).
run_some([], _Opts) ->
ok;
run_some([Spec|Specs], Opts) ->
case run(Spec, Opts) of
ok -> ok;
Error -> io:format("~p: ~p~n",[Spec,Error])
end,
run_some(Specs, Opts).
Runs one test spec ( interactive ) .
run(Testspec) when is_atom(Testspec) ->
Options=check_test_get_opts(Testspec, []),
File = atom_to_list(Testspec),
run_test(File, ["SPEC current.spec NAME ",File], Options);
%% This can be used from command line, e.g.
%% erl -s ts run all_tests <config>
%% When using the all_tests flag and running with cover, one can also
%% use the cross_cover_analysis flag.
run([all_tests|Config0]) ->
AllAtomsFun = fun(X) when is_atom(X) -> true;
(_) -> false
end,
Config1 =
case lists:all(AllAtomsFun,Config0) of
true ->
%% Could be from command line
lists:map(fun(Conf)->to_erlang_term(Conf) end,Config0)--[batch];
false ->
Config0--[batch]
end,
%% Make sure there is exactly one occurence of 'batch'
Config2 = [batch|Config1],
R = run(tests(),Config2),
case check_for_cross_cover_analysis_flag(Config2) of
false ->
ok;
Level ->
cross_cover_analyse(Level)
end,
R;
%% ts:run(ListOfTests)
run(List) when is_list(List) ->
run(List, [batch]).
run(List, Opts) when is_list(List), is_list(Opts) ->
run_some(List, Opts);
%% run/2
Runs one test spec with Options
run(Testspec, Config) when is_atom(Testspec), is_list(Config) ->
Options=check_test_get_opts(Testspec, Config),
File=atom_to_list(Testspec),
run_test(File, ["SPEC current.spec NAME ", File], Options);
Runs one module in a spec ( interactive )
run(Testspec, Mod) when is_atom(Testspec), is_atom(Mod) ->
run_test({atom_to_list(Testspec), Mod},
["SPEC current.spec NAME ", atom_to_list(Mod)],
[interactive]).
%% run/3
%% Run one module in a spec with Config
run(Testspec,Mod,Config) when is_atom(Testspec), is_atom(Mod), is_list(Config) ->
Options=check_test_get_opts(Testspec, Config),
run_test({atom_to_list(Testspec), Mod},
["SPEC current.spec NAME ", atom_to_list(Mod)],
Options);
Runs one testcase in a module .
run(Testspec, Mod, Case) when is_atom(Testspec), is_atom(Mod), is_atom(Case) ->
Options=check_test_get_opts(Testspec, []),
Args = ["CASE ",atom_to_list(Mod)," ",atom_to_list(Case)],
run_test(atom_to_list(Testspec), Args, Options).
%% run/4
Run one testcase in a module with Options .
run(Testspec, Mod, Case, Config) when is_atom(Testspec), is_atom(Mod), is_atom(Case), is_list(Config) ->
Options=check_test_get_opts(Testspec, Config),
Args = ["CASE ",atom_to_list(Mod), " ",atom_to_list(Case)],
run_test(atom_to_list(Testspec), Args, Options).
Check to be valid and get possible Options
%% from the config.
check_test_get_opts(Testspec, Config) ->
validate_test(Testspec),
Mode = configmember(batch, {batch, interactive}, Config),
Vars = configvars(Config),
Trace = configtrace(Config),
KeepTopcase = configmember(keep_topcase, {keep_topcase,[]}, Config),
Cover = configcover(Testspec,Config),
lists:flatten([Vars,Mode,Trace,KeepTopcase,Cover]).
to_erlang_term(Atom) ->
String = atom_to_list(Atom),
{ok, Tokens, _} = erl_scan:string(lists:append([String, ". "])),
{ok, Term} = erl_parse:parse_term(Tokens),
Term.
Validate that a really is a testspec ,
%% and exit if not.
validate_test(Testspec) ->
case lists:member(Testspec, tests()) of
true ->
ok;
false ->
io:format("This testspec does not seem to be "
"available.~n Please try ts:tests() "
"to see available tests.~n"),
exit(self(), {error, test_not_available})
end.
configvars(Config) ->
case lists:keysearch(vars, 1, Config) of
{value, {vars, List}} ->
List0 = special_vars(Config),
{vars, [List0|List]};
_ ->
{vars, special_vars(Config)}
end.
%% Allow some shortcuts in the Options...
special_vars(Config) ->
Verbose=
case lists:member(verbose, Config) of
true ->
{verbose, 1};
false ->
case lists:keysearch(verbose, 1, Config) of
{value, {verbose, Lvl}} ->
{verbose, Lvl};
_ ->
{verbose, 0}
end
end,
case lists:keysearch(diskless, 1, Config) of
{value,{diskless, true}} ->
[Verbose,{diskless, true}];
_ ->
[Verbose]
end.
configtrace(Config) ->
case lists:keysearch(trace,1,Config) of
{value,Value} -> Value;
false -> []
end.
configcover(Testspec,[cover|_]) ->
{cover,Testspec,default_coverfile(Testspec),overview};
configcover(Testspec,[cover_details|_]) ->
{cover,Testspec,default_coverfile(Testspec),details};
configcover(Testspec,[{cover,File}|_]) ->
{cover,Testspec,File,overview};
configcover(Testspec,[{cover_details,File}|_]) ->
{cover,Testspec,File,details};
configcover(Testspec,[_H|T]) ->
configcover(Testspec,T);
configcover(_Testspec,[]) ->
[].
default_coverfile(Testspec) ->
{ok,Cwd} = file:get_cwd(),
CoverFile = filename:join([filename:dirname(Cwd),
atom_to_list(Testspec)++"_test",
atom_to_list(Testspec)++".cover"]),
case filelib:is_file(CoverFile) of
true ->
CoverFile;
false ->
none
end.
configmember(Member, {True, False}, Config) ->
case lists:member(Member, Config) of
true ->
True;
false ->
False
end.
check_for_cross_cover_analysis_flag(Config) ->
check_for_cross_cover_analysis_flag(Config,false,false).
check_for_cross_cover_analysis_flag([cover|Config],false,false) ->
check_for_cross_cover_analysis_flag(Config,overview,false);
check_for_cross_cover_analysis_flag([cover|_Config],false,true) ->
overview;
check_for_cross_cover_analysis_flag([cover_details|Config],false,false) ->
check_for_cross_cover_analysis_flag(Config,details,false);
check_for_cross_cover_analysis_flag([cover_details|_Config],false,true) ->
details;
check_for_cross_cover_analysis_flag([cross_cover_analysis|Config],false,_) ->
check_for_cross_cover_analysis_flag(Config,false,true);
check_for_cross_cover_analysis_flag([cross_cover_analysis|_Config],Level,_) ->
Level;
check_for_cross_cover_analysis_flag([_|Config],Level,CrossFlag) ->
check_for_cross_cover_analysis_flag(Config,Level,CrossFlag);
check_for_cross_cover_analysis_flag([],_,_) ->
false.
%% Returns a list of available test suites.
tests() ->
{ok, Cwd} = file:get_cwd(),
ts_lib:specs(Cwd).
tests(Spec) ->
{ok, Cwd} = file:get_cwd(),
ts_lib:suites(Cwd, atom_to_list(Spec)).
%%
%% estone/0, estone/1
Opts = same as Opts or Config for the run ( ... ) function ,
%% e.g. [batch]
%%
estone() -> run(emulator,estone_SUITE).
estone(Opts) when is_list(Opts) -> run(emulator,estone_SUITE,Opts).
%%
%% cross_cover_analyse/1
%% Level = details | overview
%% Can be called on any node after a test (with cover) is
%% completed. The node's current directory must be the same as when
%% the tests were run.
%%
cross_cover_analyse([Level]) ->
cross_cover_analyse(Level);
cross_cover_analyse(Level) ->
test_server_ctrl:cross_cover_analyse(Level).
%%% Implementation.
check_and_run(Fun) ->
case file:consult(?variables) of
{ok, Vars} ->
check_and_run(Fun, Vars);
{error, Error} when is_atom(Error) ->
{error, not_installed};
{error, Reason} ->
{error, {bad_installation, file:format_error(Reason)}}
end.
check_and_run(Fun, Vars) ->
Platform = ts_install:platform_id(Vars),
case lists:keysearch(platform_id, 1, Vars) of
{value, {_, Platform}} ->
case catch apply(Fun, [Vars]) of
{'EXIT', Reason} ->
exit(Reason);
Other ->
Other
end;
{value, {_, OriginalPlatform}} ->
io:format("These test suites were installed for '~s'.\n",
[OriginalPlatform]),
io:format("But the current platform is '~s'.\nPlease "
"install for this platform before running "
"any tests.\n", [Platform]),
{error, inconsistent_platforms};
false ->
{error, {bad_installation, no_platform}}
end.
run_test(File, Args, Options) ->
check_and_run(fun(Vars) -> run_test(File, Args, Options, Vars) end).
run_test(File, Args, Options, Vars) ->
ts_run:run(File, Args, Options, Vars).
delete_files([]) -> ok;
delete_files([Item|Rest]) ->
case file:delete(Item) of
ok ->
delete_files(Rest);
{error,eperm} ->
file:change_mode(Item, 8#777),
delete_files(filelib:wildcard(filename:join(Item, "*"))),
file:del_dir(Item),
ok;
{error,eacces} ->
%% We'll see about that!
file:change_mode(Item, 8#777),
case file:delete(Item) of
ok -> ok;
{error,_} ->
erlang:yield(),
file:change_mode(Item, 8#777),
file:delete(Item),
ok
end;
{error,_} -> ok
end,
delete_files(Rest).
%% This module provides some convenient shortcuts to running
the test server from within a started Erlang shell .
%% (This are here for backwards compatibility.)
%%
%% r()
%% r(Opts)
%% r(SpecOrMod)
r(SpecOrMod , )
%% r(Mod, Case)
r(Mod , Case , )
%% Each of these functions starts the test server if it
%% isn't already running, then runs the test case(s) selected
%% by the aguments.
SpecOrMod can be a module name or the name of a test spec file ,
with the extension .spec or .spec . OsType . The module Mod will
%% be reloaded before running the test cases.
%% Opts = [Opt],
Opt = { Cover , AppOrCoverFile } | { Cover , App , CoverFile }
%% Cover = cover | cover_details
AppOrCoverFile = App | CoverFile
%% App = atom(), an application name
%% CoverFile = string(), name of a cover file
( see doc of : cover/2/3 )
%%
%% i()
%% Shows information about the jobs being run, by dumping
the process information for the test_server .
%%
l(Mod )
%% This function reloads a module just like c:l/1, but works
%% even for a module in one of the sticky library directories
%% (for instance, lists can be reloaded).
%% Runs all tests cases in the current directory.
r() ->
r([]).
r(Opts) when is_list(Opts), is_atom(hd(Opts)) ->
ensure_ts_started(Opts),
test_server_ctrl:add_dir("current_dir", ".");
%% Checks if argument is a spec file or a module
%% (spec file must be named "*.spec" or "*.spec.OsType")
%% If module, reloads module and runs all test cases in it.
%% If spec, runs all test cases in it.
r(SpecOrMod) ->
r(SpecOrMod,[]).
r(SpecOrMod,Opts) when is_list(Opts) ->
ensure_ts_started(Opts),
case filename:extension(SpecOrMod) of
[] ->
l(SpecOrMod),
test_server_ctrl:add_module(SpecOrMod);
".spec" ->
test_server_ctrl:add_spec(SpecOrMod);
_ ->
Spec2 = filename:rootname(SpecOrMod),
case filename:extension(Spec2) of
".spec" ->
%% *.spec.Type
test_server_ctrl:add_spec(SpecOrMod);
_ ->
{error, unknown_filetype}
end
end;
%% Reloads the given module and runs the given test case in it.
r(Mod, Case) ->
r(Mod,Case,[]).
r(Mod, Case, Opts) ->
ensure_ts_started(Opts),
l(Mod),
test_server_ctrl:add_case(Mod, Case).
%% Shows information about the jobs being run.
i() ->
ensure_ts_started([]),
hformat("Job", "Current", "Total", "Success", "Failed", "Skipped"),
i(test_server_ctrl:jobs()).
i([{Name, Pid}|Rest]) when is_pid(Pid) ->
{dictionary, PI} = process_info(Pid, dictionary),
{value, {_, CaseNum}} = lists:keysearch(test_server_case_num, 1, PI),
{value, {_, Cases}} = lists:keysearch(test_server_cases, 1, PI),
{value, {_, Failed}} = lists:keysearch(test_server_failed, 1, PI),
{value, {_, Skipped}} = lists:keysearch(test_server_skipped, 1, PI),
{value, {_, Ok}} = lists:keysearch(test_server_ok, 1, PI),
nformat(Name, CaseNum, Cases, Ok, Failed, Skipped),
i(Rest);
i([]) ->
ok.
hformat(A1, A2, A3, A4, A5, A6) ->
io:format("~-20s ~8s ~8s ~8s ~8s ~8s~n", [A1,A2,A3,A4,A5,A6]).
nformat(A1, A2, A3, A4, A5, A6) ->
io:format("~-20s ~8w ~8w ~8w ~8w ~8w~n", [A1,A2,A3,A4,A5,A6]).
Force load of a module even if it is in a sticky directory .
l(Mod) ->
case do_load(Mod) of
{error, sticky_directory} ->
Dir = filename:dirname(code:which(Mod)),
code:unstick_dir(Dir),
do_load(Mod),
code:stick_dir(Dir);
X ->
X
end.
ensure_ts_started(Opts) ->
Pid = case whereis(test_server_ctrl) of
undefined ->
test_server_ctrl:start();
P when is_pid(P) ->
P
end,
case Opts of
[{Cover,AppOrCoverFile}] when Cover==cover; Cover==cover_details ->
test_server_ctrl:cover(AppOrCoverFile,cover_type(Cover));
[{Cover,App,CoverFile}] when Cover==cover; Cover==cover_details ->
test_server_ctrl:cover(App,CoverFile,cover_type(Cover));
_ ->
ok
end,
Pid.
cover_type(cover) -> overview;
cover_type(cover_details) -> details.
do_load(Mod) ->
code:purge(Mod),
code:load_file(Mod).
| null | https://raw.githubusercontent.com/yrashk/erlang/e1282325ed75e52a98d58f5bd9fb0fa27896173f/lib/test_server/src/ts.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
-------------------------------------------------------------------
File : ts.erl
Purpose : Frontend for running tests.
-------------------------------------------------------------------
----------------------------------------------------------------------
This module, ts, is the interface to all of the functionality of
the TS framework. The picture below shows the relationship of
the modules:
+-- ts_install --+------ ts_autoconf_win32
| |
| +------ ts_autoconf_vxworks
|
ts ---+ +------ ts_erl_config
| | ts_lib
| +------ ts_make
| |
+-- ts_run -----+
| ts_filelib
+------ ts_make_erl
|
+------ ts_reports (indirectly)
The modules ts_lib and ts_filelib contains utilities used by
the other modules.
Module Description
------ -----------
ts Frontend to the test server framework. Contains all
interface functions.
The result is written to the file `variables'.
ts_run Supervises running of the tests.
for instance the location of erl_interface.
ts_make Interface to run the `make' program on Unix
and other platforms.
make (used for rebuilding test suites).
ts_reports Generates index pages in HTML, providing a summary
of the tests run.
ts_lib Miscellanous utility functions, each used by several
other modules.
----------------------------------------------------------------------
Updates the local index page.
clean(all)
Deletes all logfiles.
clean/0
Cleans up run logfiles, all but the last run.
run/0
Runs all specs found by ts:tests(), if any, or returns
{error, no_tests_available}. (batch)
This can be used from command line, e.g.
erl -s ts run all_tests <config>
When using the all_tests flag and running with cover, one can also
use the cross_cover_analysis flag.
Could be from command line
Make sure there is exactly one occurence of 'batch'
ts:run(ListOfTests)
run/2
run/3
Run one module in a spec with Config
run/4
from the config.
and exit if not.
Allow some shortcuts in the Options...
Returns a list of available test suites.
estone/0, estone/1
e.g. [batch]
cross_cover_analyse/1
Level = details | overview
Can be called on any node after a test (with cover) is
completed. The node's current directory must be the same as when
the tests were run.
Implementation.
We'll see about that!
This module provides some convenient shortcuts to running
(This are here for backwards compatibility.)
r()
r(Opts)
r(SpecOrMod)
r(Mod, Case)
Each of these functions starts the test server if it
isn't already running, then runs the test case(s) selected
by the aguments.
be reloaded before running the test cases.
Opts = [Opt],
Cover = cover | cover_details
App = atom(), an application name
CoverFile = string(), name of a cover file
i()
Shows information about the jobs being run, by dumping
This function reloads a module just like c:l/1, but works
even for a module in one of the sticky library directories
(for instance, lists can be reloaded).
Runs all tests cases in the current directory.
Checks if argument is a spec file or a module
(spec file must be named "*.spec" or "*.spec.OsType")
If module, reloads module and runs all test cases in it.
If spec, runs all test cases in it.
*.spec.Type
Reloads the given module and runs the given test case in it.
Shows information about the jobs being run. | Copyright Ericsson AB 1997 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(ts).
-export([run/0, run/1, run/2, run/3, run/4,
clean/0, clean/1,
tests/0, tests/1,
install/0, install/1, install/2, index/0,
estone/0, estone/1,
cross_cover_analyse/1,
help/0]).
-export([i/0, l/1, r/0, r/1, r/2, r/3]).
ts_install Installs the test suite . On Unix , ` autoconf ' is
is used ; on Windows , ts_autoconf_win32 is used ,
on , ts_autoconf_vxworks is used .
ts_autconf_win32 An ` autoconf ' for Windows .
ts_autconf_cross_env ` autoconf ' for other platforms ( cross environment )
ts_erl_config Finds out information about the Erlang system ,
This works for either an installed OTP or an Erlang
system running from Clearcase .
ts_make_erl A corrected version of the standar Erlang module
-include_lib("kernel/include/file.hrl").
-include("ts.hrl").
-define(
install_help,
[
" ts:install() - Install TS for local target with no Options.\n"
" ts:install([Options])\n",
" - Install TS for local target with Options\n"
" ts:install({Architecture, Target_name})\n",
" - Install TS for a remote target architecture.\n",
" and target network name (e.g. {vxworks_cpu32, sauron}).\n",
" ts:install({Architecture, Target_name}, [Options])\n",
" - Install TS as above, and with Options.\n",
"\n",
"Installation options supported:\n",
" {longnames, true} - Use fully qualified hostnames\n",
" {hosts, [HostList]}\n"
" - Use theese hosts for distributed testing.\n"
" {verbose, Level} - Sets verbosity level for TS output (0,1,2), 0 is\n"
" quiet(default).\n"
" {slavetargets, SlaveTarges}\n"
" - Available hosts for starting slave nodes for\n"
" platforms which cannot have more than one erlang\n"
" node per host.\n"
" {crossroot, TargetErlRoot}\n"
" - Erlang root directory on target host\n"
" Mandatory for remote targets\n"
" {master, {MasterHost, MasterCookie}}\n"
" - Master host and cookie for targets which are\n"
" started as slave nodes (i.e. OSE/Delta targets\n"
" erl_boot_server must be started on master before\n"
" test is run.\n"
" Optional, default is controller host and then\n"
" erl_boot_server is started autmatically\n"
]).
help() ->
case filelib:is_file(?variables) of
false -> help(uninstalled);
true -> help(installed)
end.
help(uninstalled) ->
H = ["TS is not installed yet. To install use:\n\n"],
show_help([H,?install_help]);
help(installed) ->
H = ["Run functions:\n",
" ts:run() - Run all available tests.\n",
" ts:run(Spec) - Run all tests in given test spec file.\n",
" The spec file is actually ../*_test/Spec.spec\n",
" ts:run([Specs]) - Run all tests in all given test spec files.\n",
" ts:run(Spec, Mod) - Run a single test suite.\n",
" ts:run(Spec, Mod, Case)\n",
" - Run a single test case.\n",
" All above run functions can have the additional Options argument\n",
" which is a list of options.\n",
"\n",
"Run options supported:\n",
" batch - Do not start a new xterm\n",
" {verbose, Level} - Same as the verbosity option for install\n",
" verbose - Same as {verbose, 1}\n",
" {vars, Vars} - Variables in addition to the 'variables' file\n",
" Can be any of the install options\n",
" {trace, TraceSpec}- Start call trace on target and slave nodes\n",
" TraceSpec is the name of a file containing\n",
" trace specifications or a list of trace\n",
" specification elements.\n",
"\n",
"Supported trace information elements\n",
" {tp | tpl, Mod, [] | match_spec()}\n",
" {tp | tpl, Mod, Func, [] | match_spec()}\n",
" {tp | tpl, Mod, Func, Arity, [] | match_spec()}\n",
" {ctp | ctpl, Mod}\n",
" {ctp | ctpl, Mod, Func}\n",
" {ctp | ctpl, Mod, Func, Arity}\n",
"\n",
"Support functions\n",
" ts:tests() - Shows all available families of tests.\n",
" ts:tests(Spec) - Shows all available test modules in Spec,\n",
" i.e. ../Spec_test/*_SUITE.erl\n",
" ts:index() - Updates local index page.\n",
" ts:clean() - Cleans up all but the last tests run.\n",
" ts:clean(all) - Cleans up all test runs found.\n",
" ts:estone() - Run estone_SUITE in kernel application with\n"
" no run options\n",
" ts:estone(Opts) - Run estone_SUITE in kernel application with\n"
" the given run options\n",
" ts:cross_cover_analyse(Level)\n"
" - Used after ts:run with option cover or \n"
" cover_details. Analyses modules specified in\n"
" cross.cover.\n"
" Level can be 'overview' or 'details'.\n",
" \n"
"Installation (already done):\n"
],
show_help([H,?install_help]).
show_help(H) ->
io:put_chars(lists:flatten(H)).
Installs tests .
install() ->
ts_install:install(install_local,[]).
install({Architecture, Target_name}) ->
ts_install:install({ts_lib:maybe_atom_to_list(Architecture),
ts_lib:maybe_atom_to_list(Target_name)}, []);
install(Options) when is_list(Options) ->
ts_install:install(install_local,Options).
install({Architecture, Target_name}, Options) when is_list(Options)->
ts_install:install({ts_lib:maybe_atom_to_list(Architecture),
ts_lib:maybe_atom_to_list(Target_name)}, Options).
index() ->
check_and_run(fun(_Vars) -> ts_reports:make_index(), ok end).
clean(all) ->
delete_files(filelib:wildcard("*" ++ ?logdir_ext)).
clean() ->
clean1(filelib:wildcard("*" ++ ?logdir_ext)).
clean1([Dir|Dirs]) ->
List0 = filelib:wildcard(filename:join(Dir, "run.*")),
case lists:reverse(lists:sort(List0)) of
[] -> ok;
[_Last|Rest] -> delete_files(Rest)
end,
clean1(Dirs);
clean1([]) -> ok.
run() ->
case ts:tests() of
[] ->
{error, no_tests_available};
_ ->
check_and_run(fun(Vars) -> run_all(Vars) end)
end.
run_all(_Vars) ->
run_some(tests(), [batch]).
run_some([], _Opts) ->
ok;
run_some([Spec|Specs], Opts) ->
case run(Spec, Opts) of
ok -> ok;
Error -> io:format("~p: ~p~n",[Spec,Error])
end,
run_some(Specs, Opts).
Runs one test spec ( interactive ) .
run(Testspec) when is_atom(Testspec) ->
Options=check_test_get_opts(Testspec, []),
File = atom_to_list(Testspec),
run_test(File, ["SPEC current.spec NAME ",File], Options);
run([all_tests|Config0]) ->
AllAtomsFun = fun(X) when is_atom(X) -> true;
(_) -> false
end,
Config1 =
case lists:all(AllAtomsFun,Config0) of
true ->
lists:map(fun(Conf)->to_erlang_term(Conf) end,Config0)--[batch];
false ->
Config0--[batch]
end,
Config2 = [batch|Config1],
R = run(tests(),Config2),
case check_for_cross_cover_analysis_flag(Config2) of
false ->
ok;
Level ->
cross_cover_analyse(Level)
end,
R;
run(List) when is_list(List) ->
run(List, [batch]).
run(List, Opts) when is_list(List), is_list(Opts) ->
run_some(List, Opts);
Runs one test spec with Options
run(Testspec, Config) when is_atom(Testspec), is_list(Config) ->
Options=check_test_get_opts(Testspec, Config),
File=atom_to_list(Testspec),
run_test(File, ["SPEC current.spec NAME ", File], Options);
Runs one module in a spec ( interactive )
run(Testspec, Mod) when is_atom(Testspec), is_atom(Mod) ->
run_test({atom_to_list(Testspec), Mod},
["SPEC current.spec NAME ", atom_to_list(Mod)],
[interactive]).
run(Testspec,Mod,Config) when is_atom(Testspec), is_atom(Mod), is_list(Config) ->
Options=check_test_get_opts(Testspec, Config),
run_test({atom_to_list(Testspec), Mod},
["SPEC current.spec NAME ", atom_to_list(Mod)],
Options);
Runs one testcase in a module .
run(Testspec, Mod, Case) when is_atom(Testspec), is_atom(Mod), is_atom(Case) ->
Options=check_test_get_opts(Testspec, []),
Args = ["CASE ",atom_to_list(Mod)," ",atom_to_list(Case)],
run_test(atom_to_list(Testspec), Args, Options).
Run one testcase in a module with Options .
run(Testspec, Mod, Case, Config) when is_atom(Testspec), is_atom(Mod), is_atom(Case), is_list(Config) ->
Options=check_test_get_opts(Testspec, Config),
Args = ["CASE ",atom_to_list(Mod), " ",atom_to_list(Case)],
run_test(atom_to_list(Testspec), Args, Options).
Check to be valid and get possible Options
check_test_get_opts(Testspec, Config) ->
validate_test(Testspec),
Mode = configmember(batch, {batch, interactive}, Config),
Vars = configvars(Config),
Trace = configtrace(Config),
KeepTopcase = configmember(keep_topcase, {keep_topcase,[]}, Config),
Cover = configcover(Testspec,Config),
lists:flatten([Vars,Mode,Trace,KeepTopcase,Cover]).
to_erlang_term(Atom) ->
String = atom_to_list(Atom),
{ok, Tokens, _} = erl_scan:string(lists:append([String, ". "])),
{ok, Term} = erl_parse:parse_term(Tokens),
Term.
Validate that a really is a testspec ,
validate_test(Testspec) ->
case lists:member(Testspec, tests()) of
true ->
ok;
false ->
io:format("This testspec does not seem to be "
"available.~n Please try ts:tests() "
"to see available tests.~n"),
exit(self(), {error, test_not_available})
end.
configvars(Config) ->
case lists:keysearch(vars, 1, Config) of
{value, {vars, List}} ->
List0 = special_vars(Config),
{vars, [List0|List]};
_ ->
{vars, special_vars(Config)}
end.
special_vars(Config) ->
Verbose=
case lists:member(verbose, Config) of
true ->
{verbose, 1};
false ->
case lists:keysearch(verbose, 1, Config) of
{value, {verbose, Lvl}} ->
{verbose, Lvl};
_ ->
{verbose, 0}
end
end,
case lists:keysearch(diskless, 1, Config) of
{value,{diskless, true}} ->
[Verbose,{diskless, true}];
_ ->
[Verbose]
end.
configtrace(Config) ->
case lists:keysearch(trace,1,Config) of
{value,Value} -> Value;
false -> []
end.
configcover(Testspec,[cover|_]) ->
{cover,Testspec,default_coverfile(Testspec),overview};
configcover(Testspec,[cover_details|_]) ->
{cover,Testspec,default_coverfile(Testspec),details};
configcover(Testspec,[{cover,File}|_]) ->
{cover,Testspec,File,overview};
configcover(Testspec,[{cover_details,File}|_]) ->
{cover,Testspec,File,details};
configcover(Testspec,[_H|T]) ->
configcover(Testspec,T);
configcover(_Testspec,[]) ->
[].
default_coverfile(Testspec) ->
{ok,Cwd} = file:get_cwd(),
CoverFile = filename:join([filename:dirname(Cwd),
atom_to_list(Testspec)++"_test",
atom_to_list(Testspec)++".cover"]),
case filelib:is_file(CoverFile) of
true ->
CoverFile;
false ->
none
end.
configmember(Member, {True, False}, Config) ->
case lists:member(Member, Config) of
true ->
True;
false ->
False
end.
check_for_cross_cover_analysis_flag(Config) ->
check_for_cross_cover_analysis_flag(Config,false,false).
check_for_cross_cover_analysis_flag([cover|Config],false,false) ->
check_for_cross_cover_analysis_flag(Config,overview,false);
check_for_cross_cover_analysis_flag([cover|_Config],false,true) ->
overview;
check_for_cross_cover_analysis_flag([cover_details|Config],false,false) ->
check_for_cross_cover_analysis_flag(Config,details,false);
check_for_cross_cover_analysis_flag([cover_details|_Config],false,true) ->
details;
check_for_cross_cover_analysis_flag([cross_cover_analysis|Config],false,_) ->
check_for_cross_cover_analysis_flag(Config,false,true);
check_for_cross_cover_analysis_flag([cross_cover_analysis|_Config],Level,_) ->
Level;
check_for_cross_cover_analysis_flag([_|Config],Level,CrossFlag) ->
check_for_cross_cover_analysis_flag(Config,Level,CrossFlag);
check_for_cross_cover_analysis_flag([],_,_) ->
false.
tests() ->
{ok, Cwd} = file:get_cwd(),
ts_lib:specs(Cwd).
tests(Spec) ->
{ok, Cwd} = file:get_cwd(),
ts_lib:suites(Cwd, atom_to_list(Spec)).
Opts = same as Opts or Config for the run ( ... ) function ,
estone() -> run(emulator,estone_SUITE).
estone(Opts) when is_list(Opts) -> run(emulator,estone_SUITE,Opts).
cross_cover_analyse([Level]) ->
cross_cover_analyse(Level);
cross_cover_analyse(Level) ->
test_server_ctrl:cross_cover_analyse(Level).
check_and_run(Fun) ->
case file:consult(?variables) of
{ok, Vars} ->
check_and_run(Fun, Vars);
{error, Error} when is_atom(Error) ->
{error, not_installed};
{error, Reason} ->
{error, {bad_installation, file:format_error(Reason)}}
end.
check_and_run(Fun, Vars) ->
Platform = ts_install:platform_id(Vars),
case lists:keysearch(platform_id, 1, Vars) of
{value, {_, Platform}} ->
case catch apply(Fun, [Vars]) of
{'EXIT', Reason} ->
exit(Reason);
Other ->
Other
end;
{value, {_, OriginalPlatform}} ->
io:format("These test suites were installed for '~s'.\n",
[OriginalPlatform]),
io:format("But the current platform is '~s'.\nPlease "
"install for this platform before running "
"any tests.\n", [Platform]),
{error, inconsistent_platforms};
false ->
{error, {bad_installation, no_platform}}
end.
run_test(File, Args, Options) ->
check_and_run(fun(Vars) -> run_test(File, Args, Options, Vars) end).
run_test(File, Args, Options, Vars) ->
ts_run:run(File, Args, Options, Vars).
delete_files([]) -> ok;
delete_files([Item|Rest]) ->
case file:delete(Item) of
ok ->
delete_files(Rest);
{error,eperm} ->
file:change_mode(Item, 8#777),
delete_files(filelib:wildcard(filename:join(Item, "*"))),
file:del_dir(Item),
ok;
{error,eacces} ->
file:change_mode(Item, 8#777),
case file:delete(Item) of
ok -> ok;
{error,_} ->
erlang:yield(),
file:change_mode(Item, 8#777),
file:delete(Item),
ok
end;
{error,_} -> ok
end,
delete_files(Rest).
the test server from within a started Erlang shell .
r(SpecOrMod , )
r(Mod , Case , )
SpecOrMod can be a module name or the name of a test spec file ,
with the extension .spec or .spec . OsType . The module Mod will
Opt = { Cover , AppOrCoverFile } | { Cover , App , CoverFile }
AppOrCoverFile = App | CoverFile
( see doc of : cover/2/3 )
the process information for the test_server .
l(Mod )
r() ->
r([]).
r(Opts) when is_list(Opts), is_atom(hd(Opts)) ->
ensure_ts_started(Opts),
test_server_ctrl:add_dir("current_dir", ".");
r(SpecOrMod) ->
r(SpecOrMod,[]).
r(SpecOrMod,Opts) when is_list(Opts) ->
ensure_ts_started(Opts),
case filename:extension(SpecOrMod) of
[] ->
l(SpecOrMod),
test_server_ctrl:add_module(SpecOrMod);
".spec" ->
test_server_ctrl:add_spec(SpecOrMod);
_ ->
Spec2 = filename:rootname(SpecOrMod),
case filename:extension(Spec2) of
".spec" ->
test_server_ctrl:add_spec(SpecOrMod);
_ ->
{error, unknown_filetype}
end
end;
r(Mod, Case) ->
r(Mod,Case,[]).
r(Mod, Case, Opts) ->
ensure_ts_started(Opts),
l(Mod),
test_server_ctrl:add_case(Mod, Case).
i() ->
ensure_ts_started([]),
hformat("Job", "Current", "Total", "Success", "Failed", "Skipped"),
i(test_server_ctrl:jobs()).
i([{Name, Pid}|Rest]) when is_pid(Pid) ->
{dictionary, PI} = process_info(Pid, dictionary),
{value, {_, CaseNum}} = lists:keysearch(test_server_case_num, 1, PI),
{value, {_, Cases}} = lists:keysearch(test_server_cases, 1, PI),
{value, {_, Failed}} = lists:keysearch(test_server_failed, 1, PI),
{value, {_, Skipped}} = lists:keysearch(test_server_skipped, 1, PI),
{value, {_, Ok}} = lists:keysearch(test_server_ok, 1, PI),
nformat(Name, CaseNum, Cases, Ok, Failed, Skipped),
i(Rest);
i([]) ->
ok.
hformat(A1, A2, A3, A4, A5, A6) ->
io:format("~-20s ~8s ~8s ~8s ~8s ~8s~n", [A1,A2,A3,A4,A5,A6]).
nformat(A1, A2, A3, A4, A5, A6) ->
io:format("~-20s ~8w ~8w ~8w ~8w ~8w~n", [A1,A2,A3,A4,A5,A6]).
Force load of a module even if it is in a sticky directory .
l(Mod) ->
case do_load(Mod) of
{error, sticky_directory} ->
Dir = filename:dirname(code:which(Mod)),
code:unstick_dir(Dir),
do_load(Mod),
code:stick_dir(Dir);
X ->
X
end.
ensure_ts_started(Opts) ->
Pid = case whereis(test_server_ctrl) of
undefined ->
test_server_ctrl:start();
P when is_pid(P) ->
P
end,
case Opts of
[{Cover,AppOrCoverFile}] when Cover==cover; Cover==cover_details ->
test_server_ctrl:cover(AppOrCoverFile,cover_type(Cover));
[{Cover,App,CoverFile}] when Cover==cover; Cover==cover_details ->
test_server_ctrl:cover(App,CoverFile,cover_type(Cover));
_ ->
ok
end,
Pid.
cover_type(cover) -> overview;
cover_type(cover_details) -> details.
do_load(Mod) ->
code:purge(Mod),
code:load_file(Mod).
|
012645fd00b8c2ed935ed120b32c8280e02f703d66267da90bdc4ce0b56b0fed | YoshikuniJujo/test_haskell | VulkanSamplerEnum.hs | # LANGUAGE QuasiQuotes #
# OPTiONS_GHC -Wall -fno - warn - tabs #
module VulkanSamplerEnum where
import Text.Nowdoc
import MakeEnum
make :: IO ()
make = createFile'' vulkanCore "Sampler.Enum" ["Data.Bits", "Data.Word"] [
( [("CreateFlagsZero", Int 0)],
( "CreateFlagBits", "VkSamplerCreateFlagBits",
["Show", "Eq", "Storable", "Bits"] ) ),
( [],
( "MipmapMode", "VkSamplerMipmapMode",
["Show", "Eq", "Storable", "Bits"] ) ),
( [],
( "AddressMode", "VkSamplerAddressMode",
["Show", "Eq", "Storable", "Bits"] ) )
]
[nowdoc|
type CreateFlags = CreateFlagBits|]
| null | https://raw.githubusercontent.com/YoshikuniJujo/test_haskell/6ea44c1048805a62979669c185ab32ba9f4d2e02/themes/gui/vulkan/try-vulkan-middle/tools/VulkanSamplerEnum.hs | haskell | # LANGUAGE QuasiQuotes #
# OPTiONS_GHC -Wall -fno - warn - tabs #
module VulkanSamplerEnum where
import Text.Nowdoc
import MakeEnum
make :: IO ()
make = createFile'' vulkanCore "Sampler.Enum" ["Data.Bits", "Data.Word"] [
( [("CreateFlagsZero", Int 0)],
( "CreateFlagBits", "VkSamplerCreateFlagBits",
["Show", "Eq", "Storable", "Bits"] ) ),
( [],
( "MipmapMode", "VkSamplerMipmapMode",
["Show", "Eq", "Storable", "Bits"] ) ),
( [],
( "AddressMode", "VkSamplerAddressMode",
["Show", "Eq", "Storable", "Bits"] ) )
]
[nowdoc|
type CreateFlags = CreateFlagBits|]
|
|
0dde1f71230eb01992e72a481bf25a335329dc4bdef1733e52ec7a97f2495a88 | racket/frtime | lang.rkt | #lang s-exp frtime/lang-utils
(provide value-nowable? behaviorof
(all-from-out frtime/lang-utils)
(except-out (all-from-out frtime/lang-ext) lift))
(require frtime/lang-ext)
(require (as-is:unchecked (except-in frtime/core/frp undefined undefined?) event-set? signal-value))
(define (value-nowable? x)
(or (not (signal? x))
(not (event-set? (signal-value x)))))
(define ((behaviorof pred) x)
(let ([v (value-now x)])
(or (undefined? v)
(pred v))))
| null | https://raw.githubusercontent.com/racket/frtime/9b9db67581107f4d7b995541c70f2d08f03ae89e/lang.rkt | racket | #lang s-exp frtime/lang-utils
(provide value-nowable? behaviorof
(all-from-out frtime/lang-utils)
(except-out (all-from-out frtime/lang-ext) lift))
(require frtime/lang-ext)
(require (as-is:unchecked (except-in frtime/core/frp undefined undefined?) event-set? signal-value))
(define (value-nowable? x)
(or (not (signal? x))
(not (event-set? (signal-value x)))))
(define ((behaviorof pred) x)
(let ([v (value-now x)])
(or (undefined? v)
(pred v))))
|
|
739b9219814a124cfa775166814122641623282f5a28c4bf64c002ac53d50829 | patricoferris/ocaml-multicore-monorepo | effect.compat.ml | include Stdlib.EffectHandlers
type 'a t = 'a eff = ..
| null | https://raw.githubusercontent.com/patricoferris/ocaml-multicore-monorepo/624b3293ee41e83736fe7ac3a79f810c2b70f68b/duniverse/eio/lib_eio/effect.compat.ml | ocaml | include Stdlib.EffectHandlers
type 'a t = 'a eff = ..
|
|
d034ce1b4f56333ba8046507db9a3cf46df326fbd2e0ab88bef3b9e5ed9dec13 | cbaggers/cepl | texture-samplers.lisp | (in-package :cepl.textures)
;; These only exist so the sampler objects can use them
they are neccesary in cases where the GL version is less that 3.3
;; In those cases proper sampler objects are not available and we have
;; to use our standins.
;;
;; We could allow using the methods below to set the sampling params on
;; the texture directly but this makes for a less consistant api with no
;; other benefit.
(defun+ (setf tex-lod-bias) (value texture)
(%with-scratch-texture-bound texture
(%gl:tex-parameter-f (texture-type texture) :texture-lod-bias value))
texture)
(defun+ (setf tex-min-lod) (value texture)
(%with-scratch-texture-bound texture
(%gl:tex-parameter-f (texture-type texture) :texture-min-lod value))
texture)
(defun+ (setf tex-max-lod) (value texture)
(%with-scratch-texture-bound texture
(%gl:tex-parameter-f (texture-type texture) :texture-max-lod value))
texture)
(defun+ (setf border-color) (value texture)
(cffi-sys:with-pointer-to-vector-data (ptr value)
#+sbcl(declare (sb-ext:muffle-conditions sb-ext:compiler-note))
(%with-scratch-texture-bound texture
(%gl:tex-parameter-fv (texture-type texture) :texture-border-color ptr)))
texture)
(defun+ (setf tex-magnify-filter) (value texture)
(assert (member value '(:linear :nearest)))
(%with-scratch-texture-bound texture
(%gl::tex-parameter-i (texture-type texture) :texture-mag-filter
(gl-enum value)))
texture)
(defun+ (setf tex-minify-filter) (value texture)
(%with-scratch-texture-bound texture
(%gl::tex-parameter-i (texture-type texture) :texture-min-filter
(gl-enum value)))
texture)
(defun+ (setf tex-wrap) (value texture)
(let ((options '(:repeat :mirrored-repeat :clamp-to-edge :clamp-to-border
:mirror-clamp-to-edge))
(value (if (keywordp value)
(vector value value value)
value)))
(assert (and (vectorp value)
(= (length value) 3)
(every (lambda (x) (member x options)) value)))
(%with-scratch-texture-bound texture
(%gl::tex-parameter-i (texture-type texture) :texture-wrap-s
(gl-enum (aref value 0)))
(%gl::tex-parameter-i (texture-type texture) :texture-wrap-t
(gl-enum (aref value 1)))
(%gl::tex-parameter-i (texture-type texture) :texture-wrap-r
(gl-enum (aref value 2)))))
texture)
(defun+ (setf tex-compare) (value texture)
(%with-scratch-texture-bound texture
(if value
(progn
(%gl:tex-parameter-i
(texture-type texture) :texture-compare-mode
(gl-enum :compare-ref-to-texture))
(%gl:tex-parameter-i
(texture-type texture) :texture-compare-func
(gl-enum
(case value
((:never nil) :never)
((:always t) :always)
((:equal := =) :equal)
((:not-equal :/= /=) :not-equal)
((:less :< <) :less)
((:greater :> >) :greater)
((:lequal :<= <=) :lequal)
((:gequal :>= >=) :gequal)
(otherwise (error "Invalid compare func for texture ~a" value))))))
(%gl:tex-parameter-i
(texture-type texture) :texture-compare-mode
(gl-enum :none))))
texture)
(defun+ fallback-sampler-set (sampler)
(let ((texture (%sampler-texture sampler))
(id (%sampler-id sampler)))
(unless (= id (texture-last-sampler-id texture))
(setf (tex-lod-bias texture) (%sampler-lod-bias sampler)
(tex-min-lod texture) (%sampler-min-lod sampler)
(tex-max-lod texture) (%sampler-max-lod sampler)
(tex-minify-filter texture) (%sampler-minify-filter sampler)
(tex-magnify-filter texture) (%sampler-magnify-filter sampler)
(tex-wrap texture) (%sampler-wrap sampler)
(border-color texture) (%sampler-border-color sampler)
(tex-compare texture) (%sampler-compare sampler)))
sampler))
| null | https://raw.githubusercontent.com/cbaggers/cepl/d1a10b6c8f4cedc07493bf06aef3a56c7b6f8d5b/core/textures/texture-samplers.lisp | lisp | These only exist so the sampler objects can use them
In those cases proper sampler objects are not available and we have
to use our standins.
We could allow using the methods below to set the sampling params on
the texture directly but this makes for a less consistant api with no
other benefit. | (in-package :cepl.textures)
they are neccesary in cases where the GL version is less that 3.3
(defun+ (setf tex-lod-bias) (value texture)
(%with-scratch-texture-bound texture
(%gl:tex-parameter-f (texture-type texture) :texture-lod-bias value))
texture)
(defun+ (setf tex-min-lod) (value texture)
(%with-scratch-texture-bound texture
(%gl:tex-parameter-f (texture-type texture) :texture-min-lod value))
texture)
(defun+ (setf tex-max-lod) (value texture)
(%with-scratch-texture-bound texture
(%gl:tex-parameter-f (texture-type texture) :texture-max-lod value))
texture)
(defun+ (setf border-color) (value texture)
(cffi-sys:with-pointer-to-vector-data (ptr value)
#+sbcl(declare (sb-ext:muffle-conditions sb-ext:compiler-note))
(%with-scratch-texture-bound texture
(%gl:tex-parameter-fv (texture-type texture) :texture-border-color ptr)))
texture)
(defun+ (setf tex-magnify-filter) (value texture)
(assert (member value '(:linear :nearest)))
(%with-scratch-texture-bound texture
(%gl::tex-parameter-i (texture-type texture) :texture-mag-filter
(gl-enum value)))
texture)
(defun+ (setf tex-minify-filter) (value texture)
(%with-scratch-texture-bound texture
(%gl::tex-parameter-i (texture-type texture) :texture-min-filter
(gl-enum value)))
texture)
(defun+ (setf tex-wrap) (value texture)
(let ((options '(:repeat :mirrored-repeat :clamp-to-edge :clamp-to-border
:mirror-clamp-to-edge))
(value (if (keywordp value)
(vector value value value)
value)))
(assert (and (vectorp value)
(= (length value) 3)
(every (lambda (x) (member x options)) value)))
(%with-scratch-texture-bound texture
(%gl::tex-parameter-i (texture-type texture) :texture-wrap-s
(gl-enum (aref value 0)))
(%gl::tex-parameter-i (texture-type texture) :texture-wrap-t
(gl-enum (aref value 1)))
(%gl::tex-parameter-i (texture-type texture) :texture-wrap-r
(gl-enum (aref value 2)))))
texture)
(defun+ (setf tex-compare) (value texture)
(%with-scratch-texture-bound texture
(if value
(progn
(%gl:tex-parameter-i
(texture-type texture) :texture-compare-mode
(gl-enum :compare-ref-to-texture))
(%gl:tex-parameter-i
(texture-type texture) :texture-compare-func
(gl-enum
(case value
((:never nil) :never)
((:always t) :always)
((:equal := =) :equal)
((:not-equal :/= /=) :not-equal)
((:less :< <) :less)
((:greater :> >) :greater)
((:lequal :<= <=) :lequal)
((:gequal :>= >=) :gequal)
(otherwise (error "Invalid compare func for texture ~a" value))))))
(%gl:tex-parameter-i
(texture-type texture) :texture-compare-mode
(gl-enum :none))))
texture)
(defun+ fallback-sampler-set (sampler)
(let ((texture (%sampler-texture sampler))
(id (%sampler-id sampler)))
(unless (= id (texture-last-sampler-id texture))
(setf (tex-lod-bias texture) (%sampler-lod-bias sampler)
(tex-min-lod texture) (%sampler-min-lod sampler)
(tex-max-lod texture) (%sampler-max-lod sampler)
(tex-minify-filter texture) (%sampler-minify-filter sampler)
(tex-magnify-filter texture) (%sampler-magnify-filter sampler)
(tex-wrap texture) (%sampler-wrap sampler)
(border-color texture) (%sampler-border-color sampler)
(tex-compare texture) (%sampler-compare sampler)))
sampler))
|
4cd6ef1202b4f650b4bd8b30d47f198335cd4c2dde6cdb2867d89379ce1a6554 | arenadotio/pgx | pgx_async.ml | open Core_kernel
open Async_kernel
open Async_unix
Pgx allows to generate bindings from any module implementing their
THREAD signature which encompasses monadic concurrency + IO . The
implementation that we 've chosen here is a deferred represents an
asynchronous value returned by pgx and Writer.t / Reader.t are the
channels it uses for communication
THREAD signature which encompasses monadic concurrency + IO. The
implementation that we've chosen here is a deferred represents an
asynchronous value returned by pgx and Writer.t/Reader.t are the
channels it uses for communication *)
exception Pgx_eof [@@deriving sexp]
module Thread = struct
type 'a t = 'a Deferred.t
let return = return
let ( >>= ) = ( >>= )
let catch f on_exn =
try_with ~extract_exn:true f
>>= function
| Ok x -> return x
| Error exn -> on_exn exn
;;
type sockaddr =
| Unix of string
| Inet of string * int
type in_channel = Reader.t
type out_channel = Writer.t
let output_char w char = return (Writer.write_char w char)
let output_string w s = return (Writer.write w s)
let output_binary_int w n =
let chr = Caml.Char.chr in
Writer.write_char w (chr (n lsr 24));
Writer.write_char w (chr ((n lsr 16) land 255));
Writer.write_char w (chr ((n lsr 8) land 255));
return @@ Writer.write_char w (chr (n land 255))
;;
let flush = Writer.flushed
let input_char r =
Reader.read_char r
>>| function
| `Ok c -> c
| `Eof -> raise Pgx_eof
;;
let input_binary_int r =
let b = Bytes.create 4 in
Reader.really_read r b
>>| function
| `Eof _ -> raise Pgx_eof
| `Ok ->
let code = Caml.Char.code in
(code (Bytes.get b 0) lsl 24)
lor (code (Bytes.get b 1) lsl 16)
lor (code (Bytes.get b 2) lsl 8)
lor code (Bytes.get b 3)
;;
let really_input r s pos len =
Reader.really_read r ~pos ~len s
>>| function
| `Ok -> ()
| `Eof _ -> raise Pgx_eof
;;
let close_in = Reader.close
let open_connection sockaddr =
match sockaddr with
| Unix path -> Conduit_async.connect (`Unix_domain_socket path)
| Inet (host, port) ->
Uri.make ~host ~port ()
|> Conduit_async.V3.resolve_uri
>>= Conduit_async.V3.connect
>>| fun (_socket, in_channel, out_channel) -> in_channel, out_channel
;;
type ssl_config = Conduit_async.Ssl.config
let upgrade_ssl =
try
let default_config = Conduit_async.V1.Conduit_async_ssl.Ssl_config.configure () in
`Supported
(fun ?(ssl_config = default_config) in_channel out_channel ->
Conduit_async.V1.Conduit_async_ssl.ssl_connect ssl_config in_channel out_channel)
with
| _ -> `Not_supported
;;
(* The unix getlogin syscall can fail *)
let getlogin () = Unix.getuid () |> Unix.Passwd.getbyuid_exn >>| fun { name; _ } -> name
let debug msg =
Log.Global.debug ~tags:[ "lib", "pgx_async" ] "%s" msg;
Log.Global.flushed ()
;;
let protect f ~finally = Monitor.protect f ~finally
module Sequencer = struct
type 'a monad = 'a t
type 'a t = 'a Sequencer.t
let create t = Sequencer.create ~continue_on_error:true t
let enqueue = Throttle.enqueue
end
end
include Pgx.Make (Thread)
pgx uses configures this value at build time . But this breaks when
pgx is installed before postgres itself . We prefer to set this variable
at runtime and override the ` connect ` function from to respect it
pgx is installed before postgres itself. We prefer to set this variable
at runtime and override the `connect` function from to respect it *)
let default_unix_domain_socket_dir =
let debian_default = "/var/run/postgresql" in
Lazy_deferred.create (fun () ->
Sys.is_directory debian_default
>>| function
| `Yes -> debian_default
| `No | `Unknown -> "/tmp")
;;
(* Fail if PGDATABASE environment variable is not set. *)
let check_pgdatabase =
lazy
(let db = "PGDATABASE" in
if Option.is_none (Sys.getenv db)
then failwithf "%s environment variable must be set." db ())
;;
let connect
?ssl
?host
?port
?user
?password
?database
?unix_domain_socket_dir
?verbose
?max_message_length
()
=
if Option.is_none database then Lazy.force check_pgdatabase;
(match unix_domain_socket_dir with
| Some p -> return p
| None -> Lazy_deferred.force_exn default_unix_domain_socket_dir)
>>= fun unix_domain_socket_dir ->
connect
?ssl
?host
?port
?user
?password
?database
?verbose
?max_message_length
~unix_domain_socket_dir
()
;;
let with_conn
?ssl
?host
?port
?user
?password
?database
?unix_domain_socket_dir
?verbose
?max_message_length
f
=
connect
?ssl
?host
?port
?user
?password
?database
?unix_domain_socket_dir
?verbose
?max_message_length
()
>>= fun dbh -> Monitor.protect (fun () -> f dbh) ~finally:(fun () -> close dbh)
;;
let execute_pipe ?params db query =
Pipe.create_reader ~close_on_exception:false
@@ fun writer ->
execute_iter ?params db query ~f:(fun row -> Pipe.write_if_open writer row)
;;
module Value = Pgx_value_core
| null | https://raw.githubusercontent.com/arenadotio/pgx/cdef3ff4eba56ea9b2a74c2b3bbfe652b4864a39/pgx_async/src/pgx_async.ml | ocaml | The unix getlogin syscall can fail
Fail if PGDATABASE environment variable is not set. | open Core_kernel
open Async_kernel
open Async_unix
Pgx allows to generate bindings from any module implementing their
THREAD signature which encompasses monadic concurrency + IO . The
implementation that we 've chosen here is a deferred represents an
asynchronous value returned by pgx and Writer.t / Reader.t are the
channels it uses for communication
THREAD signature which encompasses monadic concurrency + IO. The
implementation that we've chosen here is a deferred represents an
asynchronous value returned by pgx and Writer.t/Reader.t are the
channels it uses for communication *)
exception Pgx_eof [@@deriving sexp]
module Thread = struct
type 'a t = 'a Deferred.t
let return = return
let ( >>= ) = ( >>= )
let catch f on_exn =
try_with ~extract_exn:true f
>>= function
| Ok x -> return x
| Error exn -> on_exn exn
;;
type sockaddr =
| Unix of string
| Inet of string * int
type in_channel = Reader.t
type out_channel = Writer.t
let output_char w char = return (Writer.write_char w char)
let output_string w s = return (Writer.write w s)
let output_binary_int w n =
let chr = Caml.Char.chr in
Writer.write_char w (chr (n lsr 24));
Writer.write_char w (chr ((n lsr 16) land 255));
Writer.write_char w (chr ((n lsr 8) land 255));
return @@ Writer.write_char w (chr (n land 255))
;;
let flush = Writer.flushed
let input_char r =
Reader.read_char r
>>| function
| `Ok c -> c
| `Eof -> raise Pgx_eof
;;
let input_binary_int r =
let b = Bytes.create 4 in
Reader.really_read r b
>>| function
| `Eof _ -> raise Pgx_eof
| `Ok ->
let code = Caml.Char.code in
(code (Bytes.get b 0) lsl 24)
lor (code (Bytes.get b 1) lsl 16)
lor (code (Bytes.get b 2) lsl 8)
lor code (Bytes.get b 3)
;;
let really_input r s pos len =
Reader.really_read r ~pos ~len s
>>| function
| `Ok -> ()
| `Eof _ -> raise Pgx_eof
;;
let close_in = Reader.close
let open_connection sockaddr =
match sockaddr with
| Unix path -> Conduit_async.connect (`Unix_domain_socket path)
| Inet (host, port) ->
Uri.make ~host ~port ()
|> Conduit_async.V3.resolve_uri
>>= Conduit_async.V3.connect
>>| fun (_socket, in_channel, out_channel) -> in_channel, out_channel
;;
type ssl_config = Conduit_async.Ssl.config
let upgrade_ssl =
try
let default_config = Conduit_async.V1.Conduit_async_ssl.Ssl_config.configure () in
`Supported
(fun ?(ssl_config = default_config) in_channel out_channel ->
Conduit_async.V1.Conduit_async_ssl.ssl_connect ssl_config in_channel out_channel)
with
| _ -> `Not_supported
;;
let getlogin () = Unix.getuid () |> Unix.Passwd.getbyuid_exn >>| fun { name; _ } -> name
let debug msg =
Log.Global.debug ~tags:[ "lib", "pgx_async" ] "%s" msg;
Log.Global.flushed ()
;;
let protect f ~finally = Monitor.protect f ~finally
module Sequencer = struct
type 'a monad = 'a t
type 'a t = 'a Sequencer.t
let create t = Sequencer.create ~continue_on_error:true t
let enqueue = Throttle.enqueue
end
end
include Pgx.Make (Thread)
pgx uses configures this value at build time . But this breaks when
pgx is installed before postgres itself . We prefer to set this variable
at runtime and override the ` connect ` function from to respect it
pgx is installed before postgres itself. We prefer to set this variable
at runtime and override the `connect` function from to respect it *)
let default_unix_domain_socket_dir =
let debian_default = "/var/run/postgresql" in
Lazy_deferred.create (fun () ->
Sys.is_directory debian_default
>>| function
| `Yes -> debian_default
| `No | `Unknown -> "/tmp")
;;
let check_pgdatabase =
lazy
(let db = "PGDATABASE" in
if Option.is_none (Sys.getenv db)
then failwithf "%s environment variable must be set." db ())
;;
let connect
?ssl
?host
?port
?user
?password
?database
?unix_domain_socket_dir
?verbose
?max_message_length
()
=
if Option.is_none database then Lazy.force check_pgdatabase;
(match unix_domain_socket_dir with
| Some p -> return p
| None -> Lazy_deferred.force_exn default_unix_domain_socket_dir)
>>= fun unix_domain_socket_dir ->
connect
?ssl
?host
?port
?user
?password
?database
?verbose
?max_message_length
~unix_domain_socket_dir
()
;;
let with_conn
?ssl
?host
?port
?user
?password
?database
?unix_domain_socket_dir
?verbose
?max_message_length
f
=
connect
?ssl
?host
?port
?user
?password
?database
?unix_domain_socket_dir
?verbose
?max_message_length
()
>>= fun dbh -> Monitor.protect (fun () -> f dbh) ~finally:(fun () -> close dbh)
;;
let execute_pipe ?params db query =
Pipe.create_reader ~close_on_exception:false
@@ fun writer ->
execute_iter ?params db query ~f:(fun row -> Pipe.write_if_open writer row)
;;
module Value = Pgx_value_core
|
373cff30143ceab2e225c80f9fed5a325fb643e4a061020f1a8fb985faed3a60 | fukamachi/clozure-cl | l0-aprims.lisp | -*- Mode : Lisp ; Package : CCL -*-
;;;
Copyright ( C ) 2009 Clozure Associates
Copyright ( C ) 1994 - 2001 Digitool , Inc
This file is part of Clozure CL .
;;;
Clozure CL is licensed under the terms of the Lisp Lesser GNU Public
License , known as the LLGPL and distributed with Clozure CL as the
;;; file "LICENSE". The LLGPL consists of a preamble and the LGPL,
which is distributed with Clozure CL as the file " LGPL " . Where these
;;; conflict, the preamble takes precedence.
;;;
;;; Clozure CL is referenced in the preamble as the "LIBRARY."
;;;
;;; The LLGPL is also available online at
;;;
(in-package "CCL")
; l0-aprims.lisp
;;; This weak list is used to track semaphores as well as locks.
(defvar %system-locks% nil)
(defun record-system-lock (l)
(atomic-push-uvector-cell %system-locks% population.data l)
l)
;;; This has to run very early in the initial thread.
(defun %revive-system-locks ()
(dolist (s (population-data %system-locks%))
(%revive-macptr s)
(%setf-macptr s
(case (uvref s target::xmacptr.flags-cell)
(#.$flags_DisposeRecursiveLock
(ff-call
(%kernel-import target::kernel-import-new-recursive-lock)
:address))
(#.$flags_DisposeRwlock
(ff-call
(%kernel-import target::kernel-import-rwlock-new)
:address))
(#.$flags_DisposeSemaphore
(ff-call
(%kernel-import target::kernel-import-new-semaphore)
:signed-fullword 0
:address))))
(set-%gcable-macptrs% s)))
(dolist (p %all-packages%)
(setf (pkg.lock p) (make-read-write-lock)))
(defparameter %all-packages-lock% nil)
(defun %cstr-pointer (string pointer &optional (nul-terminated t))
(if (typep string 'simple-base-string)
(locally (declare (simple-base-string string)
(optimize (speed 3) (safety 0)))
(let* ((n (length string)))
(declare (fixnum n))
(dotimes (i n)
(setf (%get-unsigned-byte pointer i)
(let* ((code (%scharcode string i)))
(declare (type (mod #x110000) code))
(if (< code 256)
code
(char-code #\Sub)))))
(when nul-terminated
(setf (%get-byte pointer n) 0)))
nil)
(%cstr-segment-pointer string pointer 0 (length string) nul-terminated)))
(defun %cstr-segment-pointer (string pointer start end &optional (nul-terminated t))
(declare (fixnum start end))
(let* ((n (- end start)))
(multiple-value-bind (s o) (dereference-base-string string)
(declare (fixnum o))
(do* ((i 0 (1+ i))
(o (the fixnum (+ o start)) (1+ o)))
((= i n))
(declare (fixnum i o))
(setf (%get-unsigned-byte pointer i)
(let* ((code (char-code (schar s o))))
(declare (type (mod #x110000) code))
(if (< code 256)
code
(char-code #\Sub))))))
(when nul-terminated
(setf (%get-byte pointer n) 0))
nil))
(defun string (thing)
"Coerces X into a string. If X is a string, X is returned. If X is a
symbol, X's pname is returned. If X is a character then a one element
string containing that character is returned. If X cannot be coerced
into a string, an error occurs."
(etypecase thing
(string thing)
(symbol (symbol-name thing))
(character
(let* ((s (make-string 1)))
(setf (schar s 0) thing)
s))))
(defun dereference-base-string (s)
(multiple-value-bind (vector offset) (array-data-and-offset s)
(unless (typep vector 'simple-base-string) (report-bad-arg s 'base-string))
(values vector offset (length s))))
(defun make-gcable-macptr (flags)
(let ((v (%alloc-misc target::xmacptr.element-count target::subtag-macptr)))
(setf (uvref v target::xmacptr.address-cell) 0) ; ?? yup.
(setf (uvref v target::xmacptr.flags-cell) flags)
(set-%gcable-macptrs% v)
v))
(defun %make-recursive-lock-ptr ()
(record-system-lock
(%setf-macptr
(make-gcable-macptr $flags_DisposeRecursiveLock)
(ff-call (%kernel-import target::kernel-import-new-recursive-lock)
:address))))
(defun %make-rwlock-ptr ()
(record-system-lock
(%setf-macptr
(make-gcable-macptr $flags_DisposeRwLock)
(ff-call (%kernel-import target::kernel-import-rwlock-new)
:address))))
(defun make-recursive-lock ()
(make-lock nil))
(defun %make-lock (pointer name)
(gvector :lock pointer 'recursive-lock 0 name nil nil))
(defun make-lock (&optional name)
"Create and return a lock object, which can be used for synchronization
between threads."
(%make-lock (%make-recursive-lock-ptr) name))
(defun lock-name (lock)
(uvref (require-type lock 'lock) target::lock.name-cell))
(defun recursive-lock-ptr (r)
(if (and (eq target::subtag-lock (typecode r))
(eq (%svref r target::lock.kind-cell) 'recursive-lock))
(%svref r target::lock._value-cell)
(report-bad-arg r 'recursive-lock)))
(defun recursive-lock-whostate (r)
(if (and (eq target::subtag-lock (typecode r))
(eq (%svref r target::lock.kind-cell) 'recursive-lock))
(or (%svref r target::lock.whostate-cell)
(setf (%svref r target::lock.whostate-cell)
(%lock-whostate-string "Lock wait" r)))
(if (typep r 'string)
r
(report-bad-arg r 'recursive-lock))))
(defun read-write-lock-ptr (rw)
(if (and (eq target::subtag-lock (typecode rw))
(eq (%svref rw target::lock.kind-cell) 'read-write-lock))
(%svref rw target::lock._value-cell)
(report-bad-arg rw 'read-write-lock)))
(defun make-read-write-lock ()
"Create and return a read-write lock, which can be used for
synchronization between threads."
(gvector :lock (%make-rwlock-ptr) 'read-write-lock 0 nil nil nil))
(defun rwlock-read-whostate (rw)
(if (and (eq target::subtag-lock (typecode rw))
(eq (%svref rw target::lock.kind-cell) 'read-write-lock))
(or (%svref rw target::lock.whostate-cell)
(setf (%svref rw target::lock.whostate-cell)
(%lock-whostate-string "Read lock wait" rw)))
(report-bad-arg rw 'read-write-lock)))
(defun rwlock-write-whostate (rw)
(if (and (eq target::subtag-lock (typecode rw))
(eq (%svref rw target::lock.kind-cell) 'read-write-lock))
(or (%svref rw target::lock.whostate-2-cell)
(setf (%svref rw target::lock.whostate-2-cell)
(%lock-whostate-string "Write lock wait" rw)))
(report-bad-arg rw 'read-write-lock)))
(defun %make-semaphore-ptr ()
(let* ((p (ff-call (%kernel-import target::kernel-import-new-semaphore)
:signed-fullword 0
:address)))
(if (%null-ptr-p p)
(error "Can't create semaphore.")
(record-system-lock
(%setf-macptr
(make-gcable-macptr $flags_DisposeSemaphore)
p)))))
(defun make-semaphore ()
"Create and return a semaphore, which can be used for synchronization
between threads."
(%istruct 'semaphore (%make-semaphore-ptr)))
(defun semaphorep (x)
(istruct-typep x 'semaphore))
(setf (type-predicate 'semaphore) 'semaphorep)
(defun make-list (size &key initial-element)
"Constructs a list with size elements each set to value"
(unless (and (typep size 'fixnum)
(>= (the fixnum size) 0))
(report-bad-arg size '(and fixnum unsigned-byte)))
(locally (declare (fixnum size))
(if (>= size (ash 1 16))
(values (%allocate-list initial-element size))
(do* ((result '() (cons initial-element result)))
((zerop size) result)
(decf size)))))
; end
| null | https://raw.githubusercontent.com/fukamachi/clozure-cl/4b0c69452386ae57b08984ed815d9b50b4bcc8a2/level-0/l0-aprims.lisp | lisp | Package : CCL -*-
file "LICENSE". The LLGPL consists of a preamble and the LGPL,
conflict, the preamble takes precedence.
Clozure CL is referenced in the preamble as the "LIBRARY."
The LLGPL is also available online at
l0-aprims.lisp
This weak list is used to track semaphores as well as locks.
This has to run very early in the initial thread.
?? yup.
end | Copyright ( C ) 2009 Clozure Associates
Copyright ( C ) 1994 - 2001 Digitool , Inc
This file is part of Clozure CL .
Clozure CL is licensed under the terms of the Lisp Lesser GNU Public
License , known as the LLGPL and distributed with Clozure CL as the
which is distributed with Clozure CL as the file " LGPL " . Where these
(in-package "CCL")
(defvar %system-locks% nil)
(defun record-system-lock (l)
(atomic-push-uvector-cell %system-locks% population.data l)
l)
(defun %revive-system-locks ()
(dolist (s (population-data %system-locks%))
(%revive-macptr s)
(%setf-macptr s
(case (uvref s target::xmacptr.flags-cell)
(#.$flags_DisposeRecursiveLock
(ff-call
(%kernel-import target::kernel-import-new-recursive-lock)
:address))
(#.$flags_DisposeRwlock
(ff-call
(%kernel-import target::kernel-import-rwlock-new)
:address))
(#.$flags_DisposeSemaphore
(ff-call
(%kernel-import target::kernel-import-new-semaphore)
:signed-fullword 0
:address))))
(set-%gcable-macptrs% s)))
(dolist (p %all-packages%)
(setf (pkg.lock p) (make-read-write-lock)))
(defparameter %all-packages-lock% nil)
(defun %cstr-pointer (string pointer &optional (nul-terminated t))
(if (typep string 'simple-base-string)
(locally (declare (simple-base-string string)
(optimize (speed 3) (safety 0)))
(let* ((n (length string)))
(declare (fixnum n))
(dotimes (i n)
(setf (%get-unsigned-byte pointer i)
(let* ((code (%scharcode string i)))
(declare (type (mod #x110000) code))
(if (< code 256)
code
(char-code #\Sub)))))
(when nul-terminated
(setf (%get-byte pointer n) 0)))
nil)
(%cstr-segment-pointer string pointer 0 (length string) nul-terminated)))
(defun %cstr-segment-pointer (string pointer start end &optional (nul-terminated t))
(declare (fixnum start end))
(let* ((n (- end start)))
(multiple-value-bind (s o) (dereference-base-string string)
(declare (fixnum o))
(do* ((i 0 (1+ i))
(o (the fixnum (+ o start)) (1+ o)))
((= i n))
(declare (fixnum i o))
(setf (%get-unsigned-byte pointer i)
(let* ((code (char-code (schar s o))))
(declare (type (mod #x110000) code))
(if (< code 256)
code
(char-code #\Sub))))))
(when nul-terminated
(setf (%get-byte pointer n) 0))
nil))
(defun string (thing)
"Coerces X into a string. If X is a string, X is returned. If X is a
symbol, X's pname is returned. If X is a character then a one element
string containing that character is returned. If X cannot be coerced
into a string, an error occurs."
(etypecase thing
(string thing)
(symbol (symbol-name thing))
(character
(let* ((s (make-string 1)))
(setf (schar s 0) thing)
s))))
(defun dereference-base-string (s)
(multiple-value-bind (vector offset) (array-data-and-offset s)
(unless (typep vector 'simple-base-string) (report-bad-arg s 'base-string))
(values vector offset (length s))))
(defun make-gcable-macptr (flags)
(let ((v (%alloc-misc target::xmacptr.element-count target::subtag-macptr)))
(setf (uvref v target::xmacptr.flags-cell) flags)
(set-%gcable-macptrs% v)
v))
(defun %make-recursive-lock-ptr ()
(record-system-lock
(%setf-macptr
(make-gcable-macptr $flags_DisposeRecursiveLock)
(ff-call (%kernel-import target::kernel-import-new-recursive-lock)
:address))))
(defun %make-rwlock-ptr ()
(record-system-lock
(%setf-macptr
(make-gcable-macptr $flags_DisposeRwLock)
(ff-call (%kernel-import target::kernel-import-rwlock-new)
:address))))
(defun make-recursive-lock ()
(make-lock nil))
(defun %make-lock (pointer name)
(gvector :lock pointer 'recursive-lock 0 name nil nil))
(defun make-lock (&optional name)
"Create and return a lock object, which can be used for synchronization
between threads."
(%make-lock (%make-recursive-lock-ptr) name))
(defun lock-name (lock)
(uvref (require-type lock 'lock) target::lock.name-cell))
(defun recursive-lock-ptr (r)
(if (and (eq target::subtag-lock (typecode r))
(eq (%svref r target::lock.kind-cell) 'recursive-lock))
(%svref r target::lock._value-cell)
(report-bad-arg r 'recursive-lock)))
(defun recursive-lock-whostate (r)
(if (and (eq target::subtag-lock (typecode r))
(eq (%svref r target::lock.kind-cell) 'recursive-lock))
(or (%svref r target::lock.whostate-cell)
(setf (%svref r target::lock.whostate-cell)
(%lock-whostate-string "Lock wait" r)))
(if (typep r 'string)
r
(report-bad-arg r 'recursive-lock))))
(defun read-write-lock-ptr (rw)
(if (and (eq target::subtag-lock (typecode rw))
(eq (%svref rw target::lock.kind-cell) 'read-write-lock))
(%svref rw target::lock._value-cell)
(report-bad-arg rw 'read-write-lock)))
(defun make-read-write-lock ()
"Create and return a read-write lock, which can be used for
synchronization between threads."
(gvector :lock (%make-rwlock-ptr) 'read-write-lock 0 nil nil nil))
(defun rwlock-read-whostate (rw)
(if (and (eq target::subtag-lock (typecode rw))
(eq (%svref rw target::lock.kind-cell) 'read-write-lock))
(or (%svref rw target::lock.whostate-cell)
(setf (%svref rw target::lock.whostate-cell)
(%lock-whostate-string "Read lock wait" rw)))
(report-bad-arg rw 'read-write-lock)))
(defun rwlock-write-whostate (rw)
(if (and (eq target::subtag-lock (typecode rw))
(eq (%svref rw target::lock.kind-cell) 'read-write-lock))
(or (%svref rw target::lock.whostate-2-cell)
(setf (%svref rw target::lock.whostate-2-cell)
(%lock-whostate-string "Write lock wait" rw)))
(report-bad-arg rw 'read-write-lock)))
(defun %make-semaphore-ptr ()
(let* ((p (ff-call (%kernel-import target::kernel-import-new-semaphore)
:signed-fullword 0
:address)))
(if (%null-ptr-p p)
(error "Can't create semaphore.")
(record-system-lock
(%setf-macptr
(make-gcable-macptr $flags_DisposeSemaphore)
p)))))
(defun make-semaphore ()
"Create and return a semaphore, which can be used for synchronization
between threads."
(%istruct 'semaphore (%make-semaphore-ptr)))
(defun semaphorep (x)
(istruct-typep x 'semaphore))
(setf (type-predicate 'semaphore) 'semaphorep)
(defun make-list (size &key initial-element)
"Constructs a list with size elements each set to value"
(unless (and (typep size 'fixnum)
(>= (the fixnum size) 0))
(report-bad-arg size '(and fixnum unsigned-byte)))
(locally (declare (fixnum size))
(if (>= size (ash 1 16))
(values (%allocate-list initial-element size))
(do* ((result '() (cons initial-element result)))
((zerop size) result)
(decf size)))))
|
12b6fc8ec0bca3066190e4dc46d65aa3834588939b21908e05adac522f559228 | ghcjs/ghcjs-dom | HTMLFrameSetElement.hs | # LANGUAGE PatternSynonyms #
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
module GHCJS.DOM.JSFFI.Generated.HTMLFrameSetElement
(js_setCols, setCols, js_getCols, getCols, js_setRows, setRows,
js_getRows, getRows, blur, error, focus, focusin, focusout, load,
resize, scroll, webKitWillRevealBottom, webKitWillRevealLeft,
webKitWillRevealRight, webKitWillRevealTop,
HTMLFrameSetElement(..), gTypeHTMLFrameSetElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import qualified Prelude (error)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull, jsUndefined)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import Data.Maybe (fromJust)
import Data.Traversable (mapM)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"cols\"] = $2;" js_setCols ::
HTMLFrameSetElement -> JSString -> IO ()
-- | <-US/docs/Web/API/HTMLFrameSetElement.cols Mozilla HTMLFrameSetElement.cols documentation>
setCols ::
(MonadIO m, ToJSString val) => HTMLFrameSetElement -> val -> m ()
setCols self val = liftIO (js_setCols self (toJSString val))
foreign import javascript unsafe "$1[\"cols\"]" js_getCols ::
HTMLFrameSetElement -> IO JSString
-- | <-US/docs/Web/API/HTMLFrameSetElement.cols Mozilla HTMLFrameSetElement.cols documentation>
getCols ::
(MonadIO m, FromJSString result) => HTMLFrameSetElement -> m result
getCols self = liftIO (fromJSString <$> (js_getCols self))
foreign import javascript unsafe "$1[\"rows\"] = $2;" js_setRows ::
HTMLFrameSetElement -> JSString -> IO ()
| < -US/docs/Web/API/HTMLFrameSetElement.rows Mozilla HTMLFrameSetElement.rows documentation >
setRows ::
(MonadIO m, ToJSString val) => HTMLFrameSetElement -> val -> m ()
setRows self val = liftIO (js_setRows self (toJSString val))
foreign import javascript unsafe "$1[\"rows\"]" js_getRows ::
HTMLFrameSetElement -> IO JSString
| < -US/docs/Web/API/HTMLFrameSetElement.rows Mozilla HTMLFrameSetElement.rows documentation >
getRows ::
(MonadIO m, FromJSString result) => HTMLFrameSetElement -> m result
getRows self = liftIO (fromJSString <$> (js_getRows self))
| < -US/docs/Web/API/HTMLFrameSetElement.onblur Mozilla HTMLFrameSetElement.onblur documentation >
blur :: EventName HTMLFrameSetElement FocusEvent
blur = unsafeEventNameAsync (toJSString "blur")
| < -US/docs/Web/API/HTMLFrameSetElement.onerror Mozilla HTMLFrameSetElement.onerror documentation >
error :: EventName HTMLFrameSetElement UIEvent
error = unsafeEventNameAsync (toJSString "error")
| < -US/docs/Web/API/HTMLFrameSetElement.onfocus Mozilla HTMLFrameSetElement.onfocus documentation >
focus :: EventName HTMLFrameSetElement FocusEvent
focus = unsafeEventNameAsync (toJSString "focus")
| < -US/docs/Web/API/HTMLFrameSetElement.onfocusin Mozilla HTMLFrameSetElement.onfocusin documentation >
focusin :: EventName HTMLFrameSetElement onfocusin
focusin = unsafeEventName (toJSString "focusin")
-- | <-US/docs/Web/API/HTMLFrameSetElement.onfocusout Mozilla HTMLFrameSetElement.onfocusout documentation>
focusout :: EventName HTMLFrameSetElement onfocusout
focusout = unsafeEventName (toJSString "focusout")
| < -US/docs/Web/API/HTMLFrameSetElement.onload Mozilla HTMLFrameSetElement.onload documentation >
load :: EventName HTMLFrameSetElement UIEvent
load = unsafeEventNameAsync (toJSString "load")
-- | <-US/docs/Web/API/HTMLFrameSetElement.onresize Mozilla HTMLFrameSetElement.onresize documentation>
resize :: EventName HTMLFrameSetElement UIEvent
resize = unsafeEventName (toJSString "resize")
-- | <-US/docs/Web/API/HTMLFrameSetElement.onscroll Mozilla HTMLFrameSetElement.onscroll documentation>
scroll :: EventName HTMLFrameSetElement UIEvent
scroll = unsafeEventName (toJSString "scroll")
| < -US/docs/Web/API/HTMLFrameSetElement.onwebkitwillrevealbottom Mozilla HTMLFrameSetElement.onwebkitwillrevealbottom documentation >
webKitWillRevealBottom :: EventName HTMLFrameSetElement Event
webKitWillRevealBottom
= unsafeEventName (toJSString "webkitwillrevealbottom")
| < -US/docs/Web/API/HTMLFrameSetElement.onwebkitwillrevealleft Mozilla HTMLFrameSetElement.onwebkitwillrevealleft documentation >
webKitWillRevealLeft :: EventName HTMLFrameSetElement Event
webKitWillRevealLeft
= unsafeEventName (toJSString "webkitwillrevealleft")
| < -US/docs/Web/API/HTMLFrameSetElement.onwebkitwillrevealright Mozilla documentation >
webKitWillRevealRight :: EventName HTMLFrameSetElement Event
webKitWillRevealRight
= unsafeEventName (toJSString "webkitwillrevealright")
| < -US/docs/Web/API/HTMLFrameSetElement.onwebkitwillrevealtop Mozilla HTMLFrameSetElement.onwebkitwillrevealtop documentation >
webKitWillRevealTop :: EventName HTMLFrameSetElement Event
webKitWillRevealTop
= unsafeEventName (toJSString "webkitwillrevealtop") | null | https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/HTMLFrameSetElement.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
| <-US/docs/Web/API/HTMLFrameSetElement.cols Mozilla HTMLFrameSetElement.cols documentation>
| <-US/docs/Web/API/HTMLFrameSetElement.cols Mozilla HTMLFrameSetElement.cols documentation>
| <-US/docs/Web/API/HTMLFrameSetElement.onfocusout Mozilla HTMLFrameSetElement.onfocusout documentation>
| <-US/docs/Web/API/HTMLFrameSetElement.onresize Mozilla HTMLFrameSetElement.onresize documentation>
| <-US/docs/Web/API/HTMLFrameSetElement.onscroll Mozilla HTMLFrameSetElement.onscroll documentation> | # LANGUAGE PatternSynonyms #
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
module GHCJS.DOM.JSFFI.Generated.HTMLFrameSetElement
(js_setCols, setCols, js_getCols, getCols, js_setRows, setRows,
js_getRows, getRows, blur, error, focus, focusin, focusout, load,
resize, scroll, webKitWillRevealBottom, webKitWillRevealLeft,
webKitWillRevealRight, webKitWillRevealTop,
HTMLFrameSetElement(..), gTypeHTMLFrameSetElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import qualified Prelude (error)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull, jsUndefined)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import Data.Maybe (fromJust)
import Data.Traversable (mapM)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"cols\"] = $2;" js_setCols ::
HTMLFrameSetElement -> JSString -> IO ()
setCols ::
(MonadIO m, ToJSString val) => HTMLFrameSetElement -> val -> m ()
setCols self val = liftIO (js_setCols self (toJSString val))
foreign import javascript unsafe "$1[\"cols\"]" js_getCols ::
HTMLFrameSetElement -> IO JSString
getCols ::
(MonadIO m, FromJSString result) => HTMLFrameSetElement -> m result
getCols self = liftIO (fromJSString <$> (js_getCols self))
foreign import javascript unsafe "$1[\"rows\"] = $2;" js_setRows ::
HTMLFrameSetElement -> JSString -> IO ()
| < -US/docs/Web/API/HTMLFrameSetElement.rows Mozilla HTMLFrameSetElement.rows documentation >
setRows ::
(MonadIO m, ToJSString val) => HTMLFrameSetElement -> val -> m ()
setRows self val = liftIO (js_setRows self (toJSString val))
foreign import javascript unsafe "$1[\"rows\"]" js_getRows ::
HTMLFrameSetElement -> IO JSString
| < -US/docs/Web/API/HTMLFrameSetElement.rows Mozilla HTMLFrameSetElement.rows documentation >
getRows ::
(MonadIO m, FromJSString result) => HTMLFrameSetElement -> m result
getRows self = liftIO (fromJSString <$> (js_getRows self))
| < -US/docs/Web/API/HTMLFrameSetElement.onblur Mozilla HTMLFrameSetElement.onblur documentation >
blur :: EventName HTMLFrameSetElement FocusEvent
blur = unsafeEventNameAsync (toJSString "blur")
| < -US/docs/Web/API/HTMLFrameSetElement.onerror Mozilla HTMLFrameSetElement.onerror documentation >
error :: EventName HTMLFrameSetElement UIEvent
error = unsafeEventNameAsync (toJSString "error")
| < -US/docs/Web/API/HTMLFrameSetElement.onfocus Mozilla HTMLFrameSetElement.onfocus documentation >
focus :: EventName HTMLFrameSetElement FocusEvent
focus = unsafeEventNameAsync (toJSString "focus")
| < -US/docs/Web/API/HTMLFrameSetElement.onfocusin Mozilla HTMLFrameSetElement.onfocusin documentation >
focusin :: EventName HTMLFrameSetElement onfocusin
focusin = unsafeEventName (toJSString "focusin")
focusout :: EventName HTMLFrameSetElement onfocusout
focusout = unsafeEventName (toJSString "focusout")
| < -US/docs/Web/API/HTMLFrameSetElement.onload Mozilla HTMLFrameSetElement.onload documentation >
load :: EventName HTMLFrameSetElement UIEvent
load = unsafeEventNameAsync (toJSString "load")
resize :: EventName HTMLFrameSetElement UIEvent
resize = unsafeEventName (toJSString "resize")
scroll :: EventName HTMLFrameSetElement UIEvent
scroll = unsafeEventName (toJSString "scroll")
| < -US/docs/Web/API/HTMLFrameSetElement.onwebkitwillrevealbottom Mozilla HTMLFrameSetElement.onwebkitwillrevealbottom documentation >
webKitWillRevealBottom :: EventName HTMLFrameSetElement Event
webKitWillRevealBottom
= unsafeEventName (toJSString "webkitwillrevealbottom")
| < -US/docs/Web/API/HTMLFrameSetElement.onwebkitwillrevealleft Mozilla HTMLFrameSetElement.onwebkitwillrevealleft documentation >
webKitWillRevealLeft :: EventName HTMLFrameSetElement Event
webKitWillRevealLeft
= unsafeEventName (toJSString "webkitwillrevealleft")
| < -US/docs/Web/API/HTMLFrameSetElement.onwebkitwillrevealright Mozilla documentation >
webKitWillRevealRight :: EventName HTMLFrameSetElement Event
webKitWillRevealRight
= unsafeEventName (toJSString "webkitwillrevealright")
| < -US/docs/Web/API/HTMLFrameSetElement.onwebkitwillrevealtop Mozilla HTMLFrameSetElement.onwebkitwillrevealtop documentation >
webKitWillRevealTop :: EventName HTMLFrameSetElement Event
webKitWillRevealTop
= unsafeEventName (toJSString "webkitwillrevealtop") |
5ca956964915a7f3a2a3caae4808d3bdcf580a72663cea82b08c222d9d6a0ae9 | RedHatQE/katello.auto | systems.clj | (ns katello.systems
(:require [webdriver :as browser]
[clj-webdriver.core :as action]
[clojure.string :refer [blank?]]
[clojure.data :as data]
[slingshot.slingshot :refer [throw+]]
[katello.tasks :refer [expecting-error]]
[test.assert :as assert]
[katello :as kt]
(katello [navigation :as nav]
environments
[notifications :as notification]
[ui :as ui]
[ui-common :as common]
[rest :as rest]
[tasks :as tasks])))
;; Locators
(browser/template-fns
{subscription-available-checkbox "//div[@alch-table='availableSubscriptionsTable']//td[contains(normalize-space(.),'%s')]/preceding-sibling::td[@class='row-select']/input[@type='checkbox']"
subscription-current-checkbox "//div[@alch-table='currentSubscriptionsTable']//td[contains(normalize-space(.),'%s')]/preceding-sibling::td[@class='row-select']/input[@type='checkbox']"
checkbox "//input[@class='system_checkbox' and @type='checkbox' and parent::td[normalize-space(.)='%s']]"
sysgroup-checkbox "//input[@title='%s']"
check-selected-env "//span[@class='checkbox_holder']/input[@class='node_select' and @data-node_name='%s']"
select-sysgroup-checkbox "//input[contains(@title,'%s') and @name='multiselect_system_group']"
activation-key-link (ui/link "%s")
env-select (ui/link "%s")
select-system "//td[@class='ng-scope']/a[contains(text(), '%s')]"
select-system-checkbox "//td[@class='ng-scope']/a[contains(text(), '%s')]/parent::td/preceding-sibling::td[@class='row-select']/input[@ng-model='system.selected']"
remove-package "//td[contains(text(), '%s')]/following::td/i[@ng-click='table.removePackage(package)']"
remove-package-status "//td[contains(text(), '%s')]/following::td/i[2]"
package-select "//input[@id='package_%s']"
get-filtered-package "//td[contains(., '%s') and parent::tr[@ng-repeat='package in table.rows | filter:table.filter']]"
environment-checkbox "//div[contains(text(), '%s')]"
system-detail-textbox "//span[contains(.,'%s')]/./following-sibling::*[1]"
system-fact-textbox "//span[contains(.,'%s')]/./following-sibling::*[1]"
existing-key-value-field "//div[@class='details-container']/div/span[contains(text(), '%s')]/following::span[@class='fr']/i[1]"
remove-custom-info-button "//div[@class='details-container']/div/span[contains(text(), '%s')]/following::span[@class='fr']/i[2]"
save-button-common "//span[@class='info-label ng-binding' and contains(.,'%s')]/../div/div/span/div/button[@ng-click='save()']"})
(ui/defelements :katello.deployment/any []
{::new "new"
::create {:name "commit"}
::name-text {:tag :input, :name "system[name]"}
::sockets-text {:tag :input, :name "system[sockets]"}
::arch-select {:name "arch[arch_id]"}
::system-virtual-type "system_type_virtualized_virtual"
::content-view-select {:name "system[content_view_id]"}
::expand-env-widget "path-collapsed"
::remove "//button[contains(text(), 'Remove System')]"
::confirmation-yes "//button[normalize-space(.)='Yes']"
::confirmation-no "//button[normalize-space(.)='No']"
::bulk-action "//div[@class='nutupane-actions fr']/button[contains (.,'Bulk Actions')]"
::select-all-system "//input[@ng-model='table.allSelected']"
::total-selected-count "//div[@class='fr select-action']/span"
::multi-remove (ui/link "Remove System(s)")
::confirm-yes "//input[@value='Yes']"
::select-sysgrp "//div[@class='alch-edit']/div[@ng-click='edit()']"
::add-sysgrp "//button[@ng-click='add()']"
::confirm-to-no "xpath=(//button[@type='button'])[3]"
::system-groups {:xpath (ui/third-level-link "systems_system_groups")}
::add-group-form "//form[@id='add_group_form']/button"
::add-group "//input[@id='add_groups']"
;;new system form
::sockets-icon "//fieldset[descendant::input[@id='system_sockets']]//i"
::ram-icon "//fieldset[descendant::input[@id='system_memory']]//i"
;;content
::packages-link "//nav[@class='details-navigation']//li/a[contains (text(), 'Packages')]"
::events-link "//nav[@class='details-navigation']//li/a[contains (text(), 'Events')]"
::errata-link "//nav[@class='details-navigation']//li/a[contains (text(), 'Errata')]"
::package-action "//select[@ng-model='packageAction.actionType']"
::perform-action "//input[@name='Perform']"
::input-package-name "//input[@ng-model='packageAction.term']"
::filter-package "//input[@ng-model='currentPackagesTable.filter']"
::update-all "//button[@ng-click='updateAll()']"
::filter-errata "//input[@ng-model='errataTable.errataFilterTerm']"
::pkg-install-status "//div[@class='details']//div[2]/span[2]"
::pkg-summary "//div[@class='details']//div/span[2]"
::pkg-request "//div[@class='details']//div[4]/span[2]"
::pkg-parameters "//div[@class='details']//div[5]/span[2]"
::pkg-result "//div[@class='detail']/span[contains(., 'Result')]//following-sibling::span"
;;system-edit details
::details "//nav[@class='details-navigation']//li/a[contains (text(), 'Details')]"
::edit-name "//div[@alch-edit-text='system.name']//span"
::input-name-text "//div[@alch-edit-text='system.name']//input"
::edit-description "//div[@alch-edit-textarea='system.description']//span"
::input-description-text "//div[@alch-edit-textarea='system.description']//textarea"
::save-button "//button[@ng-click='save()']"
::cancel-button "//button[@ng-click='cancel()']"
::get-selected-env "//div[@id='path_select_system_details_path_selector']//label[@class='active']//div"
::select-content-view "//div[@edit-trigger='editContentView']/select"
::release-version-edit "//div[@selector='system.releaseVer']/div/div/span/i[contains(@class,'icon-edit')]"
::select-release-version "//div[@alch-edit-select='system.releaseVer']/select"
::expand-eth-interface "//div/i[@class='expand-icon clickable icon-plus']"
::expand-lo-interface "//div[2]/i[@class='expand-icon clickable icon-plus']"
::sys-count "//div[@class='nutupane-actionbar']/div/span"
::subs-detail-textbox "//span[contains(.,'Details')]/../div/ul/li"
;;system-facts
::expand-advanced-info "//div[@class='advanced-info']/header/i[@class='expand-icon clickable icon-plus']"
;;custom-info
::custom-info (ui/link "Custom Information")
::key-name {:tag :input, :ng-model "newKey"}
::key-value {:tag :input, :ng-model "newValue"}
::add-custom-info "//button[@ng-click='add({value: {keyname: newKey, value: newValue}})']"
::input-custom-value "//div[@alch-edit-text='customInfo.value']//input"
::custom-info-save-button "//div/div/div/div/span/div/button" ;;ui/save-button locator doesn't work
::existing-custom-items "//div[@class='existing-items']"
;;subscriptions pane
::subscriptions "//nav[@class='details-navigation']//li/a[contains (text(), 'Subscriptions')]"
::attach-subscription "//button[@ng-click='attachSubscriptions()']"
::remove-subscription "//button[@ng-click='removeSubscriptions()']"
::current-subscription-name "//div[@alch-table='currentSubscriptionsTable']//td[2]"
::red-subs-icon "//i[@class='icon-circle red']"
::green-subs-icon "//i[@class='icon-circle green']"})
;; Nav
(nav/defpages :katello.deployment/any katello.menu
[::page
[::named-page (fn [system] (ui/go-to-system system))
[::details-page (fn [_] (browser/click ::details))]
[::subscriptions-page (fn [_] (browser/click ::subscriptions))]
[::packages-page (fn [_] (browser/click ::packages-link))]
[::errata-page (fn [_] (browser/click ::errata-link))]]])
(def save-map
{:name "Name"
:description "Description"
:auto-attach "Auto-Attach"
:service-level "Service Level"
:system-groups "System Groups"
:release-version "Release Version"
:content-view "Content View"})
;; Tasks
(defn- create "Create a system from UI"
[]
;;use rest
)
(defn delete "Deletes the selected system."
[system]
(nav/go-to system)
(browser/click ::remove)
(browser/click ::confirmation-yes))
(defn- select-multisys
[systems]
(doseq [system systems]
(browser/click (select-system-checkbox (:name system)))))
(defn multi-delete "Delete multiple systems at once."
[systems]
(nav/go-to ::page (first systems))
(select-multisys systems)
(browser/click ::bulk-action)
(browser/click ::remove)
(browser/click ::confirmation-yes)
(browser/refresh))
(defn add-bulk-sys-to-sysgrp
"Adding systems to system group in bulk by pressing ctrl, from right-pane of system tab."
[systems group]
(select-multisys systems)
(browser/click ::bulk-action)
(browser/click ::select-sysgrp)
(browser/click (-> group :name sysgroup-checkbox))
(browser/click ::add-sysgrp)
(browser/click ::confirmation-yes))
(defn- add-sys-to-sysgrp
"Adding sys to sysgroup from right pane"
[system group-name]
(nav/go-to system)
(browser/click ::system-groups)
(browser/click ::add-group-form)
(if (browser/exists? (select-sysgroup-checkbox group-name))
(do
(browser/click (select-sysgroup-checkbox group-name))
(browser/click ::add-group)
(notification/success-type :sys-add-sysgrps))
(throw+ {:type ::selected-sys-group-is-unavailable
:msg "Selected sys-group is not available to add more system as limit already exceeds"})))
(defn- set-environment "select a new environment for a system"
[new-environment published-name]
{:pre [(not-empty new-environment)]}
(browser/click (environment-checkbox new-environment))
(browser/select-by-text ::select-content-view published-name)
(browser/click (-> save-map :content-view save-button-common)))
(defn subscribe
"Subscribes the given system to the products. (products should be a
list). Can also set the auto-subscribe for a particular SLA.
auto-subscribe must be either true or false to select a new setting
for auto-subscribe and SLA. If auto-subscribe is nil, no changes
will be made."
[add-products remove-products]
(let [sub-unsub-fn (fn [content checkbox-fn submit]
(when-not (empty? content)
(doseq [item content]
(browser/click (checkbox-fn (:name item))))
(browser/click submit)
(notification/success-type :sys-update-subscriptions)))]
(sub-unsub-fn add-products subscription-available-checkbox ::attach-subscription)
(sub-unsub-fn remove-products subscription-current-checkbox ::remove-subscription)))
(defn- edit-system-name
[{:keys [name]}]
(if-not (nil? name)
(do
(browser/click ::edit-name)
(common/edit-sys-details {::input-name-text name}))))
(defn- edit-system-description
[{:keys [description]}]
(if-not (nil? description)
(do
(browser/click ::edit-description)
(common/edit-sys-details {::input-description-text description}))))
(defn- edit-custom-info
[key value]
(if-not (nil? value)
(do
(browser/click (existing-key-value-field key))
(browser/clear ::input-custom-value)
(browser/input-text ::input-custom-value value)
(browser/click ::custom-info-save-button))))
(defn- set-release-version
[release-version]
(browser/click ::release-version-edit)
(browser/select-by-text ::select-release-version release-version)
(browser/click (-> save-map :release-version save-button-common)))
(defn get-release-version
[system]
(nav/go-to ::details-page system)
(browser/click ::release-version-edit)
(browser/text ::select-release-version))
(defn- update-custom-info [to-add to-remove]
(doseq [[k v] to-add]
(if (and to-remove (to-remove k)) ;;if also in the remove, it's an update
(edit-custom-info k v)
(do (browser/input-text ::key-name k)
(browser/input-text ::key-value v)
#_(browser keyUp ::key-name "w") ;; TODO: composite actions fixme
(browser/click ::add-custom-info))))
;; process removes
(doseq [[k _] (apply dissoc to-remove (keys to-add))]
(browser/click (remove-custom-info-button k))))
(defn- update
"Edits the properties of the given system. Optionally specify a new
name, a new description, and a new location."
[system updated]
(let [[to-remove {:keys [name description location release-version
service-level auto-attach env cv]
:as to-add} _] (data/diff system updated)]
(when (some not-empty (list to-remove to-add))
(Thread/sleep 5000)
(nav/go-to ::details-page system)
(edit-system-name to-add)
(edit-system-description to-add)
(when env (set-environment (:name env :published-name cv)))
(when release-version (set-release-version release-version))
(when (or (:custom-info to-add) (:custom-info to-remove))
(update-custom-info (:custom-info to-add) (:custom-info to-remove)))
(let [added-products (:products to-add)
removed-products (:products to-remove)]
(when (some #(not (nil? %)) (list added-products removed-products
service-level auto-attach))
(browser/click ::subscriptions)
(subscribe added-products removed-products)
(when (some #(not (nil? %)) (list service-level auto-attach))
(common/in-place-edit {::service-level-select (format "Auto-attach %s, %s"
(if (:auto-attach updated) "On" "Off")
(:service-level updated))})))))))
(defn random-facts
"Generate facts about a system - used to register fake systems via
the api. Some facts are randomized to guarantee uniqueness."
[]
(let [rand (java.util.Random.)
rand-255 #(.nextInt rand 255)
splice (comp (partial apply str) interpose)
ip-prefix (splice "." (repeatedly 3 rand-255 ))
mac (splice ":" (repeatedly 6 #(format "%02x" (rand-255))))] {
"dmi.bios.runtime_size" "128 KB"
"lscpu.cpu_op-mode(s)" "64-bit"
"uname.sysname" "Linux"
"distribution.name" "Fedora"
"dmi.system.family" "Virtual Machine"
"lscpu.l1d_cache" "32K"
"dmi.system.product_name" "VirtualBox"
"dmi.bios.address" "0xe0000"
"lscpu.stepping" "5"
"virt.host_type" "virtualbox"
"lscpu.l2d_cache" "6144K"
"uname.machine" "x86_64"
"lscpu.thread(s)_per_core" "1"
"cpu.cpu_socket(s)" "1"
"net.interface.eth1.hwaddr" mac
"lscpu.cpu(s)" "1"
"uname.version" "#1 SMP Fri Oct 22 15:36:08 UTC 2010"
"distribution.version" "14"
"lscpu.architecture" "x86_64"
"dmi.system.manufacturer" "innotek GmbH"
"network.ipaddr" (format "%s.4" ip-prefix),
"system.entitlements_valid" "true"
"dmi.system.uuid" (.toString (java.util.UUID/randomUUID)),
"uname.release" "2.6.35.6-48.fc14.x86_64"
"dmi.system.serial_number" "0"
"dmi.bios.version" "VirtualBox"
"cpu.core(s)_per_socket" "1"
"lscpu.core(s)_per_socket" "1"
"net.interface.lo.broadcast" "0.0.0.0"
"memory.swaptotal" "2031612"
"net.interface.lo.netmask" "255.0.0.0"
"lscpu.model" "37"
"lscpu.cpu_mhz" "2825.811"
"net.interface.eth1.netmask" "255.255.255.0"
"lscpu.numa_node(s)" "1"
"net.interface.lo.hwaddr" "00:00:00:00:00:00"
"uname.nodename" "killing-time.appliedlogic.ca"
"dmi.bios.vendor" "innotek GmbH"
"network.hostname" (str "killing-time" (rand-255) ".appliedlogic."
(rand-nth ["ca" "org" "com" "edu" "in"])),
"net.interface.eth1.broadcast" (format "%s.255" ip-prefix),
"memory.memtotal" "1023052"
"dmi.system.wake-up_type" "Power Switch"
"cpu.cpu(s)" "1"
"virt.is_guest" "true"
"dmi.system.sku_number" "Not Specified"
"net.interface.lo.ipaddr" "127.0.0.1"
"distribution.id" "Laughlin"
"lscpu.cpu_socket(s)" "1"
"dmi.system.version" "1.2"
"dmi.bios.rom_size" "128 KB"
"lscpu.vendor_id" "GenuineIntel"
"net.interface.eth1.ipaddr" (format "%s.8" ip-prefix),
"lscpu.cpu_family" "6"
"dmi.bios.relase_date" "12/01/2006"
"lscpu.numa_node0_cpu(s)" "0"
}))
(extend katello.System
ui/CRUD {:create create
:delete delete
:update* update}
rest/CRUD (let [headpin-url (partial rest/url-maker [["api/organizations/%s/systems" [#'kt/org]]])
katello-url (partial rest/url-maker [["api/environments/%s/systems" [#'kt/env]]])
id-url (partial rest/url-maker [["api/systems/%s" [identity]]])]
{:id :uuid
:query (fn [sys]
(rest/query-by-name
(if (rest/is-katello?)
katello-url headpin-url) sys))
:read (partial rest/read-impl id-url)
:create (fn [sys]
(merge sys (rest/http-post
(if (rest/is-katello?)
(katello-url sys)
(headpin-url sys))
{:body (assoc (select-keys sys [:name :facts])
:type "system")})))})
tasks/Uniqueable {:uniques #(for [s (tasks/timestamps)]
(assoc (tasks/stamp-entity %1 s)
:facts (if-let [f (:facts %1)]
f
(random-facts))))}
nav/Destination {:go-to (partial nav/go-to ::named-page)})
(defn api-pools
"Gets all pools a system is subscribed to"
[system]
(->> (rest/http-get (rest/url-maker [["api/systems/%s/pools" [identity]]] system))
:pools
(map kt/newPool)))
(defn pool-provides-product [{:keys [name] :as product}
{:keys [productName providedProducts] :as pool}]
(or (= productName name)
(some #(= (:productName %) name)
providedProducts)))
(defn pool-id "Fetch subscription pool-id"
[system product]
(->> system
api-pools
(filter (partial pool-provides-product product))
first :id))
(defn environment "Get name of current environment of the system"
[system]
(nav/go-to ::details-page system)
(browser/text ::get-selected-env))
(defn get-details [system]
(nav/go-to ::details-page system)
(browser/click ::expand-eth-interface)
(let [headpin-details ["UUID" "Hostname" "Interfaces" "Name" "Description" "OS" "Release"
"Arch" "RAM" "Sockets" "Checkin" "Registered" "Type"
"ipv4 address" "ipv4 netmask" "ipv4 broadcast" "Product" "Activation Key(s)"]
;;Removed some details, New UI doesn't show these under details tab
;;like: "Last Booted"
katello-details (conj headpin-details "Environment")
details (if (rest/is-katello?) katello-details headpin-details)]
(zipmap details
(doall (for [detail details]
(browser/text (system-detail-textbox detail)))))))
(defn get-facts [system]
(nav/go-to ::details-page system)
(browser/click ::expand-advanced-info)
(let [facts ["core(s) per_socket" "cpu(s)" "cpu socket(s)"
"id" "name" "version"
"memtotal" "swaptotal"
"host type" "is guest" "uuid"
"machine" "nodename" "release"
"sysname" "hostname"]]
(zipmap facts
(doall (for [fact facts]
(browser/text (system-fact-textbox fact)))))))
(defn check-package-status
[&[timeout-ms]]
(browser/loop-with-timeout (or timeout-ms (* 20 60 1000))[current-status ""]
(case current-status
"finished" current-status
"error" (throw+ {:type ::package-install-failed :msg "Package operation failed"})
(do (Thread/sleep 2000)
(recur (browser/text ::pkg-install-status))))))
(defn package-action "Install/remove/update package/package-group on selected system "
[system {:keys [package pkg-action]}]
(nav/go-to ::packages-page system)
(browser/select-by-text ::package-action pkg-action)
(browser/input-text ::input-package-name package)
(browser/click ::perform-action)
(check-package-status))
(defn update-all "Run update-all to update a selected system"
[system]
(nav/go-to ::packages-page system)
(browser/click ::update-all)
(check-package-status))
(defn filter-package
[system {:keys [package]}]
(nav/go-to ::packages-page system)
(browser/input-text ::filter-package package))
(defn remove-selected-package "Remove a selected package from package-list"
[system {:keys [package]} &[timeout-ms]]
(filter-package system {:package package})
(browser/click (remove-package package)))
| null | https://raw.githubusercontent.com/RedHatQE/katello.auto/79fec96581044bce5db5350d0da325e517024962/src/katello/systems.clj | clojure | Locators
new system form
content
system-edit details
system-facts
custom-info
ui/save-button locator doesn't work
subscriptions pane
Nav
Tasks
use rest
if also in the remove, it's an update
TODO: composite actions fixme
process removes
Removed some details, New UI doesn't show these under details tab
like: "Last Booted" | (ns katello.systems
(:require [webdriver :as browser]
[clj-webdriver.core :as action]
[clojure.string :refer [blank?]]
[clojure.data :as data]
[slingshot.slingshot :refer [throw+]]
[katello.tasks :refer [expecting-error]]
[test.assert :as assert]
[katello :as kt]
(katello [navigation :as nav]
environments
[notifications :as notification]
[ui :as ui]
[ui-common :as common]
[rest :as rest]
[tasks :as tasks])))
(browser/template-fns
{subscription-available-checkbox "//div[@alch-table='availableSubscriptionsTable']//td[contains(normalize-space(.),'%s')]/preceding-sibling::td[@class='row-select']/input[@type='checkbox']"
subscription-current-checkbox "//div[@alch-table='currentSubscriptionsTable']//td[contains(normalize-space(.),'%s')]/preceding-sibling::td[@class='row-select']/input[@type='checkbox']"
checkbox "//input[@class='system_checkbox' and @type='checkbox' and parent::td[normalize-space(.)='%s']]"
sysgroup-checkbox "//input[@title='%s']"
check-selected-env "//span[@class='checkbox_holder']/input[@class='node_select' and @data-node_name='%s']"
select-sysgroup-checkbox "//input[contains(@title,'%s') and @name='multiselect_system_group']"
activation-key-link (ui/link "%s")
env-select (ui/link "%s")
select-system "//td[@class='ng-scope']/a[contains(text(), '%s')]"
select-system-checkbox "//td[@class='ng-scope']/a[contains(text(), '%s')]/parent::td/preceding-sibling::td[@class='row-select']/input[@ng-model='system.selected']"
remove-package "//td[contains(text(), '%s')]/following::td/i[@ng-click='table.removePackage(package)']"
remove-package-status "//td[contains(text(), '%s')]/following::td/i[2]"
package-select "//input[@id='package_%s']"
get-filtered-package "//td[contains(., '%s') and parent::tr[@ng-repeat='package in table.rows | filter:table.filter']]"
environment-checkbox "//div[contains(text(), '%s')]"
system-detail-textbox "//span[contains(.,'%s')]/./following-sibling::*[1]"
system-fact-textbox "//span[contains(.,'%s')]/./following-sibling::*[1]"
existing-key-value-field "//div[@class='details-container']/div/span[contains(text(), '%s')]/following::span[@class='fr']/i[1]"
remove-custom-info-button "//div[@class='details-container']/div/span[contains(text(), '%s')]/following::span[@class='fr']/i[2]"
save-button-common "//span[@class='info-label ng-binding' and contains(.,'%s')]/../div/div/span/div/button[@ng-click='save()']"})
(ui/defelements :katello.deployment/any []
{::new "new"
::create {:name "commit"}
::name-text {:tag :input, :name "system[name]"}
::sockets-text {:tag :input, :name "system[sockets]"}
::arch-select {:name "arch[arch_id]"}
::system-virtual-type "system_type_virtualized_virtual"
::content-view-select {:name "system[content_view_id]"}
::expand-env-widget "path-collapsed"
::remove "//button[contains(text(), 'Remove System')]"
::confirmation-yes "//button[normalize-space(.)='Yes']"
::confirmation-no "//button[normalize-space(.)='No']"
::bulk-action "//div[@class='nutupane-actions fr']/button[contains (.,'Bulk Actions')]"
::select-all-system "//input[@ng-model='table.allSelected']"
::total-selected-count "//div[@class='fr select-action']/span"
::multi-remove (ui/link "Remove System(s)")
::confirm-yes "//input[@value='Yes']"
::select-sysgrp "//div[@class='alch-edit']/div[@ng-click='edit()']"
::add-sysgrp "//button[@ng-click='add()']"
::confirm-to-no "xpath=(//button[@type='button'])[3]"
::system-groups {:xpath (ui/third-level-link "systems_system_groups")}
::add-group-form "//form[@id='add_group_form']/button"
::add-group "//input[@id='add_groups']"
::sockets-icon "//fieldset[descendant::input[@id='system_sockets']]//i"
::ram-icon "//fieldset[descendant::input[@id='system_memory']]//i"
::packages-link "//nav[@class='details-navigation']//li/a[contains (text(), 'Packages')]"
::events-link "//nav[@class='details-navigation']//li/a[contains (text(), 'Events')]"
::errata-link "//nav[@class='details-navigation']//li/a[contains (text(), 'Errata')]"
::package-action "//select[@ng-model='packageAction.actionType']"
::perform-action "//input[@name='Perform']"
::input-package-name "//input[@ng-model='packageAction.term']"
::filter-package "//input[@ng-model='currentPackagesTable.filter']"
::update-all "//button[@ng-click='updateAll()']"
::filter-errata "//input[@ng-model='errataTable.errataFilterTerm']"
::pkg-install-status "//div[@class='details']//div[2]/span[2]"
::pkg-summary "//div[@class='details']//div/span[2]"
::pkg-request "//div[@class='details']//div[4]/span[2]"
::pkg-parameters "//div[@class='details']//div[5]/span[2]"
::pkg-result "//div[@class='detail']/span[contains(., 'Result')]//following-sibling::span"
::details "//nav[@class='details-navigation']//li/a[contains (text(), 'Details')]"
::edit-name "//div[@alch-edit-text='system.name']//span"
::input-name-text "//div[@alch-edit-text='system.name']//input"
::edit-description "//div[@alch-edit-textarea='system.description']//span"
::input-description-text "//div[@alch-edit-textarea='system.description']//textarea"
::save-button "//button[@ng-click='save()']"
::cancel-button "//button[@ng-click='cancel()']"
::get-selected-env "//div[@id='path_select_system_details_path_selector']//label[@class='active']//div"
::select-content-view "//div[@edit-trigger='editContentView']/select"
::release-version-edit "//div[@selector='system.releaseVer']/div/div/span/i[contains(@class,'icon-edit')]"
::select-release-version "//div[@alch-edit-select='system.releaseVer']/select"
::expand-eth-interface "//div/i[@class='expand-icon clickable icon-plus']"
::expand-lo-interface "//div[2]/i[@class='expand-icon clickable icon-plus']"
::sys-count "//div[@class='nutupane-actionbar']/div/span"
::subs-detail-textbox "//span[contains(.,'Details')]/../div/ul/li"
::expand-advanced-info "//div[@class='advanced-info']/header/i[@class='expand-icon clickable icon-plus']"
::custom-info (ui/link "Custom Information")
::key-name {:tag :input, :ng-model "newKey"}
::key-value {:tag :input, :ng-model "newValue"}
::add-custom-info "//button[@ng-click='add({value: {keyname: newKey, value: newValue}})']"
::input-custom-value "//div[@alch-edit-text='customInfo.value']//input"
::existing-custom-items "//div[@class='existing-items']"
::subscriptions "//nav[@class='details-navigation']//li/a[contains (text(), 'Subscriptions')]"
::attach-subscription "//button[@ng-click='attachSubscriptions()']"
::remove-subscription "//button[@ng-click='removeSubscriptions()']"
::current-subscription-name "//div[@alch-table='currentSubscriptionsTable']//td[2]"
::red-subs-icon "//i[@class='icon-circle red']"
::green-subs-icon "//i[@class='icon-circle green']"})
(nav/defpages :katello.deployment/any katello.menu
[::page
[::named-page (fn [system] (ui/go-to-system system))
[::details-page (fn [_] (browser/click ::details))]
[::subscriptions-page (fn [_] (browser/click ::subscriptions))]
[::packages-page (fn [_] (browser/click ::packages-link))]
[::errata-page (fn [_] (browser/click ::errata-link))]]])
(def save-map
{:name "Name"
:description "Description"
:auto-attach "Auto-Attach"
:service-level "Service Level"
:system-groups "System Groups"
:release-version "Release Version"
:content-view "Content View"})
(defn- create "Create a system from UI"
[]
)
(defn delete "Deletes the selected system."
[system]
(nav/go-to system)
(browser/click ::remove)
(browser/click ::confirmation-yes))
(defn- select-multisys
[systems]
(doseq [system systems]
(browser/click (select-system-checkbox (:name system)))))
(defn multi-delete "Delete multiple systems at once."
[systems]
(nav/go-to ::page (first systems))
(select-multisys systems)
(browser/click ::bulk-action)
(browser/click ::remove)
(browser/click ::confirmation-yes)
(browser/refresh))
(defn add-bulk-sys-to-sysgrp
"Adding systems to system group in bulk by pressing ctrl, from right-pane of system tab."
[systems group]
(select-multisys systems)
(browser/click ::bulk-action)
(browser/click ::select-sysgrp)
(browser/click (-> group :name sysgroup-checkbox))
(browser/click ::add-sysgrp)
(browser/click ::confirmation-yes))
(defn- add-sys-to-sysgrp
"Adding sys to sysgroup from right pane"
[system group-name]
(nav/go-to system)
(browser/click ::system-groups)
(browser/click ::add-group-form)
(if (browser/exists? (select-sysgroup-checkbox group-name))
(do
(browser/click (select-sysgroup-checkbox group-name))
(browser/click ::add-group)
(notification/success-type :sys-add-sysgrps))
(throw+ {:type ::selected-sys-group-is-unavailable
:msg "Selected sys-group is not available to add more system as limit already exceeds"})))
(defn- set-environment "select a new environment for a system"
[new-environment published-name]
{:pre [(not-empty new-environment)]}
(browser/click (environment-checkbox new-environment))
(browser/select-by-text ::select-content-view published-name)
(browser/click (-> save-map :content-view save-button-common)))
(defn subscribe
"Subscribes the given system to the products. (products should be a
list). Can also set the auto-subscribe for a particular SLA.
auto-subscribe must be either true or false to select a new setting
for auto-subscribe and SLA. If auto-subscribe is nil, no changes
will be made."
[add-products remove-products]
(let [sub-unsub-fn (fn [content checkbox-fn submit]
(when-not (empty? content)
(doseq [item content]
(browser/click (checkbox-fn (:name item))))
(browser/click submit)
(notification/success-type :sys-update-subscriptions)))]
(sub-unsub-fn add-products subscription-available-checkbox ::attach-subscription)
(sub-unsub-fn remove-products subscription-current-checkbox ::remove-subscription)))
(defn- edit-system-name
[{:keys [name]}]
(if-not (nil? name)
(do
(browser/click ::edit-name)
(common/edit-sys-details {::input-name-text name}))))
(defn- edit-system-description
[{:keys [description]}]
(if-not (nil? description)
(do
(browser/click ::edit-description)
(common/edit-sys-details {::input-description-text description}))))
(defn- edit-custom-info
[key value]
(if-not (nil? value)
(do
(browser/click (existing-key-value-field key))
(browser/clear ::input-custom-value)
(browser/input-text ::input-custom-value value)
(browser/click ::custom-info-save-button))))
(defn- set-release-version
[release-version]
(browser/click ::release-version-edit)
(browser/select-by-text ::select-release-version release-version)
(browser/click (-> save-map :release-version save-button-common)))
(defn get-release-version
[system]
(nav/go-to ::details-page system)
(browser/click ::release-version-edit)
(browser/text ::select-release-version))
(defn- update-custom-info [to-add to-remove]
(doseq [[k v] to-add]
(edit-custom-info k v)
(do (browser/input-text ::key-name k)
(browser/input-text ::key-value v)
(browser/click ::add-custom-info))))
(doseq [[k _] (apply dissoc to-remove (keys to-add))]
(browser/click (remove-custom-info-button k))))
(defn- update
"Edits the properties of the given system. Optionally specify a new
name, a new description, and a new location."
[system updated]
(let [[to-remove {:keys [name description location release-version
service-level auto-attach env cv]
:as to-add} _] (data/diff system updated)]
(when (some not-empty (list to-remove to-add))
(Thread/sleep 5000)
(nav/go-to ::details-page system)
(edit-system-name to-add)
(edit-system-description to-add)
(when env (set-environment (:name env :published-name cv)))
(when release-version (set-release-version release-version))
(when (or (:custom-info to-add) (:custom-info to-remove))
(update-custom-info (:custom-info to-add) (:custom-info to-remove)))
(let [added-products (:products to-add)
removed-products (:products to-remove)]
(when (some #(not (nil? %)) (list added-products removed-products
service-level auto-attach))
(browser/click ::subscriptions)
(subscribe added-products removed-products)
(when (some #(not (nil? %)) (list service-level auto-attach))
(common/in-place-edit {::service-level-select (format "Auto-attach %s, %s"
(if (:auto-attach updated) "On" "Off")
(:service-level updated))})))))))
(defn random-facts
"Generate facts about a system - used to register fake systems via
the api. Some facts are randomized to guarantee uniqueness."
[]
(let [rand (java.util.Random.)
rand-255 #(.nextInt rand 255)
splice (comp (partial apply str) interpose)
ip-prefix (splice "." (repeatedly 3 rand-255 ))
mac (splice ":" (repeatedly 6 #(format "%02x" (rand-255))))] {
"dmi.bios.runtime_size" "128 KB"
"lscpu.cpu_op-mode(s)" "64-bit"
"uname.sysname" "Linux"
"distribution.name" "Fedora"
"dmi.system.family" "Virtual Machine"
"lscpu.l1d_cache" "32K"
"dmi.system.product_name" "VirtualBox"
"dmi.bios.address" "0xe0000"
"lscpu.stepping" "5"
"virt.host_type" "virtualbox"
"lscpu.l2d_cache" "6144K"
"uname.machine" "x86_64"
"lscpu.thread(s)_per_core" "1"
"cpu.cpu_socket(s)" "1"
"net.interface.eth1.hwaddr" mac
"lscpu.cpu(s)" "1"
"uname.version" "#1 SMP Fri Oct 22 15:36:08 UTC 2010"
"distribution.version" "14"
"lscpu.architecture" "x86_64"
"dmi.system.manufacturer" "innotek GmbH"
"network.ipaddr" (format "%s.4" ip-prefix),
"system.entitlements_valid" "true"
"dmi.system.uuid" (.toString (java.util.UUID/randomUUID)),
"uname.release" "2.6.35.6-48.fc14.x86_64"
"dmi.system.serial_number" "0"
"dmi.bios.version" "VirtualBox"
"cpu.core(s)_per_socket" "1"
"lscpu.core(s)_per_socket" "1"
"net.interface.lo.broadcast" "0.0.0.0"
"memory.swaptotal" "2031612"
"net.interface.lo.netmask" "255.0.0.0"
"lscpu.model" "37"
"lscpu.cpu_mhz" "2825.811"
"net.interface.eth1.netmask" "255.255.255.0"
"lscpu.numa_node(s)" "1"
"net.interface.lo.hwaddr" "00:00:00:00:00:00"
"uname.nodename" "killing-time.appliedlogic.ca"
"dmi.bios.vendor" "innotek GmbH"
"network.hostname" (str "killing-time" (rand-255) ".appliedlogic."
(rand-nth ["ca" "org" "com" "edu" "in"])),
"net.interface.eth1.broadcast" (format "%s.255" ip-prefix),
"memory.memtotal" "1023052"
"dmi.system.wake-up_type" "Power Switch"
"cpu.cpu(s)" "1"
"virt.is_guest" "true"
"dmi.system.sku_number" "Not Specified"
"net.interface.lo.ipaddr" "127.0.0.1"
"distribution.id" "Laughlin"
"lscpu.cpu_socket(s)" "1"
"dmi.system.version" "1.2"
"dmi.bios.rom_size" "128 KB"
"lscpu.vendor_id" "GenuineIntel"
"net.interface.eth1.ipaddr" (format "%s.8" ip-prefix),
"lscpu.cpu_family" "6"
"dmi.bios.relase_date" "12/01/2006"
"lscpu.numa_node0_cpu(s)" "0"
}))
(extend katello.System
ui/CRUD {:create create
:delete delete
:update* update}
rest/CRUD (let [headpin-url (partial rest/url-maker [["api/organizations/%s/systems" [#'kt/org]]])
katello-url (partial rest/url-maker [["api/environments/%s/systems" [#'kt/env]]])
id-url (partial rest/url-maker [["api/systems/%s" [identity]]])]
{:id :uuid
:query (fn [sys]
(rest/query-by-name
(if (rest/is-katello?)
katello-url headpin-url) sys))
:read (partial rest/read-impl id-url)
:create (fn [sys]
(merge sys (rest/http-post
(if (rest/is-katello?)
(katello-url sys)
(headpin-url sys))
{:body (assoc (select-keys sys [:name :facts])
:type "system")})))})
tasks/Uniqueable {:uniques #(for [s (tasks/timestamps)]
(assoc (tasks/stamp-entity %1 s)
:facts (if-let [f (:facts %1)]
f
(random-facts))))}
nav/Destination {:go-to (partial nav/go-to ::named-page)})
(defn api-pools
"Gets all pools a system is subscribed to"
[system]
(->> (rest/http-get (rest/url-maker [["api/systems/%s/pools" [identity]]] system))
:pools
(map kt/newPool)))
(defn pool-provides-product [{:keys [name] :as product}
{:keys [productName providedProducts] :as pool}]
(or (= productName name)
(some #(= (:productName %) name)
providedProducts)))
(defn pool-id "Fetch subscription pool-id"
[system product]
(->> system
api-pools
(filter (partial pool-provides-product product))
first :id))
(defn environment "Get name of current environment of the system"
[system]
(nav/go-to ::details-page system)
(browser/text ::get-selected-env))
(defn get-details [system]
(nav/go-to ::details-page system)
(browser/click ::expand-eth-interface)
(let [headpin-details ["UUID" "Hostname" "Interfaces" "Name" "Description" "OS" "Release"
"Arch" "RAM" "Sockets" "Checkin" "Registered" "Type"
"ipv4 address" "ipv4 netmask" "ipv4 broadcast" "Product" "Activation Key(s)"]
katello-details (conj headpin-details "Environment")
details (if (rest/is-katello?) katello-details headpin-details)]
(zipmap details
(doall (for [detail details]
(browser/text (system-detail-textbox detail)))))))
(defn get-facts [system]
(nav/go-to ::details-page system)
(browser/click ::expand-advanced-info)
(let [facts ["core(s) per_socket" "cpu(s)" "cpu socket(s)"
"id" "name" "version"
"memtotal" "swaptotal"
"host type" "is guest" "uuid"
"machine" "nodename" "release"
"sysname" "hostname"]]
(zipmap facts
(doall (for [fact facts]
(browser/text (system-fact-textbox fact)))))))
(defn check-package-status
[&[timeout-ms]]
(browser/loop-with-timeout (or timeout-ms (* 20 60 1000))[current-status ""]
(case current-status
"finished" current-status
"error" (throw+ {:type ::package-install-failed :msg "Package operation failed"})
(do (Thread/sleep 2000)
(recur (browser/text ::pkg-install-status))))))
(defn package-action "Install/remove/update package/package-group on selected system "
[system {:keys [package pkg-action]}]
(nav/go-to ::packages-page system)
(browser/select-by-text ::package-action pkg-action)
(browser/input-text ::input-package-name package)
(browser/click ::perform-action)
(check-package-status))
(defn update-all "Run update-all to update a selected system"
[system]
(nav/go-to ::packages-page system)
(browser/click ::update-all)
(check-package-status))
(defn filter-package
[system {:keys [package]}]
(nav/go-to ::packages-page system)
(browser/input-text ::filter-package package))
(defn remove-selected-package "Remove a selected package from package-list"
[system {:keys [package]} &[timeout-ms]]
(filter-package system {:package package})
(browser/click (remove-package package)))
|
2f131866324a84b6fd6489fb55972eb297b32c56a514c347d80d758783b4c241 | ItsMeijers/Lambdabox | Extended.hs | # LANGUAGE DeriveGeneric , OverloadedStrings , ScopedTypeVariables #
# LANGUAGE GeneralizedNewtypeDeriving , ExistentialQuantification #
# LANGUAGE UndecidableInstances , FlexibleInstances , TypeSynonymInstances #
# LANGUAGE NamedFieldPuns #
module Network.Wreq.Extended
( module Network.Wreq
, get
, post
, put
, delete
, getSigned
, postSigned
, deleteSigned
, optionalParams
, ToText(..)
, OptionalParameter(..)
) where
import Lambdabox.Box
import Network.Wreq hiding (get, post, delete, put)
import Control.Lens ((&), (^.), (^?), (.~), set)
import Control.Monad.Reader
import Control.Monad.Except
import Data.Aeson (FromJSON)
import Data.Aeson.Lens (key)
import Data.Maybe (catMaybes)
import Data.Text (Text, pack, append)
import Data.Text.Encoding (encodeUtf8, decodeUtf8)
import Data.ByteString.Lazy (ByteString, empty)
import Data.Time.Clock.POSIX (getPOSIXTime)
import Crypto.MAC.HMAC (HMAC, hmac, hmacGetDigest)
import Crypto.Hash (Digest)
import Crypto.Hash.Algorithms (SHA256)
import qualified Data.Text as T
import qualified Network.HTTP.Client as N
import qualified Control.Exception as E
get :: forall a. (FromJSON a)
=> String
-> [(Text, Text)]
-> Box a
get uri params = httpRequest getWith uri params
post :: forall a. (FromJSON a)
=> String
-> [(Text, Text)]
-> Box a
post uri params = httpRequest (\o s -> postWith o s empty) uri params
put :: forall a. (FromJSON a)
=> String
-> [(Text, Text)]
-> Box a
put uri params = httpRequest (\o s -> putWith o s empty) uri params
delete :: forall a. (FromJSON a)
=> String
-> [(Text, Text)]
-> Box a
delete uri params = httpRequest deleteWith uri params
getSigned :: forall a. (FromJSON a)
=> String
-> [(Text, Text)]
-> Box a
getSigned uri params = signed params (get uri)
postSigned :: forall a. (FromJSON a) => String -> [(Text, Text)] -> Box a
postSigned uri params = signed params (post uri)
deleteSigned :: forall a. (FromJSON a) => String -> [(Text, Text)] -> Box a
deleteSigned uri params = signed params (delete uri)
signed :: forall a. (FromJSON a)
=> [(Text, Text)]
-> ([(Text, Text)] -> Box a) -- Continuation Request
-> Box a
signed params cRequest = do
boxConfiguration <- ask
timestamp <- liftIO getTimeStamp
let paramsT = ("timestamp", timestamp) : params
signature = sign paramsT (secretKey boxConfiguration)
cRequest (("signature", signature) : paramsT)
-- | Return timestamp in milliseconds
getTimeStamp :: IO Text
getTimeStamp = (pack . show . round . (* 1000)) <$> getPOSIXTime
-- | Sign the request by hashing the url parameters and secret key using SHA256
sign :: [(Text, Text)] -> Text -> Text
sign params secretKey = toText $ hmac' secretKey message
where message = T.drop 1 $ foldr keyValue "" params
keyValue (k, v) m = m `append` "&" `append` k `append` "=" `append` v
hmac' :: Text -> Text -> Digest SHA256
hmac' sk = hmacGetDigest . hmac (encodeUtf8 sk) . encodeUtf8
httpRequest :: forall a. (FromJSON a)
=> (Options -> String -> IO (Response ByteString))
-> String
-> [(Text, Text)]
-> Box a
httpRequest request uri params = do
boxConfiguration <- ask
response <- liftIO $ request
(buildOptions boxConfiguration params)
("" ++ uri)
liftEither $ foldResponse (response ^. responseStatus . statusCode) response
-- | Build the options for the http request based on a list of key value
-- parameters and setting the option of not checking the response and throwing
-- an IO error.
buildOptions :: BoxConfiguration -> [(Text, Text)] -> Options
buildOptions bo = foldl (\o (k, v) -> o & param k .~ [v]) (defaults' & key)
where defaults' = set checkResponse (Just $ \_ _ -> return ()) defaults
key = header "X-MBX-APIKEY" .~ [encodeUtf8 $ apiKey bo]
-- | Fold the response in Either an Error or the specific data
foldResponse :: (FromJSON a) => Int -> Response ByteString -> Either Error a
foldResponse s r
| s <= 207 && s >= 200 = liftJSONException (asJSON r)
| otherwise = do
error <- liftJSONException (asJSON r)
Left error
-- | If JSOn extraction goes wrong the error gets transformed into the Error
-- Data type
liftJSONException :: Either E.SomeException (Response a) -> Either Error a
liftJSONException (Right x) = Right (N.responseBody x)
liftJSONException (Left se) = Left $ Error
{ code = -1
, msg = pack $ E.displayException se}
class ToText a where
toText :: a -> Text
instance {-# OVERLAPPING #-} ToText Text where
toText = id
instance Show a => ToText a where
toText = pack . show
data OptionalParameter = forall s. ToText s => (:?) Text (Maybe s)
| Concatenates a list of key and a maybe value for easy
optionalParams :: [OptionalParameter] -> [(Text, Text)]
optionalParams = catMaybes . fmap fromMaybeParam
where fromMaybeParam (k :? (Just v)) = Just (k, toText v)
fromMaybeParam _ = Nothing | null | https://raw.githubusercontent.com/ItsMeijers/Lambdabox/c19a8ae7d37b9f8ab5054d558fe788a5d4483092/src/Network/Wreq/Extended.hs | haskell | Continuation Request
| Return timestamp in milliseconds
| Sign the request by hashing the url parameters and secret key using SHA256
| Build the options for the http request based on a list of key value
parameters and setting the option of not checking the response and throwing
an IO error.
| Fold the response in Either an Error or the specific data
| If JSOn extraction goes wrong the error gets transformed into the Error
Data type
# OVERLAPPING # | # LANGUAGE DeriveGeneric , OverloadedStrings , ScopedTypeVariables #
# LANGUAGE GeneralizedNewtypeDeriving , ExistentialQuantification #
# LANGUAGE UndecidableInstances , FlexibleInstances , TypeSynonymInstances #
# LANGUAGE NamedFieldPuns #
module Network.Wreq.Extended
( module Network.Wreq
, get
, post
, put
, delete
, getSigned
, postSigned
, deleteSigned
, optionalParams
, ToText(..)
, OptionalParameter(..)
) where
import Lambdabox.Box
import Network.Wreq hiding (get, post, delete, put)
import Control.Lens ((&), (^.), (^?), (.~), set)
import Control.Monad.Reader
import Control.Monad.Except
import Data.Aeson (FromJSON)
import Data.Aeson.Lens (key)
import Data.Maybe (catMaybes)
import Data.Text (Text, pack, append)
import Data.Text.Encoding (encodeUtf8, decodeUtf8)
import Data.ByteString.Lazy (ByteString, empty)
import Data.Time.Clock.POSIX (getPOSIXTime)
import Crypto.MAC.HMAC (HMAC, hmac, hmacGetDigest)
import Crypto.Hash (Digest)
import Crypto.Hash.Algorithms (SHA256)
import qualified Data.Text as T
import qualified Network.HTTP.Client as N
import qualified Control.Exception as E
get :: forall a. (FromJSON a)
=> String
-> [(Text, Text)]
-> Box a
get uri params = httpRequest getWith uri params
post :: forall a. (FromJSON a)
=> String
-> [(Text, Text)]
-> Box a
post uri params = httpRequest (\o s -> postWith o s empty) uri params
put :: forall a. (FromJSON a)
=> String
-> [(Text, Text)]
-> Box a
put uri params = httpRequest (\o s -> putWith o s empty) uri params
delete :: forall a. (FromJSON a)
=> String
-> [(Text, Text)]
-> Box a
delete uri params = httpRequest deleteWith uri params
getSigned :: forall a. (FromJSON a)
=> String
-> [(Text, Text)]
-> Box a
getSigned uri params = signed params (get uri)
postSigned :: forall a. (FromJSON a) => String -> [(Text, Text)] -> Box a
postSigned uri params = signed params (post uri)
deleteSigned :: forall a. (FromJSON a) => String -> [(Text, Text)] -> Box a
deleteSigned uri params = signed params (delete uri)
signed :: forall a. (FromJSON a)
=> [(Text, Text)]
-> Box a
signed params cRequest = do
boxConfiguration <- ask
timestamp <- liftIO getTimeStamp
let paramsT = ("timestamp", timestamp) : params
signature = sign paramsT (secretKey boxConfiguration)
cRequest (("signature", signature) : paramsT)
getTimeStamp :: IO Text
getTimeStamp = (pack . show . round . (* 1000)) <$> getPOSIXTime
sign :: [(Text, Text)] -> Text -> Text
sign params secretKey = toText $ hmac' secretKey message
where message = T.drop 1 $ foldr keyValue "" params
keyValue (k, v) m = m `append` "&" `append` k `append` "=" `append` v
hmac' :: Text -> Text -> Digest SHA256
hmac' sk = hmacGetDigest . hmac (encodeUtf8 sk) . encodeUtf8
httpRequest :: forall a. (FromJSON a)
=> (Options -> String -> IO (Response ByteString))
-> String
-> [(Text, Text)]
-> Box a
httpRequest request uri params = do
boxConfiguration <- ask
response <- liftIO $ request
(buildOptions boxConfiguration params)
("" ++ uri)
liftEither $ foldResponse (response ^. responseStatus . statusCode) response
buildOptions :: BoxConfiguration -> [(Text, Text)] -> Options
buildOptions bo = foldl (\o (k, v) -> o & param k .~ [v]) (defaults' & key)
where defaults' = set checkResponse (Just $ \_ _ -> return ()) defaults
key = header "X-MBX-APIKEY" .~ [encodeUtf8 $ apiKey bo]
foldResponse :: (FromJSON a) => Int -> Response ByteString -> Either Error a
foldResponse s r
| s <= 207 && s >= 200 = liftJSONException (asJSON r)
| otherwise = do
error <- liftJSONException (asJSON r)
Left error
liftJSONException :: Either E.SomeException (Response a) -> Either Error a
liftJSONException (Right x) = Right (N.responseBody x)
liftJSONException (Left se) = Left $ Error
{ code = -1
, msg = pack $ E.displayException se}
class ToText a where
toText :: a -> Text
toText = id
instance Show a => ToText a where
toText = pack . show
data OptionalParameter = forall s. ToText s => (:?) Text (Maybe s)
| Concatenates a list of key and a maybe value for easy
optionalParams :: [OptionalParameter] -> [(Text, Text)]
optionalParams = catMaybes . fmap fromMaybeParam
where fromMaybeParam (k :? (Just v)) = Just (k, toText v)
fromMaybeParam _ = Nothing |
a992f520be26f8ac7280679aa382d44c4b7f70d626e09f31ce9c15acf8ca0e21 | BitGameEN/bitgamex | rest_pastebin_app.erl | %% Feel free to use, reuse and abuse the code in this file.
@private
-module(rest_pastebin_app).
-behaviour(application).
%% API.
-export([start/2]).
-export([stop/1]).
%% API.
start(_Type, _Args) ->
Dispatch = cowboy_router:compile([
{'_', [
{"/[:paste_id]", toppage_handler, []}
]}
]),
{ok, _} = cowboy:start_clear(http, [{port, 8080}], #{
env => #{dispatch => Dispatch}
}),
rest_pastebin_sup:start_link().
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/BitGameEN/bitgamex/151ba70a481615379f9648581a5d459b503abe19/src/deps/cowboy/examples/rest_pastebin/src/rest_pastebin_app.erl | erlang | Feel free to use, reuse and abuse the code in this file.
API.
API. |
@private
-module(rest_pastebin_app).
-behaviour(application).
-export([start/2]).
-export([stop/1]).
start(_Type, _Args) ->
Dispatch = cowboy_router:compile([
{'_', [
{"/[:paste_id]", toppage_handler, []}
]}
]),
{ok, _} = cowboy:start_clear(http, [{port, 8080}], #{
env => #{dispatch => Dispatch}
}),
rest_pastebin_sup:start_link().
stop(_State) ->
ok.
|
c734649a00b0e0241a92fea629dbd9d2d6666b67c498662984199a9e10df2eb8 | marianoguerra/tanodb | tanodb_console.erl | %% @doc Interface for riak_searchng-admin commands.
-module(tanodb_console).
-export([staged_join/1,
down/1,
ringready/1]).
-ignore_xref([join/1,
leave/1,
remove/1,
ringready/1]).
staged_join([NodeStr]) ->
Node = list_to_atom(NodeStr),
join(NodeStr, fun riak_core:staged_join/1,
"Success: staged join request for ~p to ~p~n", [node(), Node]).
join(NodeStr, JoinFn, SuccessFmt, SuccessArgs) ->
try
case JoinFn(NodeStr) of
ok ->
io:format(SuccessFmt, SuccessArgs),
ok;
{error, not_reachable} ->
io:format("Node ~s is not reachable!~n", [NodeStr]),
error;
{error, different_ring_sizes} ->
io:format("Failed: ~s has a different ring_creation_size~n",
[NodeStr]),
error;
{error, unable_to_get_join_ring} ->
io:format("Failed: Unable to get ring from ~s~n", [NodeStr]),
error;
{error, not_single_node} ->
io:format("Failed: This node is already a member of a "
"cluster~n"),
error;
{error, self_join} ->
io:format("Failed: This node cannot join itself in a "
"cluster~n"),
error;
{error, _} ->
io:format("Join failed. Try again in a few moments.~n", []),
error
end
catch
Exception:Reason ->
lager:error("Join failed ~p:~p", [Exception, Reason]),
io:format("Join failed, see log for details~n"),
error
end.
down([Node]) ->
try
case riak_core:down(list_to_atom(Node)) of
ok ->
io:format("Success: ~p marked as down~n", [Node]),
ok;
{error, legacy_mode} ->
io:format("Cluster is currently in legacy mode~n"),
ok;
{error, is_up} ->
io:format("Failed: ~s is up~n", [Node]),
error;
{error, not_member} ->
io:format("Failed: ~p is not a member of the cluster.~n",
[Node]),
error;
{error, only_member} ->
io:format("Failed: ~p is the only member.~n", [Node]),
error
end
catch
Exception:Reason ->
lager:error("Down failed ~p:~p", [Exception, Reason]),
io:format("Down failed, see log for details~n"),
error
end.
ringready([]) ->
try
case riak_core_status:ringready() of
{ok, Nodes} ->
io:format("TRUE All nodes agree on the ring ~p\n", [Nodes]);
{error, {different_owners, N1, N2}} ->
io:format("FALSE Node ~p and ~p list different partition owners\n", [N1, N2]),
error;
{error, {nodes_down, Down}} ->
io:format("FALSE ~p down. All nodes need to be up to check.\n", [Down]),
error
end
catch
Exception:Reason ->
lager:error("Ringready failed ~p:~p", [Exception,
Reason]),
io:format("Ringready failed, see log for details~n"),
error
end.
| null | https://raw.githubusercontent.com/marianoguerra/tanodb/7b8bb0ddc0fd1e67b2522cff8a0dac40b412acdb/apps/tanodb/src/tanodb_console.erl | erlang | @doc Interface for riak_searchng-admin commands. | -module(tanodb_console).
-export([staged_join/1,
down/1,
ringready/1]).
-ignore_xref([join/1,
leave/1,
remove/1,
ringready/1]).
staged_join([NodeStr]) ->
Node = list_to_atom(NodeStr),
join(NodeStr, fun riak_core:staged_join/1,
"Success: staged join request for ~p to ~p~n", [node(), Node]).
join(NodeStr, JoinFn, SuccessFmt, SuccessArgs) ->
try
case JoinFn(NodeStr) of
ok ->
io:format(SuccessFmt, SuccessArgs),
ok;
{error, not_reachable} ->
io:format("Node ~s is not reachable!~n", [NodeStr]),
error;
{error, different_ring_sizes} ->
io:format("Failed: ~s has a different ring_creation_size~n",
[NodeStr]),
error;
{error, unable_to_get_join_ring} ->
io:format("Failed: Unable to get ring from ~s~n", [NodeStr]),
error;
{error, not_single_node} ->
io:format("Failed: This node is already a member of a "
"cluster~n"),
error;
{error, self_join} ->
io:format("Failed: This node cannot join itself in a "
"cluster~n"),
error;
{error, _} ->
io:format("Join failed. Try again in a few moments.~n", []),
error
end
catch
Exception:Reason ->
lager:error("Join failed ~p:~p", [Exception, Reason]),
io:format("Join failed, see log for details~n"),
error
end.
down([Node]) ->
try
case riak_core:down(list_to_atom(Node)) of
ok ->
io:format("Success: ~p marked as down~n", [Node]),
ok;
{error, legacy_mode} ->
io:format("Cluster is currently in legacy mode~n"),
ok;
{error, is_up} ->
io:format("Failed: ~s is up~n", [Node]),
error;
{error, not_member} ->
io:format("Failed: ~p is not a member of the cluster.~n",
[Node]),
error;
{error, only_member} ->
io:format("Failed: ~p is the only member.~n", [Node]),
error
end
catch
Exception:Reason ->
lager:error("Down failed ~p:~p", [Exception, Reason]),
io:format("Down failed, see log for details~n"),
error
end.
ringready([]) ->
try
case riak_core_status:ringready() of
{ok, Nodes} ->
io:format("TRUE All nodes agree on the ring ~p\n", [Nodes]);
{error, {different_owners, N1, N2}} ->
io:format("FALSE Node ~p and ~p list different partition owners\n", [N1, N2]),
error;
{error, {nodes_down, Down}} ->
io:format("FALSE ~p down. All nodes need to be up to check.\n", [Down]),
error
end
catch
Exception:Reason ->
lager:error("Ringready failed ~p:~p", [Exception,
Reason]),
io:format("Ringready failed, see log for details~n"),
error
end.
|
0e7d16fe1fdd2716fd0a94ee7c24446e30fcb80b9b7f4e7343f76a5b7e860848 | mirage/ocaml-ipaddr | macaddr_cstruct.ml |
* Copyright ( c ) 2019 Anil Madhavapeddy
* Copyright ( c ) 2014
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2019 Anil Madhavapeddy
* Copyright (c) 2014 Nicolás Ojeda Bär
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
let try_with_result fn a =
try Ok (fn a)
with Macaddr.Parse_error (msg, _) -> Error (`Msg ("Macaddr: " ^ msg))
let of_cstruct_exn cs =
if Cstruct.length cs <> 6 then
raise (Macaddr.Parse_error ("MAC is exactly 6 bytes", Cstruct.to_string cs))
else Cstruct.to_string cs |> Macaddr.of_octets_exn
let of_cstruct cs = try_with_result of_cstruct_exn cs
let write_cstruct_exn (mac : Macaddr.t) cs =
let len = Cstruct.length cs in
let mac = Macaddr.to_octets mac in
if len <> 6 then raise (Macaddr.Parse_error ("MAC is exactly 6 bytes", mac));
Cstruct.blit_from_string mac 0 cs 0 6
let to_cstruct ?(allocator = Cstruct.create) mac =
let cs = allocator 6 in
write_cstruct_exn mac cs;
cs
| null | https://raw.githubusercontent.com/mirage/ocaml-ipaddr/1a9da1cf1e922dad5aafdd41ca61d7c1b2275b9c/lib/macaddr_cstruct.ml | ocaml |
* Copyright ( c ) 2019 Anil Madhavapeddy
* Copyright ( c ) 2014
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2019 Anil Madhavapeddy
* Copyright (c) 2014 Nicolás Ojeda Bär
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
let try_with_result fn a =
try Ok (fn a)
with Macaddr.Parse_error (msg, _) -> Error (`Msg ("Macaddr: " ^ msg))
let of_cstruct_exn cs =
if Cstruct.length cs <> 6 then
raise (Macaddr.Parse_error ("MAC is exactly 6 bytes", Cstruct.to_string cs))
else Cstruct.to_string cs |> Macaddr.of_octets_exn
let of_cstruct cs = try_with_result of_cstruct_exn cs
let write_cstruct_exn (mac : Macaddr.t) cs =
let len = Cstruct.length cs in
let mac = Macaddr.to_octets mac in
if len <> 6 then raise (Macaddr.Parse_error ("MAC is exactly 6 bytes", mac));
Cstruct.blit_from_string mac 0 cs 0 6
let to_cstruct ?(allocator = Cstruct.create) mac =
let cs = allocator 6 in
write_cstruct_exn mac cs;
cs
|
|
58540da16b4b3f11b05fcd410a6f508d7310ff65ac06c6225c8156c3debe5770 | avsm/platform | posix.mli |
RE - A regular expression library
Copyright ( C ) 2001
email :
This library is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation , with
linking exception ; either version 2.1 of the License , or ( at
your option ) any later version .
This library is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA
RE - A regular expression library
Copyright (C) 2001 Jerome Vouillon
email:
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, with
linking exception; either version 2.1 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*)
*
References :
- { { : } re }
- { { : } regcomp }
Example of how to use this module ( to parse some IRC logs ):
{ [
type msg = {
time : string ;
author : string ;
content : string ;
}
let re = Core.compile ( " ( [ ^:].*:[^:]*:[^:]{2})<.([^>]+ ) > ( .+)$ " )
( * parse a line
References:
- {{: } re}
- {{: } regcomp}
Example of how to use this module (to parse some IRC logs):
{[
type msg = {
time:string;
author:string;
content:string;
}
let re = Core.compile (Re_posix.re "([^:].*:[^:]*:[^:]{2})<.([^>]+)> (.+)$")
(* parse a line *)
let match_line line =
try
let substrings = Core.exec re line in
let groups = Core.get_all substrings in
(* groups can be obtained directly by index within [substrings] *)
Some {time=groups.(1); author=groups.(2); content=groups.(3)}
with Not_found ->
None (* regex didn't match *)
]}
*)
(** XXX Character classes *)
exception Parse_error
exception Not_supported
(** Errors that can be raised during the parsing of the regular expression *)
type opt = [`ICase | `NoSub | `Newline]
val re : ?opts:(opt list) -> string -> Core.t
* Parsing of a extended regular expression
val compile : Core.t -> Core.re
(** Regular expression compilation *)
val compile_pat : ?opts:(opt list) -> string -> Core.re
(** [compile r] is defined as [Core.compile (Core.longest r)] *)
Deviation from the standard / ambiguities in the standard
---------------------------------------------------------
We tested the behavior of the Linux library ( glibc ) and the Solaris
library .
( 1 ) An expression [ efg ] should be parsed as [ ( ef)g ] .
All implementations parse it as [ e(fg ) ] .
( 2 ) When matching the pattern " ( ( a)|b ) * " against the string " ab " ,
the sub - expression " ( ( a)|b ) " should match " b " , and the
sub - expression " ( a ) " should not match anything .
In both implementation , the sub - expression " ( a ) " matches " a " .
( 3 ) When matching the pattern " ( aa ? ) * " against the string " aaa " , it is
not clear whether the final match of the sub - expression " ( aa ? ) " is
the last " a " ( all matches of the sub - expression are successively
maximized ) , or " aa " ( the final match is maximized ) .
Both implementations implements the first case .
( 4 ) When matching the pattern " ( ( a?)|b ) * " against the string " ab " ,
the sub - expression " ( ( a?)|b ) " should match the empty string at the
end of the string ( it is better to match the empty string than to
match nothing ) .
In both implementations , this sub - expression matches " b " .
( Strangely , in the Linux implementation , the sub - expression " ( a ? ) "
correctly matches the empty string at the end of the string )
This library behaves the same way as the other libraries for all
points , except for ( 2 ) and ( 4 ) where it follows the standard .
The behavior of this library in theses four cases may change in future
releases .
Deviation from the standard / ambiguities in the standard
---------------------------------------------------------
We tested the behavior of the Linux library (glibc) and the Solaris
library.
(1) An expression [efg] should be parsed as [(ef)g].
All implementations parse it as [e(fg)].
(2) When matching the pattern "((a)|b)*" against the string "ab",
the sub-expression "((a)|b)" should match "b", and the
sub-expression "(a)" should not match anything.
In both implementation, the sub-expression "(a)" matches "a".
(3) When matching the pattern "(aa?)*" against the string "aaa", it is
not clear whether the final match of the sub-expression "(aa?)" is
the last "a" (all matches of the sub-expression are successively
maximized), or "aa" (the final match is maximized).
Both implementations implements the first case.
(4) When matching the pattern "((a?)|b)*" against the string "ab",
the sub-expression "((a?)|b)" should match the empty string at the
end of the string (it is better to match the empty string than to
match nothing).
In both implementations, this sub-expression matches "b".
(Strangely, in the Linux implementation, the sub-expression "(a?)"
correctly matches the empty string at the end of the string)
This library behaves the same way as the other libraries for all
points, except for (2) and (4) where it follows the standard.
The behavior of this library in theses four cases may change in future
releases.
*)
| null | https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/re.1.9.0/lib/posix.mli | ocaml | parse a line
groups can be obtained directly by index within [substrings]
regex didn't match
* XXX Character classes
* Errors that can be raised during the parsing of the regular expression
* Regular expression compilation
* [compile r] is defined as [Core.compile (Core.longest r)] |
RE - A regular expression library
Copyright ( C ) 2001
email :
This library is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation , with
linking exception ; either version 2.1 of the License , or ( at
your option ) any later version .
This library is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA
RE - A regular expression library
Copyright (C) 2001 Jerome Vouillon
email:
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, with
linking exception; either version 2.1 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*)
*
References :
- { { : } re }
- { { : } regcomp }
Example of how to use this module ( to parse some IRC logs ):
{ [
type msg = {
time : string ;
author : string ;
content : string ;
}
let re = Core.compile ( " ( [ ^:].*:[^:]*:[^:]{2})<.([^>]+ ) > ( .+)$ " )
( * parse a line
References:
- {{: } re}
- {{: } regcomp}
Example of how to use this module (to parse some IRC logs):
{[
type msg = {
time:string;
author:string;
content:string;
}
let re = Core.compile (Re_posix.re "([^:].*:[^:]*:[^:]{2})<.([^>]+)> (.+)$")
let match_line line =
try
let substrings = Core.exec re line in
let groups = Core.get_all substrings in
Some {time=groups.(1); author=groups.(2); content=groups.(3)}
with Not_found ->
]}
*)
exception Parse_error
exception Not_supported
type opt = [`ICase | `NoSub | `Newline]
val re : ?opts:(opt list) -> string -> Core.t
* Parsing of a extended regular expression
val compile : Core.t -> Core.re
val compile_pat : ?opts:(opt list) -> string -> Core.re
Deviation from the standard / ambiguities in the standard
---------------------------------------------------------
We tested the behavior of the Linux library ( glibc ) and the Solaris
library .
( 1 ) An expression [ efg ] should be parsed as [ ( ef)g ] .
All implementations parse it as [ e(fg ) ] .
( 2 ) When matching the pattern " ( ( a)|b ) * " against the string " ab " ,
the sub - expression " ( ( a)|b ) " should match " b " , and the
sub - expression " ( a ) " should not match anything .
In both implementation , the sub - expression " ( a ) " matches " a " .
( 3 ) When matching the pattern " ( aa ? ) * " against the string " aaa " , it is
not clear whether the final match of the sub - expression " ( aa ? ) " is
the last " a " ( all matches of the sub - expression are successively
maximized ) , or " aa " ( the final match is maximized ) .
Both implementations implements the first case .
( 4 ) When matching the pattern " ( ( a?)|b ) * " against the string " ab " ,
the sub - expression " ( ( a?)|b ) " should match the empty string at the
end of the string ( it is better to match the empty string than to
match nothing ) .
In both implementations , this sub - expression matches " b " .
( Strangely , in the Linux implementation , the sub - expression " ( a ? ) "
correctly matches the empty string at the end of the string )
This library behaves the same way as the other libraries for all
points , except for ( 2 ) and ( 4 ) where it follows the standard .
The behavior of this library in theses four cases may change in future
releases .
Deviation from the standard / ambiguities in the standard
---------------------------------------------------------
We tested the behavior of the Linux library (glibc) and the Solaris
library.
(1) An expression [efg] should be parsed as [(ef)g].
All implementations parse it as [e(fg)].
(2) When matching the pattern "((a)|b)*" against the string "ab",
the sub-expression "((a)|b)" should match "b", and the
sub-expression "(a)" should not match anything.
In both implementation, the sub-expression "(a)" matches "a".
(3) When matching the pattern "(aa?)*" against the string "aaa", it is
not clear whether the final match of the sub-expression "(aa?)" is
the last "a" (all matches of the sub-expression are successively
maximized), or "aa" (the final match is maximized).
Both implementations implements the first case.
(4) When matching the pattern "((a?)|b)*" against the string "ab",
the sub-expression "((a?)|b)" should match the empty string at the
end of the string (it is better to match the empty string than to
match nothing).
In both implementations, this sub-expression matches "b".
(Strangely, in the Linux implementation, the sub-expression "(a?)"
correctly matches the empty string at the end of the string)
This library behaves the same way as the other libraries for all
points, except for (2) and (4) where it follows the standard.
The behavior of this library in theses four cases may change in future
releases.
*)
|
b64d45913254978cd7bdf8956234998eecc020cd9ce1fbb29b09cd43d7e05982 | static-analysis-engineering/codehawk | cCHDsAssumption.ml | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk C Analyzer
Author : ------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2019 Kestrel Technology LLC
Copyright ( c ) 2020 ( c ) 2021 Aarno Labs LLC
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
, 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 .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk C Analyzer
Author: Henny Sipma
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2019 Kestrel Technology LLC
Copyright (c) 2020 Henny Sipma
Copyright (c) 2021 Aarno Labs LLC
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.
============================================================================= *)
chlib
open CHPretty
(* chutil *)
open CHPrettyUtil
open CHXmlDocument
(* cchlib *)
open CCHBasicTypes
open CCHLibTypes
open CCHUtilities
cchpre
open CCHPODictionary
open CCHProofObligation
open CCHPreTypes
let pd = CCHPredicateDictionary.predicate_dictionary
let write_xml_dependent_proof_obligations
(node:xml_element_int) (l:string list) =
let l = List.sort Stdlib.compare l in
node#appendChildren
(List.map (fun i ->
let iNode = xmlElement "po" in
begin iNode#setAttribute "id" i; iNode end) l)
class ds_assumption_t ?(pos=[]) (index:int):ds_assumption_int =
object (self)
val mutable dependent_ppos = List.filter (fun i -> i > 0) pos
val mutable dependent_spos = List.filter (fun i -> i < 0) pos
method add_dependents (pos:int list) =
begin
dependent_ppos <- (List.filter (fun i -> i > 0) pos) @ dependent_ppos ;
dependent_spos <- (List.filter (fun i -> i < 0) pos) @ dependent_spos
end
method index = index
method get_predicate = pd#get_po_predicate index
method get_dependent_ppos = dependent_ppos
method get_dependent_spos = dependent_spos
method write_xml (node:xml_element_int) =
let set = node#setAttribute in
let seti = node#setIntAttribute in
begin
(if (List.length dependent_ppos) > 0 then
set "ppos" (String.concat "," (List.map string_of_int dependent_ppos)));
(if (List.length dependent_spos) > 0 then
let spos = List.map (fun i -> (-i)) dependent_spos in
set "spos" (String.concat "," (List.map string_of_int spos)));
seti "ipr" index
end
end
let mk_ds_assumption ?(pos=[]) (index:int):ds_assumption_int =
new ds_assumption_t ~pos index
let read_xml_ds_assumption (node:xml_element_int) =
let get = node#getAttribute in
let geti = node#getIntAttribute in
let has = node#hasNamedAttribute in
let index = geti "ipr" in
let ppos =
if has "ppos" then
List.map int_of_string (nsplit ',' (get "ppos"))
else
[] in
let spos =
if has "spos" then
List.map int_of_string (nsplit ',' (get "spos"))
else
[] in
let spos = List.map (fun i -> (-i)) spos in
mk_ds_assumption ~pos:(ppos@spos) index
| null | https://raw.githubusercontent.com/static-analysis-engineering/codehawk/f2891d9120d5a776ea9ac1feec7bf98cce335e12/CodeHawk/CHC/cchpre/cCHDsAssumption.ml | ocaml | chutil
cchlib | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk C Analyzer
Author : ------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2019 Kestrel Technology LLC
Copyright ( c ) 2020 ( c ) 2021 Aarno Labs LLC
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
, 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 .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk C Analyzer
Author: Henny Sipma
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2019 Kestrel Technology LLC
Copyright (c) 2020 Henny Sipma
Copyright (c) 2021 Aarno Labs LLC
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.
============================================================================= *)
chlib
open CHPretty
open CHPrettyUtil
open CHXmlDocument
open CCHBasicTypes
open CCHLibTypes
open CCHUtilities
cchpre
open CCHPODictionary
open CCHProofObligation
open CCHPreTypes
let pd = CCHPredicateDictionary.predicate_dictionary
let write_xml_dependent_proof_obligations
(node:xml_element_int) (l:string list) =
let l = List.sort Stdlib.compare l in
node#appendChildren
(List.map (fun i ->
let iNode = xmlElement "po" in
begin iNode#setAttribute "id" i; iNode end) l)
class ds_assumption_t ?(pos=[]) (index:int):ds_assumption_int =
object (self)
val mutable dependent_ppos = List.filter (fun i -> i > 0) pos
val mutable dependent_spos = List.filter (fun i -> i < 0) pos
method add_dependents (pos:int list) =
begin
dependent_ppos <- (List.filter (fun i -> i > 0) pos) @ dependent_ppos ;
dependent_spos <- (List.filter (fun i -> i < 0) pos) @ dependent_spos
end
method index = index
method get_predicate = pd#get_po_predicate index
method get_dependent_ppos = dependent_ppos
method get_dependent_spos = dependent_spos
method write_xml (node:xml_element_int) =
let set = node#setAttribute in
let seti = node#setIntAttribute in
begin
(if (List.length dependent_ppos) > 0 then
set "ppos" (String.concat "," (List.map string_of_int dependent_ppos)));
(if (List.length dependent_spos) > 0 then
let spos = List.map (fun i -> (-i)) dependent_spos in
set "spos" (String.concat "," (List.map string_of_int spos)));
seti "ipr" index
end
end
let mk_ds_assumption ?(pos=[]) (index:int):ds_assumption_int =
new ds_assumption_t ~pos index
let read_xml_ds_assumption (node:xml_element_int) =
let get = node#getAttribute in
let geti = node#getIntAttribute in
let has = node#hasNamedAttribute in
let index = geti "ipr" in
let ppos =
if has "ppos" then
List.map int_of_string (nsplit ',' (get "ppos"))
else
[] in
let spos =
if has "spos" then
List.map int_of_string (nsplit ',' (get "spos"))
else
[] in
let spos = List.map (fun i -> (-i)) spos in
mk_ds_assumption ~pos:(ppos@spos) index
|
70994c098963d1380cfc925d702d6d2f28f3c8f569a87f5326ebf52819d117d9 | weblocks-framework/weblocks | tableview.lisp |
(in-package :weblocks)
(export '(table table-view table-scaffold table-view-default-summary
table-view-header-row-prefix-fn
table-view-header-row-suffix-fn table-view-field
with-table-view-header with-table-view-header-row
render-table-view-header-row render-view-field-header
render-view-field-header-value with-table-view-body-row
render-table-view-body-row))
;;; Table view
(defclass table-view (sequence-view)
((default-summary :initform nil
:initarg :summary
:accessor table-view-default-summary
:documentation "A summary string to be used for
the table if no :summary keyword is provided.")
(header-row-prefix-fn :initform nil
:initarg :header-row-prefix-fn
:accessor table-view-header-row-prefix-fn
:documentation "A function called prior to
rendering the table header row. The function
should expect the view object, the object
being rendered, and any additional arguments
passed to the view.")
(header-row-suffix-fn :initform nil
:initarg :header-row-suffix-fn
:accessor table-view-header-row-suffix-fn
:documentation "A function called after
rendering the header row. The function should
expect the view object, the object being
rendered, and any additional arguments passed
to the view.")
(field-sorter
:initform nil
:initarg :sort-fields-by
:accessor table-view-field-sorter))
(:documentation "A view designed to present sequences of object in a
table to the user."))
;;; Table view field
(defclass table-view-field (sequence-view-field)
((presentation :initform (make-instance 'text-presentation)))
(:documentation "A field class representing a column in the table
view."))
;;; Make scaffolding system happy
(defclass table-scaffold (sequence-scaffold)
())
...
(defmethod view-default-field-type ((view-type (eql 'table)) (field-type (eql 'mixin)))
'mixin-sequence)
;; Table heading
(defmethod with-view-header ((view table-view) obj widget body-fn &rest args &key
(fields-prefix-fn (view-fields-default-prefix-fn view))
(fields-suffix-fn (view-fields-default-suffix-fn view))
&allow-other-keys)
(let* ((object-name (object-class-name (car obj)))
(header-class (format nil "view table ~A"
(if (eql object-name 'null)
"empty"
(attributize-name object-name)))))
(with-html
(:div :class header-class
(with-extra-tags
(safe-apply fields-prefix-fn view obj args)
(apply body-fn view obj args)
(safe-apply fields-suffix-fn view obj args))))))
(defun table-view-header-wt (&key caption summary header-content content)
(with-html-to-string
(:table :summary summary
(when caption
(htm (:caption (str caption))))
(htm
(:thead
(str header-content))
(:tbody
(str content))))))
(deftemplate :table-view-header-wt 'table-view-header-wt)
(defgeneric with-table-view-header (view obj widget header-fn rows-fn &rest args
&key summary &allow-other-keys)
(:documentation "Table specific header responsible for rendering
table, thead, and tbody HTML.")
(:method ((view table-view) obj widget header-fn rows-fn &rest args
&key summary &allow-other-keys)
(render-wt
:table-view-header-wt
(list :view view :object obj :widget widget)
:caption (view-caption view)
:summary (or summary (table-view-default-summary view))
:header-content (capture-weblocks-output (apply header-fn view (car obj) widget args))
:content (capture-weblocks-output (apply rows-fn view obj widget args)))))
(defun table-header-row-wt (&key suffix content prefix)
(with-html-to-string
(str suffix)
(:tr (str content))
(str prefix)))
(deftemplate :table-header-row-wt 'table-header-row-wt)
;; Table header row
(defgeneric with-table-view-header-row (view obj widget &rest args)
(:documentation
"Used by table view to render header rows. This functions calls
'render-table-view-header-row' to render the header cells. Specialize
this function to modify HTML around a given header row's cells.")
(:method ((view table-view) obj widget &rest args)
(render-wt
:table-header-row-wt
(list :view view :object obj :widget widget)
:suffix (capture-weblocks-output (safe-apply (table-view-header-row-prefix-fn view) view obj args))
:content (capture-weblocks-output (apply #'render-table-view-header-row view obj widget args))
:prefix (capture-weblocks-output (safe-apply (table-view-header-row-suffix-fn view) view obj args)))))
(defgeneric render-table-view-header-row (view obj widget &rest args)
(:documentation
"Renders the row in the 'thead' element of the table. The default
implementation uses 'render-view-field-header' to render particular
cells. Specialize this method to achieve customized header row
rendering.")
(:method ((view table-view) obj widget &rest args)
(apply #'map-sorted-view-fields
(lambda (field-info)
(let ((field (field-info-field field-info))
(obj (field-info-object field-info)))
(apply #'render-view-field-header
field view widget (view-field-presentation field)
(obtain-view-field-value field obj) obj
:field-info field-info
args)))
view obj (table-view-field-sorter view) args)))
(defun table-view-field-header-wt (&key row-class label)
(with-html-to-string
(:th :class row-class
(:span :class "label" (str label)))))
(deftemplate :table-view-field-header-wt 'table-view-field-header-wt)
(defgeneric render-view-field-header (field view widget presentation value obj &rest args
&key field-info &allow-other-keys)
(:documentation "Renders a table header cell.")
(:method ((field table-view-field) (view table-view) widget presentation value obj &rest args
&key field-info &allow-other-keys)
(render-wt
:table-view-field-header-wt
(list :view view :field field :widget widget :presentation presentation :object obj)
:row-class (if field-info
(attributize-view-field-name field-info)
(attributize-name (view-field-slot-name field)))
:label (translate (view-field-label field)))))
(defun table-view-body-row-wt (&key prefix suffix row-class content)
(with-html-to-string
(str prefix)
(:tr :class row-class
(str content))
(str suffix)))
(deftemplate :table-view-body-row-wt 'table-view-body-row-wt)
;; Table body
(defgeneric with-table-view-body-row (view obj widget &rest args &key alternp &allow-other-keys)
(:documentation
"Used by table view to render body rows. Specialize this function
to modify HTML around a given row's cells.")
(:method ((view table-view) obj widget &rest args &key alternp &allow-other-keys)
(render-wt
:table-view-body-row-wt
(list :view view :widget widget :object obj)
:content (capture-weblocks-output (apply #'render-table-view-body-row view obj widget args))
:prefix (capture-weblocks-output (safe-apply (sequence-view-row-prefix-fn view) view obj args))
:row-class (if alternp "altern" nil)
:suffix (capture-weblocks-output (safe-apply (sequence-view-row-suffix-fn view) view obj args)))))
(defgeneric render-table-view-body-row (view obj widget &rest args)
(:documentation
"Renders the rows in the 'tbody' element of the table. The
default implementation uses 'render-table-body-cell' to render
particular cells. See 'render-table-header-row' for more
details.")
(:method ((view table-view) obj widget &rest args)
(apply #'map-sorted-view-fields
(lambda (field-info)
(let ((field (field-info-field field-info))
(obj (field-info-object field-info)))
(safe-apply (view-field-prefix-fn field) view field obj args)
(apply #'render-view-field
field view widget (view-field-presentation field)
(obtain-view-field-value field obj) obj
:field-info field-info
args)
(safe-apply (view-field-suffix-fn field) view field obj args)))
view obj (table-view-field-sorter view) args)))
(defun table-view-body-row-cell-wt (&key class content)
(with-html-to-string
(:td :class class
(str content))))
(deftemplate :table-view-body-row-cell-wt 'table-view-body-row-cell-wt)
(defmethod render-view-field ((field table-view-field) (view table-view)
widget presentation value obj
&rest args
&key field-info &allow-other-keys)
(render-wt
:table-view-body-row-cell-wt
(list :view view :widget widget :object obj)
:class (if field-info
(attributize-view-field-name field-info)
(attributize-name (view-field-slot-name field)))
:content (capture-weblocks-output
(apply #'render-view-field-value value presentation field view widget obj args))))
;; The table itself
(defmethod render-object-view-impl ((obj sequence) (view table-view) widget &rest args &key
(fields-prefix-fn (view-fields-default-prefix-fn view))
(fields-suffix-fn (view-fields-default-suffix-fn view))
&allow-other-keys)
(apply #'with-view-header view obj widget
(lambda (view obj &rest args)
(apply #'with-table-view-header view obj widget
(lambda (view obj widget &rest args)
(safe-apply fields-prefix-fn view obj args)
(apply #'with-table-view-header-row view obj widget args))
(lambda (view obj widget &rest args)
(let ((row-num -1))
(mapc (lambda (obj)
(apply #'with-table-view-body-row view obj
widget
:alternp (oddp (incf row-num))
args))
obj))
(safe-apply fields-suffix-fn view obj args))
args))
args))
| null | https://raw.githubusercontent.com/weblocks-framework/weblocks/fe96152458c8eb54d74751b3201db42dafe1708b/src/views/tableview.lisp | lisp | Table view
Table view field
Make scaffolding system happy
Table heading
Table header row
Table body
The table itself |
(in-package :weblocks)
(export '(table table-view table-scaffold table-view-default-summary
table-view-header-row-prefix-fn
table-view-header-row-suffix-fn table-view-field
with-table-view-header with-table-view-header-row
render-table-view-header-row render-view-field-header
render-view-field-header-value with-table-view-body-row
render-table-view-body-row))
(defclass table-view (sequence-view)
((default-summary :initform nil
:initarg :summary
:accessor table-view-default-summary
:documentation "A summary string to be used for
the table if no :summary keyword is provided.")
(header-row-prefix-fn :initform nil
:initarg :header-row-prefix-fn
:accessor table-view-header-row-prefix-fn
:documentation "A function called prior to
rendering the table header row. The function
should expect the view object, the object
being rendered, and any additional arguments
passed to the view.")
(header-row-suffix-fn :initform nil
:initarg :header-row-suffix-fn
:accessor table-view-header-row-suffix-fn
:documentation "A function called after
rendering the header row. The function should
expect the view object, the object being
rendered, and any additional arguments passed
to the view.")
(field-sorter
:initform nil
:initarg :sort-fields-by
:accessor table-view-field-sorter))
(:documentation "A view designed to present sequences of object in a
table to the user."))
(defclass table-view-field (sequence-view-field)
((presentation :initform (make-instance 'text-presentation)))
(:documentation "A field class representing a column in the table
view."))
(defclass table-scaffold (sequence-scaffold)
())
...
(defmethod view-default-field-type ((view-type (eql 'table)) (field-type (eql 'mixin)))
'mixin-sequence)
(defmethod with-view-header ((view table-view) obj widget body-fn &rest args &key
(fields-prefix-fn (view-fields-default-prefix-fn view))
(fields-suffix-fn (view-fields-default-suffix-fn view))
&allow-other-keys)
(let* ((object-name (object-class-name (car obj)))
(header-class (format nil "view table ~A"
(if (eql object-name 'null)
"empty"
(attributize-name object-name)))))
(with-html
(:div :class header-class
(with-extra-tags
(safe-apply fields-prefix-fn view obj args)
(apply body-fn view obj args)
(safe-apply fields-suffix-fn view obj args))))))
(defun table-view-header-wt (&key caption summary header-content content)
(with-html-to-string
(:table :summary summary
(when caption
(htm (:caption (str caption))))
(htm
(:thead
(str header-content))
(:tbody
(str content))))))
(deftemplate :table-view-header-wt 'table-view-header-wt)
(defgeneric with-table-view-header (view obj widget header-fn rows-fn &rest args
&key summary &allow-other-keys)
(:documentation "Table specific header responsible for rendering
table, thead, and tbody HTML.")
(:method ((view table-view) obj widget header-fn rows-fn &rest args
&key summary &allow-other-keys)
(render-wt
:table-view-header-wt
(list :view view :object obj :widget widget)
:caption (view-caption view)
:summary (or summary (table-view-default-summary view))
:header-content (capture-weblocks-output (apply header-fn view (car obj) widget args))
:content (capture-weblocks-output (apply rows-fn view obj widget args)))))
(defun table-header-row-wt (&key suffix content prefix)
(with-html-to-string
(str suffix)
(:tr (str content))
(str prefix)))
(deftemplate :table-header-row-wt 'table-header-row-wt)
(defgeneric with-table-view-header-row (view obj widget &rest args)
(:documentation
"Used by table view to render header rows. This functions calls
'render-table-view-header-row' to render the header cells. Specialize
this function to modify HTML around a given header row's cells.")
(:method ((view table-view) obj widget &rest args)
(render-wt
:table-header-row-wt
(list :view view :object obj :widget widget)
:suffix (capture-weblocks-output (safe-apply (table-view-header-row-prefix-fn view) view obj args))
:content (capture-weblocks-output (apply #'render-table-view-header-row view obj widget args))
:prefix (capture-weblocks-output (safe-apply (table-view-header-row-suffix-fn view) view obj args)))))
(defgeneric render-table-view-header-row (view obj widget &rest args)
(:documentation
"Renders the row in the 'thead' element of the table. The default
implementation uses 'render-view-field-header' to render particular
cells. Specialize this method to achieve customized header row
rendering.")
(:method ((view table-view) obj widget &rest args)
(apply #'map-sorted-view-fields
(lambda (field-info)
(let ((field (field-info-field field-info))
(obj (field-info-object field-info)))
(apply #'render-view-field-header
field view widget (view-field-presentation field)
(obtain-view-field-value field obj) obj
:field-info field-info
args)))
view obj (table-view-field-sorter view) args)))
(defun table-view-field-header-wt (&key row-class label)
(with-html-to-string
(:th :class row-class
(:span :class "label" (str label)))))
(deftemplate :table-view-field-header-wt 'table-view-field-header-wt)
(defgeneric render-view-field-header (field view widget presentation value obj &rest args
&key field-info &allow-other-keys)
(:documentation "Renders a table header cell.")
(:method ((field table-view-field) (view table-view) widget presentation value obj &rest args
&key field-info &allow-other-keys)
(render-wt
:table-view-field-header-wt
(list :view view :field field :widget widget :presentation presentation :object obj)
:row-class (if field-info
(attributize-view-field-name field-info)
(attributize-name (view-field-slot-name field)))
:label (translate (view-field-label field)))))
(defun table-view-body-row-wt (&key prefix suffix row-class content)
(with-html-to-string
(str prefix)
(:tr :class row-class
(str content))
(str suffix)))
(deftemplate :table-view-body-row-wt 'table-view-body-row-wt)
(defgeneric with-table-view-body-row (view obj widget &rest args &key alternp &allow-other-keys)
(:documentation
"Used by table view to render body rows. Specialize this function
to modify HTML around a given row's cells.")
(:method ((view table-view) obj widget &rest args &key alternp &allow-other-keys)
(render-wt
:table-view-body-row-wt
(list :view view :widget widget :object obj)
:content (capture-weblocks-output (apply #'render-table-view-body-row view obj widget args))
:prefix (capture-weblocks-output (safe-apply (sequence-view-row-prefix-fn view) view obj args))
:row-class (if alternp "altern" nil)
:suffix (capture-weblocks-output (safe-apply (sequence-view-row-suffix-fn view) view obj args)))))
(defgeneric render-table-view-body-row (view obj widget &rest args)
(:documentation
"Renders the rows in the 'tbody' element of the table. The
default implementation uses 'render-table-body-cell' to render
particular cells. See 'render-table-header-row' for more
details.")
(:method ((view table-view) obj widget &rest args)
(apply #'map-sorted-view-fields
(lambda (field-info)
(let ((field (field-info-field field-info))
(obj (field-info-object field-info)))
(safe-apply (view-field-prefix-fn field) view field obj args)
(apply #'render-view-field
field view widget (view-field-presentation field)
(obtain-view-field-value field obj) obj
:field-info field-info
args)
(safe-apply (view-field-suffix-fn field) view field obj args)))
view obj (table-view-field-sorter view) args)))
(defun table-view-body-row-cell-wt (&key class content)
(with-html-to-string
(:td :class class
(str content))))
(deftemplate :table-view-body-row-cell-wt 'table-view-body-row-cell-wt)
(defmethod render-view-field ((field table-view-field) (view table-view)
widget presentation value obj
&rest args
&key field-info &allow-other-keys)
(render-wt
:table-view-body-row-cell-wt
(list :view view :widget widget :object obj)
:class (if field-info
(attributize-view-field-name field-info)
(attributize-name (view-field-slot-name field)))
:content (capture-weblocks-output
(apply #'render-view-field-value value presentation field view widget obj args))))
(defmethod render-object-view-impl ((obj sequence) (view table-view) widget &rest args &key
(fields-prefix-fn (view-fields-default-prefix-fn view))
(fields-suffix-fn (view-fields-default-suffix-fn view))
&allow-other-keys)
(apply #'with-view-header view obj widget
(lambda (view obj &rest args)
(apply #'with-table-view-header view obj widget
(lambda (view obj widget &rest args)
(safe-apply fields-prefix-fn view obj args)
(apply #'with-table-view-header-row view obj widget args))
(lambda (view obj widget &rest args)
(let ((row-num -1))
(mapc (lambda (obj)
(apply #'with-table-view-body-row view obj
widget
:alternp (oddp (incf row-num))
args))
obj))
(safe-apply fields-suffix-fn view obj args))
args))
args))
|
b28396bb0e5eadc21d6c9a61cd69d4cd848570bb630436d4e6982e4dcb422586 | music-suite/music-suite | Pitch.hs | # LANGUAGE FlexibleContexts #
-- | Common pitch.
module Music.Pitch.Common.Pitch
( -- * Accidentals
Accidental,
natural,
flat,
sharp,
doubleFlat,
doubleSharp,
-- ** Inspecting accidentals
isNatural,
isFlattened,
isSharpened,
isStandardAccidental,
-- ** Name
Name (..),
-- * Pitch
Pitch,
mkPitch,
name,
accidental,
-- ** Diatonic and chromatic pitch
upDiatonicP,
downDiatonicP,
upChromaticP,
downChromaticP,
invertDiatonicallyP,
invertChromaticallyP,
)
where
import Music.Pitch.Common.Internal
| null | https://raw.githubusercontent.com/music-suite/music-suite/7f01fd62334c66418043b7a2d662af127f98685d/src/Music/Pitch/Common/Pitch.hs | haskell | | Common pitch.
* Accidentals
** Inspecting accidentals
** Name
* Pitch
** Diatonic and chromatic pitch | # LANGUAGE FlexibleContexts #
module Music.Pitch.Common.Pitch
Accidental,
natural,
flat,
sharp,
doubleFlat,
doubleSharp,
isNatural,
isFlattened,
isSharpened,
isStandardAccidental,
Name (..),
Pitch,
mkPitch,
name,
accidental,
upDiatonicP,
downDiatonicP,
upChromaticP,
downChromaticP,
invertDiatonicallyP,
invertChromaticallyP,
)
where
import Music.Pitch.Common.Internal
|
c1ef7df8819c052cdf7beee15f7a2c0550ec6e5ddb8effca27ced03d572ef33f | imitator-model-checker/imitator | AlgoEFopt.ml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université Paris 13 , LIPN , CNRS , France
* Université de Lorraine , CNRS , , LORIA , Nancy , France
*
* Module description : " EF optimized " algorithm : minimization or minimization of a parameter valuation for which there exists a run leading to some states [ ABPP19 ]
*
* File contributors : * Created : 2017/05/02
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université Paris 13, LIPN, CNRS, France
* Université de Lorraine, CNRS, Inria, LORIA, Nancy, France
*
* Module description: "EF optimized" algorithm: minimization or minimization of a parameter valuation for which there exists a run leading to some states [ABPP19]
*
* File contributors : Étienne André
* Created : 2017/05/02
*
************************************************************)
(************************************************************)
(************************************************************)
(* Modules *)
(************************************************************)
(************************************************************)
open OCamlUtilities
open ImitatorUtilities
open Exceptions
open AbstractModel
open AbstractProperty
open Result
open AlgoStateBased
open Statistics
open State
(************************************************************)
(************************************************************)
(* Class definition *)
(************************************************************)
(************************************************************)
class virtual algoEFopt (state_predicate : AbstractProperty.state_predicate) (parameter_index : Automaton.parameter_index) =
object (self) inherit algoStateBased as super
(************************************************************)
(* Class variables *)
(************************************************************)
(*------------------------------------------------------------*)
(* Class "parameters" to be initialized *)
(*------------------------------------------------------------*)
val mutable synthesize_valuations : bool option = None
(*------------------------------------------------------------*)
(* Variables *)
(*------------------------------------------------------------*)
val mutable current_optimum : LinearConstraint.p_linear_constraint option = None
val mutable negated_optimum : LinearConstraint.p_linear_constraint option = None
(* Parameter valuations in all |P| dimensions for which the optimum is reached *)
val mutable current_optimum_valuations : LinearConstraint.p_nnconvex_constraint option = None
(*------------------------------------------------------------*)
(* Timing info *)
(*------------------------------------------------------------*)
Start time for t_found and t_done
Time to the first time that the target location is reached
Time to the end of the algorithm
(*------------------------------------------------------------*)
(* Shortcuts *)
(*------------------------------------------------------------*)
val parameters_to_hide =
OCamlUtilities.list_remove_first_occurence parameter_index (Input.get_model ()).parameters
(*------------------------------------------------------------*)
(* Counters *)
(*------------------------------------------------------------*)
State discarded because of a not interesting parameter constraint
val counter_discarded_state = create_discrete_counter_and_register "EFopt:state discarded" PPL_counter Verbose_low
(************************************************************)
(* Class methods *)
(************************************************************)
(*------------------------------------------------------------*)
(* Instantiating min/max *)
(*------------------------------------------------------------*)
(* Function to remove upper bounds (if minimum) or lower bounds (if maximum) *)
method virtual remove_bounds : Automaton.parameter_index list -> Automaton.parameter_index list -> LinearConstraint.p_linear_constraint -> unit
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(* Function to negate an inequality (to be defined in subclasses) *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method virtual negate_inequality : LinearConstraint.p_linear_constraint -> LinearConstraint.p_linear_constraint
(* The closed operator (>= for minimization, and <= for maximization) *)
method virtual closed_op : LinearConstraint.op
(* Various strings *)
method virtual str_optimum : string
method virtual str_upper_lower : string
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(* Variable initialization *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(* Set the `synthesize_valuations` flag (must be done right after creating the algorithm object!) *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method set_synthesize_valuations flag =
synthesize_valuations <- Some flag
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(* Shortcuts methods *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method private get_synthesize_valuations =
match synthesize_valuations with
| Some flag -> flag
| None -> raise (InternalError "Variable `synthesize_valuations` not initialized in AlgoEFopt although it should have been at this point")
method private get_current_optimum =
match current_optimum with
| Some optimum -> optimum
| None -> raise (InternalError "Variable `current_optimum` not initialized in AlgoEFopt although it should have been at this point")
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(** Compute the p-constraint of a state, projected onto the parameter to be optimized *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method private project_constraint px_constraint =
(* Project the constraint onto that parameter *)
let projected_constraint = LinearConstraint.px_hide_allclocks_and_someparameters_and_collapse parameters_to_hide px_constraint in
(* Return result *)
projected_constraint
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(** Check if goal state *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method private is_goal_state state =
(* Print some information *)
self#print_algo_message Verbose_total "Entering AlgoEFopt:is_goal_state…";
(* Check the state_predicate *)
State.match_state_predicate model.is_accepting state_predicate state
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(** Update the current optimum *)
(*** WARNING: side effect on projected_constraint ***)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method private update_optimum projected_constraint =
(* Print some information *)
if verbose_mode_greater Verbose_low then(
self#print_algo_message Verbose_medium "Associated constraint:";
self#print_algo_message Verbose_medium (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint);
self#print_algo_message Verbose_medium ("Removing " ^ self#str_upper_lower ^ " bound…");
);
Relax the constraint , i.e. , grow to infinity ( for minimization ) or to zero ( for maximization )
self#remove_bounds [parameter_index] parameters_to_hide projected_constraint;
(* Print some information *)
if verbose_mode_greater Verbose_standard then(
self#print_algo_message Verbose_low ("Updating the " ^ self#str_optimum ^ ":");
self#print_algo_message Verbose_standard (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint);
);
(* Update the min *)
current_optimum <- Some projected_constraint;
let new_negated_optimum =
try self#negate_inequality projected_constraint
with LinearConstraint.Not_an_inequality -> raise (InternalError ("Error when trying to negate an inequality: equality found! The constraint was: " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint)))
in
(* Print some information *)
if verbose_mode_greater Verbose_low then(
self#print_algo_message_newline Verbose_low ("New negated optimum: " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names new_negated_optimum));
);
(* Update the negated optimum too *)
negated_optimum <- Some new_negated_optimum
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(** Update the current optimum by updating it by union *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method private update_optimum_valuations px_constraint =
(* Get the updated optimum constraint *)
let current_optimum_constraint = self#get_current_optimum in
(* Compute the projection onto all parameters *)
let projected_constraint_onto_P = LinearConstraint.px_hide_nonparameters_and_collapse px_constraint in
(* Print some information *)
if verbose_mode_greater Verbose_high then(
self#print_algo_message_newline Verbose_high ("Considering the following constraint: " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint_onto_P));
);
Intersect with the optimum
LinearConstraint.p_intersection_assign projected_constraint_onto_P [current_optimum_constraint];
(* Print some information *)
if verbose_mode_greater Verbose_high then(
self#print_algo_message_newline Verbose_high ("After intersection with the optimum, about to add to the optimum valuations: " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint_onto_P));
);
(* Add to the collected current_optimum_constraint *)
match current_optimum_valuations with
| Some current_optimum_valuations ->
LinearConstraint.p_nnconvex_p_union_assign current_optimum_valuations projected_constraint_onto_P;
(* Print some information *)
if verbose_mode_greater Verbose_low then(
self#print_algo_message_newline Verbose_low ("New " ^ self#str_optimum ^ " constraint after addition: " ^ (LinearConstraint.string_of_p_nnconvex_constraint model.variable_names current_optimum_valuations));
);
| None -> raise (InternalError "Variable `current_optimum_valuations` not initialized in AlgoEFopt although it should have been at this point")
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(** Update the current optimum by replacing it *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method private replace_optimum_valuations px_constraint =
(* Replace the current synthesized valuations with the new ones *)
(* Get the updated optimum constraint *)
let current_optimum_constraint = self#get_current_optimum in
(* Compute the projection onto all parameters *)
let projected_constraint_onto_P = LinearConstraint.px_hide_nonparameters_and_collapse px_constraint in
Intersect with the optimum
LinearConstraint.p_intersection_assign projected_constraint_onto_P [current_optimum_constraint];
(* Replace *)
current_optimum_valuations <- Some (LinearConstraint.p_nnconvex_constraint_of_p_linear_constraint projected_constraint_onto_P);
(* Print some information *)
if verbose_mode_greater Verbose_low then(
self#print_algo_message_newline Verbose_low ("New " ^ self#str_optimum ^ " constraint after replacement: " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint_onto_P));
);
(* The end *)
()
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(** Actions to perform when trying to minimize/maximize a parameter. Returns true if the same should be kept, false if discarded. *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method private process_state (state : state) =
(* Print some information *)
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high "Entering AlgoEFopt:process_state…";
);
(* Retrieve the constraint *)
let state_location, px_constraint = state.global_location, state.px_constraint in
(* Check if an optimum constraint was defined *)
match current_optimum with
| None ->
(* Print some information *)
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high "No optimum known for now";
);
(* If goal state, update the constraint *)
let is_goal_state = self#is_goal_state state in
if is_goal_state then(
(* Compute the projection *)
let projected_constraint = self#project_constraint px_constraint in
self#print_algo_message Verbose_standard ("Found a first " ^ self#str_optimum);
self#update_optimum projected_constraint;
(* Case synthesis *)
if self#get_synthesize_valuations then(
self#replace_optimum_valuations px_constraint;
);
(* Timing info *)
if !t_found = max_float then (
t_found := time_from !t_start;
print_message Verbose_standard ("t_found: " ^ (string_of_seconds !t_found));
);
)else(
(* Print some information *)
self#print_algo_message Verbose_medium ("Not yet a goal state");
);
(* Keep the state only if not a goal state *)
(*** NOTE: here, we cannot use the optimum to update the state ***)
not is_goal_state
| Some current_optimum_constraint ->
(* Print some information *)
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high "An optimum already exists";
);
(*** NOTE: this is an expensive test, as ALL states will be projected to the goal parameters and compared to the current optimum ***)
(*** TODO: try with emptiness of intersection? ***)
let projected_constraint = self#project_constraint px_constraint in
(* Test if the current optimum is already larger *)
if LinearConstraint.p_is_leq projected_constraint current_optimum_constraint then(
(* Print some information *)
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high "The known optimum is already better than the new state: discard";
);
(* Statistics *)
counter_discarded_state#increment;
(* Flag that might be set to false in the following if condition *)
let discard = ref true in
(* Case synthesis AND goal location *)
if self#get_synthesize_valuations then(
(* Print some information *)
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high "…but since we want synthesis, still checks whether the optimum is *equal*";
self#print_algo_message Verbose_total ("About to compare:\n" ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint) ^ "\n=?=\n" ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names current_optimum_constraint) ^ "…");
);
If optimum is equal : still add the p - constraint
* * NOTE : this part is a bit technical : the current_optimum_constraint is necessarily of the form p > = n or p > n ( for EFmin ) , while the projected_constraint might be of the form p = i , or i < = p < = i ' ; if i = n then and large inequalities are used , then the projected_constraint is still as good as the current_optimum_constraint . We therefore use the function for projected_constraint . * *
(* Apply extrapolation *)
(*** WARNING: do not copy only because this object is not used anymore afterwards ***)
let projected_constraint_extrapolated = (*LinearConstraint.p_copy*) projected_constraint in
self#remove_bounds [parameter_index] [] projected_constraint_extrapolated;
(* Print some information *)
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high ("Extrapolation of the new state optimum:\n" ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint_extrapolated) ^ "");
);
if LinearConstraint.p_is_equal projected_constraint_extrapolated current_optimum_constraint then(
(* Print some information *)
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high "Known optimum equal to that of the new state";
);
(* Don't discard because the optimum is exactly equivalent to the known optimum, so there may be interesting successors (recall that the state is not necessarily a target state!) *)
discard := false;
(* If goal location: update optimum! *)
if self#is_goal_state state then(
(* Print some information *)
self#print_algo_message Verbose_medium ("This is a goal state: Update the optimum valuations");
self#update_optimum_valuations px_constraint;
(* Discard as nothing more interesting can be found that way because the state is already a target state *)
discard := true;
);
)else(
(* Print some information *)
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high "Known optimum strictly better than that of the new state: really discard";
);
(* Redundant assignment (safety) *)
discard := true;
);
);
(* Print some information *)
if verbose_mode_greater Verbose_total then(
self#print_algo_message Verbose_total ("Discard? " ^ (string_of_bool !discard));
);
(* Discard state, i.e., do not keep it; EXCEPT if synthesis AND equivalent optimum, because we can find more constraints in that direction! *)
not !discard
(* Otherwise: keep the state *)
)else(
(* If goal state, update the constraint *)
if self#is_goal_state state then(
(* Print some information *)
if verbose_mode_greater Verbose_medium then(
self#print_algo_message Verbose_medium ("Goal state found!");
self#print_algo_message_newline Verbose_medium ("Current " ^ self#str_optimum ^ ": " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names current_optimum_constraint));
self#print_algo_message_newline Verbose_medium ("New state projected constraint: " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint));
);
self#print_algo_message Verbose_standard ("Found a better " ^ self#str_optimum);
self#update_optimum projected_constraint;
(* Case synthesis *)
if self#get_synthesize_valuations then(
self#replace_optimum_valuations px_constraint;
);
(* Hack: discard the state! Since no better successor can be found *)
false
)else(
(* Print some information *)
self#print_algo_message Verbose_medium ("Not a goal state");
(* Keep the state, but add the negation of the optimum to squeeze the state space! (no need to explore the part with parameters smaller/larger than the optimum) *)
(*** NOTE: not in synthesis mode ***)
if not self#get_synthesize_valuations then(
let negated_optimum = match negated_optimum with
| Some negated_optimum -> negated_optimum
| None -> raise (InternalError("A negated optimum should be defined at that point"))
in
(* Print some information *)
if verbose_mode_greater Verbose_high then(
self#print_algo_message_newline Verbose_high ("Intersecting state with: " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names negated_optimum));
);
Intersect with side - effects
LinearConstraint.px_intersection_assign_p px_constraint [negated_optimum];
);
(* Keep the state *)
(*** NOTE: what if it becomes unsatisfiable? ***)
true
)
)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(* Add a new state to the reachability_graph (if indeed needed) *)
(* Return true if the state is not discarded by the algorithm, i.e., if it is either added OR was already present before *)
Can raise an exception TerminateAnalysis to lead to an immediate termination
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(*** TODO: return the list of actually added states ***)
method add_a_new_state source_state_index combined_transition new_state =
(* Print some information *)
if verbose_mode_greater Verbose_medium then(
self#print_algo_message Verbose_medium "Entering AlgoEFopt:add_a_new_state…";
);
(* If we have to optimize a parameter, do that now *)
let keep_processing = self#process_state new_state in
(* Print some information *)
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high ("New state to be kept? " ^ (string_of_bool keep_processing) ^ "");
);
(* Only process if we have to *)
if keep_processing then(
(* Try to add the new state to the state space *)
let addition_result = StateSpace.add_state state_space options#comparison_operator new_state in
begin
match addition_result with
(* If the state was present: do nothing *)
| StateSpace.State_already_present _ -> ()
(* If this is really a new state, or a state larger than a former state *)
| StateSpace.New_state new_state_index | StateSpace.State_replacing new_state_index ->
First check whether this is a bad tile according to the property and the nature of the state
self#update_statespace_nature new_state;
(* Will the state be added to the list of new states (the successors of which will be computed)? *)
(* Add the state_index to the list of new states (used to compute their successors at the next iteration) *)
if true then
new_states_indexes <- new_state_index :: new_states_indexes;
end (* end if new state *)
;
(*** TODO: move the rest to a higher level function? (post_from_one_state?) ***)
(* Add the transition to the state space *)
self#add_transition_to_state_space (source_state_index, combined_transition, (*** HACK ***) match addition_result with | StateSpace.State_already_present new_state_index | StateSpace.New_state new_state_index | StateSpace.State_replacing new_state_index -> new_state_index) addition_result;
(* The state is kept in any case *)
true
)else(
(* If state discarded after minimization: do not keep it *)
false
)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(** Actions to perform with the initial state; returns true unless the initial state cannot be kept (in which case the algorithm will stop immediately) *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method process_initial_state initial_state = (
(* Timing info *)
t_start := Unix.gettimeofday();
self#process_state initial_state
)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(* Actions to perform when meeting a state with no successors: nothing to do for this algorithm *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method process_deadlock_state state_index = ()
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(** Actions to perform at the end of the computation of the *successors* of post^n (i.e., when this method is called, the successors were just computed). Nothing to do for this algorithm. *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method process_post_n (post_n : State.state_index list) = ()
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(** Check whether the algorithm should terminate at the end of some post, independently of the number of states to be processed (e.g., if the constraint is already true or false) *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(*** TODO: could be stopped when the bad constraints are equal to the initial p-constraint ***)
method check_termination_at_post_n = false
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(* Method packaging the result output by the algorithm *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method compute_result =
(* Print some information *)
self#print_algo_message_newline Verbose_standard (
"Algorithm completed " ^ (after_seconds ()) ^ "."
);
(* Timing info *)
t_done := time_from !t_start;
print_message Verbose_standard ("t_done: " ^ (string_of_seconds !t_done));
let result =
(* Case synthesis: get the synthesized multidimensional constraint *)
if self#get_synthesize_valuations then (
(* Get the constraint *)
match current_optimum_valuations with
| None -> LinearConstraint.false_p_nnconvex_constraint()
| Some current_optimum_valuations ->
* * NOTE : Here , if the optimum is of the form p > = c , we need to impose p = c , as the minimization is requested * *
First get the optimum ( necessarily defined )
let current_optimum = self#get_current_optimum in
(* Get its operator and coefficient *)
let (_, op, coefficient) = try(
LinearConstraint.parameter_constraint_of_p_linear_constraint parameter_index current_optimum
) with
LinearConstraint.Not_a_1d_parameter_constraint -> raise (InternalError ("Problem when looking for a strict or non-strict optimum in AlgoEFopt:compute_result: the constraint " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names current_optimum) ^ " is not of the expected form."))
in
(* Print some information *)
if verbose_mode_greater Verbose_low then(
self#print_algo_message Verbose_low ("The almost final optimum is: " ^ (model.variable_names parameter_index) ^ " " ^ (LinearConstraint.string_of_op op) ^ " " ^ (NumConst.string_of_numconst coefficient) ^ "");
);
(* If the optimum is a >=, then convert to equality *)
if op = self#closed_op then(
(* If closed op, we need to force equality *)
(* Print some information *)
if verbose_mode_greater Verbose_low then(
self#print_algo_message Verbose_low ("Non-necessarily punctual optimum detected: restrains to equality");
);
(* Reconstruct a linear constraint param = coefficient *)
let equality_constraint = LinearConstraint.p_constraint_of_point [(parameter_index, coefficient)] in
Intersect with the optimum valuations
LinearConstraint.p_nnconvex_intersection_assign current_optimum_valuations equality_constraint;
);
(* Return the constraint *)
current_optimum_valuations
)else(
(* Otherwise get the optimum *)
(* Get the constraint *)
match current_optimum with
| None -> LinearConstraint.false_p_nnconvex_constraint()
| Some current_optimum -> LinearConstraint.p_nnconvex_constraint_of_p_linear_constraint current_optimum
)
in
(* Get the termination status *)
let termination_status = match termination_status with
| None -> raise (InternalError "Termination status not set in EFopt.compute_result")
| Some status -> status
in
Constraint is exact if termination is normal , possibly under - approximated otherwise
let soundness = if termination_status = Regular_termination then Constraint_exact else Constraint_maybe_under in
(* Return the result *)
Single_synthesis_result
{
(* Non-necessarily convex constraint guaranteeing the non-reachability of the bad location *)
result = Good_constraint (result, soundness);
English description of the constraint
constraint_description = "constraint guaranteeing " ^ self#str_optimum ^ "-parameter reachability";
(* Explored state space *)
state_space = state_space;
(* Total computation time of the algorithm *)
computation_time = time_from start_time;
(* Termination *)
termination = termination_status;
}
(************************************************************)
(************************************************************)
end;;
(************************************************************)
(************************************************************)
| null | https://raw.githubusercontent.com/imitator-model-checker/imitator/105408ae2bd8c3e3291f286e4d127defd492a58b/src/AlgoEFopt.ml | ocaml | **********************************************************
**********************************************************
Modules
**********************************************************
**********************************************************
**********************************************************
**********************************************************
Class definition
**********************************************************
**********************************************************
**********************************************************
Class variables
**********************************************************
------------------------------------------------------------
Class "parameters" to be initialized
------------------------------------------------------------
------------------------------------------------------------
Variables
------------------------------------------------------------
Parameter valuations in all |P| dimensions for which the optimum is reached
------------------------------------------------------------
Timing info
------------------------------------------------------------
------------------------------------------------------------
Shortcuts
------------------------------------------------------------
------------------------------------------------------------
Counters
------------------------------------------------------------
**********************************************************
Class methods
**********************************************************
------------------------------------------------------------
Instantiating min/max
------------------------------------------------------------
Function to remove upper bounds (if minimum) or lower bounds (if maximum)
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Function to negate an inequality (to be defined in subclasses)
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
The closed operator (>= for minimization, and <= for maximization)
Various strings
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Variable initialization
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Set the `synthesize_valuations` flag (must be done right after creating the algorithm object!)
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Shortcuts methods
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
* Compute the p-constraint of a state, projected onto the parameter to be optimized
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Project the constraint onto that parameter
Return result
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
* Check if goal state
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Print some information
Check the state_predicate
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
* Update the current optimum
** WARNING: side effect on projected_constraint **
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Print some information
Print some information
Update the min
Print some information
Update the negated optimum too
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
* Update the current optimum by updating it by union
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Get the updated optimum constraint
Compute the projection onto all parameters
Print some information
Print some information
Add to the collected current_optimum_constraint
Print some information
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
* Update the current optimum by replacing it
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Replace the current synthesized valuations with the new ones
Get the updated optimum constraint
Compute the projection onto all parameters
Replace
Print some information
The end
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
* Actions to perform when trying to minimize/maximize a parameter. Returns true if the same should be kept, false if discarded.
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Print some information
Retrieve the constraint
Check if an optimum constraint was defined
Print some information
If goal state, update the constraint
Compute the projection
Case synthesis
Timing info
Print some information
Keep the state only if not a goal state
** NOTE: here, we cannot use the optimum to update the state **
Print some information
** NOTE: this is an expensive test, as ALL states will be projected to the goal parameters and compared to the current optimum **
** TODO: try with emptiness of intersection? **
Test if the current optimum is already larger
Print some information
Statistics
Flag that might be set to false in the following if condition
Case synthesis AND goal location
Print some information
Apply extrapolation
** WARNING: do not copy only because this object is not used anymore afterwards **
LinearConstraint.p_copy
Print some information
Print some information
Don't discard because the optimum is exactly equivalent to the known optimum, so there may be interesting successors (recall that the state is not necessarily a target state!)
If goal location: update optimum!
Print some information
Discard as nothing more interesting can be found that way because the state is already a target state
Print some information
Redundant assignment (safety)
Print some information
Discard state, i.e., do not keep it; EXCEPT if synthesis AND equivalent optimum, because we can find more constraints in that direction!
Otherwise: keep the state
If goal state, update the constraint
Print some information
Case synthesis
Hack: discard the state! Since no better successor can be found
Print some information
Keep the state, but add the negation of the optimum to squeeze the state space! (no need to explore the part with parameters smaller/larger than the optimum)
** NOTE: not in synthesis mode **
Print some information
Keep the state
** NOTE: what if it becomes unsatisfiable? **
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Add a new state to the reachability_graph (if indeed needed)
Return true if the state is not discarded by the algorithm, i.e., if it is either added OR was already present before
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
** TODO: return the list of actually added states **
Print some information
If we have to optimize a parameter, do that now
Print some information
Only process if we have to
Try to add the new state to the state space
If the state was present: do nothing
If this is really a new state, or a state larger than a former state
Will the state be added to the list of new states (the successors of which will be computed)?
Add the state_index to the list of new states (used to compute their successors at the next iteration)
end if new state
** TODO: move the rest to a higher level function? (post_from_one_state?) **
Add the transition to the state space
** HACK **
The state is kept in any case
If state discarded after minimization: do not keep it
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
* Actions to perform with the initial state; returns true unless the initial state cannot be kept (in which case the algorithm will stop immediately)
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Timing info
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Actions to perform when meeting a state with no successors: nothing to do for this algorithm
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
* Actions to perform at the end of the computation of the *successors* of post^n (i.e., when this method is called, the successors were just computed). Nothing to do for this algorithm.
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
* Check whether the algorithm should terminate at the end of some post, independently of the number of states to be processed (e.g., if the constraint is already true or false)
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
** TODO: could be stopped when the bad constraints are equal to the initial p-constraint **
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Method packaging the result output by the algorithm
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Print some information
Timing info
Case synthesis: get the synthesized multidimensional constraint
Get the constraint
Get its operator and coefficient
Print some information
If the optimum is a >=, then convert to equality
If closed op, we need to force equality
Print some information
Reconstruct a linear constraint param = coefficient
Return the constraint
Otherwise get the optimum
Get the constraint
Get the termination status
Return the result
Non-necessarily convex constraint guaranteeing the non-reachability of the bad location
Explored state space
Total computation time of the algorithm
Termination
**********************************************************
**********************************************************
**********************************************************
********************************************************** | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université Paris 13 , LIPN , CNRS , France
* Université de Lorraine , CNRS , , LORIA , Nancy , France
*
* Module description : " EF optimized " algorithm : minimization or minimization of a parameter valuation for which there exists a run leading to some states [ ABPP19 ]
*
* File contributors : * Created : 2017/05/02
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université Paris 13, LIPN, CNRS, France
* Université de Lorraine, CNRS, Inria, LORIA, Nancy, France
*
* Module description: "EF optimized" algorithm: minimization or minimization of a parameter valuation for which there exists a run leading to some states [ABPP19]
*
* File contributors : Étienne André
* Created : 2017/05/02
*
************************************************************)
open OCamlUtilities
open ImitatorUtilities
open Exceptions
open AbstractModel
open AbstractProperty
open Result
open AlgoStateBased
open Statistics
open State
class virtual algoEFopt (state_predicate : AbstractProperty.state_predicate) (parameter_index : Automaton.parameter_index) =
object (self) inherit algoStateBased as super
val mutable synthesize_valuations : bool option = None
val mutable current_optimum : LinearConstraint.p_linear_constraint option = None
val mutable negated_optimum : LinearConstraint.p_linear_constraint option = None
val mutable current_optimum_valuations : LinearConstraint.p_nnconvex_constraint option = None
Start time for t_found and t_done
Time to the first time that the target location is reached
Time to the end of the algorithm
val parameters_to_hide =
OCamlUtilities.list_remove_first_occurence parameter_index (Input.get_model ()).parameters
State discarded because of a not interesting parameter constraint
val counter_discarded_state = create_discrete_counter_and_register "EFopt:state discarded" PPL_counter Verbose_low
method virtual remove_bounds : Automaton.parameter_index list -> Automaton.parameter_index list -> LinearConstraint.p_linear_constraint -> unit
method virtual negate_inequality : LinearConstraint.p_linear_constraint -> LinearConstraint.p_linear_constraint
method virtual closed_op : LinearConstraint.op
method virtual str_optimum : string
method virtual str_upper_lower : string
method set_synthesize_valuations flag =
synthesize_valuations <- Some flag
method private get_synthesize_valuations =
match synthesize_valuations with
| Some flag -> flag
| None -> raise (InternalError "Variable `synthesize_valuations` not initialized in AlgoEFopt although it should have been at this point")
method private get_current_optimum =
match current_optimum with
| Some optimum -> optimum
| None -> raise (InternalError "Variable `current_optimum` not initialized in AlgoEFopt although it should have been at this point")
method private project_constraint px_constraint =
let projected_constraint = LinearConstraint.px_hide_allclocks_and_someparameters_and_collapse parameters_to_hide px_constraint in
projected_constraint
method private is_goal_state state =
self#print_algo_message Verbose_total "Entering AlgoEFopt:is_goal_state…";
State.match_state_predicate model.is_accepting state_predicate state
method private update_optimum projected_constraint =
if verbose_mode_greater Verbose_low then(
self#print_algo_message Verbose_medium "Associated constraint:";
self#print_algo_message Verbose_medium (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint);
self#print_algo_message Verbose_medium ("Removing " ^ self#str_upper_lower ^ " bound…");
);
Relax the constraint , i.e. , grow to infinity ( for minimization ) or to zero ( for maximization )
self#remove_bounds [parameter_index] parameters_to_hide projected_constraint;
if verbose_mode_greater Verbose_standard then(
self#print_algo_message Verbose_low ("Updating the " ^ self#str_optimum ^ ":");
self#print_algo_message Verbose_standard (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint);
);
current_optimum <- Some projected_constraint;
let new_negated_optimum =
try self#negate_inequality projected_constraint
with LinearConstraint.Not_an_inequality -> raise (InternalError ("Error when trying to negate an inequality: equality found! The constraint was: " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint)))
in
if verbose_mode_greater Verbose_low then(
self#print_algo_message_newline Verbose_low ("New negated optimum: " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names new_negated_optimum));
);
negated_optimum <- Some new_negated_optimum
method private update_optimum_valuations px_constraint =
let current_optimum_constraint = self#get_current_optimum in
let projected_constraint_onto_P = LinearConstraint.px_hide_nonparameters_and_collapse px_constraint in
if verbose_mode_greater Verbose_high then(
self#print_algo_message_newline Verbose_high ("Considering the following constraint: " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint_onto_P));
);
Intersect with the optimum
LinearConstraint.p_intersection_assign projected_constraint_onto_P [current_optimum_constraint];
if verbose_mode_greater Verbose_high then(
self#print_algo_message_newline Verbose_high ("After intersection with the optimum, about to add to the optimum valuations: " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint_onto_P));
);
match current_optimum_valuations with
| Some current_optimum_valuations ->
LinearConstraint.p_nnconvex_p_union_assign current_optimum_valuations projected_constraint_onto_P;
if verbose_mode_greater Verbose_low then(
self#print_algo_message_newline Verbose_low ("New " ^ self#str_optimum ^ " constraint after addition: " ^ (LinearConstraint.string_of_p_nnconvex_constraint model.variable_names current_optimum_valuations));
);
| None -> raise (InternalError "Variable `current_optimum_valuations` not initialized in AlgoEFopt although it should have been at this point")
method private replace_optimum_valuations px_constraint =
let current_optimum_constraint = self#get_current_optimum in
let projected_constraint_onto_P = LinearConstraint.px_hide_nonparameters_and_collapse px_constraint in
Intersect with the optimum
LinearConstraint.p_intersection_assign projected_constraint_onto_P [current_optimum_constraint];
current_optimum_valuations <- Some (LinearConstraint.p_nnconvex_constraint_of_p_linear_constraint projected_constraint_onto_P);
if verbose_mode_greater Verbose_low then(
self#print_algo_message_newline Verbose_low ("New " ^ self#str_optimum ^ " constraint after replacement: " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint_onto_P));
);
()
method private process_state (state : state) =
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high "Entering AlgoEFopt:process_state…";
);
let state_location, px_constraint = state.global_location, state.px_constraint in
match current_optimum with
| None ->
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high "No optimum known for now";
);
let is_goal_state = self#is_goal_state state in
if is_goal_state then(
let projected_constraint = self#project_constraint px_constraint in
self#print_algo_message Verbose_standard ("Found a first " ^ self#str_optimum);
self#update_optimum projected_constraint;
if self#get_synthesize_valuations then(
self#replace_optimum_valuations px_constraint;
);
if !t_found = max_float then (
t_found := time_from !t_start;
print_message Verbose_standard ("t_found: " ^ (string_of_seconds !t_found));
);
)else(
self#print_algo_message Verbose_medium ("Not yet a goal state");
);
not is_goal_state
| Some current_optimum_constraint ->
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high "An optimum already exists";
);
let projected_constraint = self#project_constraint px_constraint in
if LinearConstraint.p_is_leq projected_constraint current_optimum_constraint then(
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high "The known optimum is already better than the new state: discard";
);
counter_discarded_state#increment;
let discard = ref true in
if self#get_synthesize_valuations then(
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high "…but since we want synthesis, still checks whether the optimum is *equal*";
self#print_algo_message Verbose_total ("About to compare:\n" ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint) ^ "\n=?=\n" ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names current_optimum_constraint) ^ "…");
);
If optimum is equal : still add the p - constraint
* * NOTE : this part is a bit technical : the current_optimum_constraint is necessarily of the form p > = n or p > n ( for EFmin ) , while the projected_constraint might be of the form p = i , or i < = p < = i ' ; if i = n then and large inequalities are used , then the projected_constraint is still as good as the current_optimum_constraint . We therefore use the function for projected_constraint . * *
self#remove_bounds [parameter_index] [] projected_constraint_extrapolated;
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high ("Extrapolation of the new state optimum:\n" ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint_extrapolated) ^ "");
);
if LinearConstraint.p_is_equal projected_constraint_extrapolated current_optimum_constraint then(
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high "Known optimum equal to that of the new state";
);
discard := false;
if self#is_goal_state state then(
self#print_algo_message Verbose_medium ("This is a goal state: Update the optimum valuations");
self#update_optimum_valuations px_constraint;
discard := true;
);
)else(
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high "Known optimum strictly better than that of the new state: really discard";
);
discard := true;
);
);
if verbose_mode_greater Verbose_total then(
self#print_algo_message Verbose_total ("Discard? " ^ (string_of_bool !discard));
);
not !discard
)else(
if self#is_goal_state state then(
if verbose_mode_greater Verbose_medium then(
self#print_algo_message Verbose_medium ("Goal state found!");
self#print_algo_message_newline Verbose_medium ("Current " ^ self#str_optimum ^ ": " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names current_optimum_constraint));
self#print_algo_message_newline Verbose_medium ("New state projected constraint: " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names projected_constraint));
);
self#print_algo_message Verbose_standard ("Found a better " ^ self#str_optimum);
self#update_optimum projected_constraint;
if self#get_synthesize_valuations then(
self#replace_optimum_valuations px_constraint;
);
false
)else(
self#print_algo_message Verbose_medium ("Not a goal state");
if not self#get_synthesize_valuations then(
let negated_optimum = match negated_optimum with
| Some negated_optimum -> negated_optimum
| None -> raise (InternalError("A negated optimum should be defined at that point"))
in
if verbose_mode_greater Verbose_high then(
self#print_algo_message_newline Verbose_high ("Intersecting state with: " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names negated_optimum));
);
Intersect with side - effects
LinearConstraint.px_intersection_assign_p px_constraint [negated_optimum];
);
true
)
)
Can raise an exception TerminateAnalysis to lead to an immediate termination
method add_a_new_state source_state_index combined_transition new_state =
if verbose_mode_greater Verbose_medium then(
self#print_algo_message Verbose_medium "Entering AlgoEFopt:add_a_new_state…";
);
let keep_processing = self#process_state new_state in
if verbose_mode_greater Verbose_high then(
self#print_algo_message Verbose_high ("New state to be kept? " ^ (string_of_bool keep_processing) ^ "");
);
if keep_processing then(
let addition_result = StateSpace.add_state state_space options#comparison_operator new_state in
begin
match addition_result with
| StateSpace.State_already_present _ -> ()
| StateSpace.New_state new_state_index | StateSpace.State_replacing new_state_index ->
First check whether this is a bad tile according to the property and the nature of the state
self#update_statespace_nature new_state;
if true then
new_states_indexes <- new_state_index :: new_states_indexes;
;
true
)else(
false
)
method process_initial_state initial_state = (
t_start := Unix.gettimeofday();
self#process_state initial_state
)
method process_deadlock_state state_index = ()
method process_post_n (post_n : State.state_index list) = ()
method check_termination_at_post_n = false
method compute_result =
self#print_algo_message_newline Verbose_standard (
"Algorithm completed " ^ (after_seconds ()) ^ "."
);
t_done := time_from !t_start;
print_message Verbose_standard ("t_done: " ^ (string_of_seconds !t_done));
let result =
if self#get_synthesize_valuations then (
match current_optimum_valuations with
| None -> LinearConstraint.false_p_nnconvex_constraint()
| Some current_optimum_valuations ->
* * NOTE : Here , if the optimum is of the form p > = c , we need to impose p = c , as the minimization is requested * *
First get the optimum ( necessarily defined )
let current_optimum = self#get_current_optimum in
let (_, op, coefficient) = try(
LinearConstraint.parameter_constraint_of_p_linear_constraint parameter_index current_optimum
) with
LinearConstraint.Not_a_1d_parameter_constraint -> raise (InternalError ("Problem when looking for a strict or non-strict optimum in AlgoEFopt:compute_result: the constraint " ^ (LinearConstraint.string_of_p_linear_constraint model.variable_names current_optimum) ^ " is not of the expected form."))
in
if verbose_mode_greater Verbose_low then(
self#print_algo_message Verbose_low ("The almost final optimum is: " ^ (model.variable_names parameter_index) ^ " " ^ (LinearConstraint.string_of_op op) ^ " " ^ (NumConst.string_of_numconst coefficient) ^ "");
);
if op = self#closed_op then(
if verbose_mode_greater Verbose_low then(
self#print_algo_message Verbose_low ("Non-necessarily punctual optimum detected: restrains to equality");
);
let equality_constraint = LinearConstraint.p_constraint_of_point [(parameter_index, coefficient)] in
Intersect with the optimum valuations
LinearConstraint.p_nnconvex_intersection_assign current_optimum_valuations equality_constraint;
);
current_optimum_valuations
)else(
match current_optimum with
| None -> LinearConstraint.false_p_nnconvex_constraint()
| Some current_optimum -> LinearConstraint.p_nnconvex_constraint_of_p_linear_constraint current_optimum
)
in
let termination_status = match termination_status with
| None -> raise (InternalError "Termination status not set in EFopt.compute_result")
| Some status -> status
in
Constraint is exact if termination is normal , possibly under - approximated otherwise
let soundness = if termination_status = Regular_termination then Constraint_exact else Constraint_maybe_under in
Single_synthesis_result
{
result = Good_constraint (result, soundness);
English description of the constraint
constraint_description = "constraint guaranteeing " ^ self#str_optimum ^ "-parameter reachability";
state_space = state_space;
computation_time = time_from start_time;
termination = termination_status;
}
end;;
|
4a04723a24633089e0e58c264f9eda02a6029728b06e1bfa9a4d62d7f193509c | jnoll/gantt | DateRange.hs | module DateRange where
import Parse
import Control.Monad.Reader
import Data.Time.Calendar (addDays, diffDays, addGregorianMonthsClip, addGregorianMonthsRollOver, addGregorianYearsRollOver, fromGregorian, toGregorian, gregorianMonthLength,)
import Data.Time.Calendar.WeekDate (toWeekDate)
import Data.Time.Clock (utctDay, getCurrentTime)
import Data.Time.Format (formatTime)
import Data.Time.Locale.Compat (defaultTimeLocale)
1 for Monday , 7 for Sunday
dayOfWeek :: Day -> Int
dayOfWeek d = let (_, _, n) = toWeekDate d in n
data Clipped = StartClipped | EndClipped | BothClipped | NeitherClipped | UhOh
-- calcPeriods is for calendar 'window' view, so use window start
calcPeriods :: Int -> Reader Gantt Int
calcPeriods dur = do
g <- ask
end_day <- endToDay dur
let p = inSize g
st_day = windowStart g
return $ case p of
Daily -> fromIntegral $ (+) 1 $ diffDays end_day st_day
Weekly -> ceiling $ (fromIntegral (diffDays end_day st_day)) / 7
Quarterly -> ceiling $ (fromIntegral (diffDays end_day st_day)) / 365 * 4
Yearly -> ceiling $ (fromIntegral (diffDays end_day st_day)) / 365
otherwise -> ceiling $ (fromIntegral (diffDays end_day st_day)) / 365 * 12
-- calcEnd is for calendar 'window' view, so used window start
calcEnd :: Day -> Reader Gantt Int
calcEnd day = do
g <- ask
return $ case (inSize g) of
Daily -> fromIntegral $ (+) 1 $ diffDays day (windowStart g)
Weekly -> round $ (fromIntegral (diffDays day (windowStart g))) / 7
Quarterly -> let (y, m, _) = toGregorian day
(st_y, _, _) = toGregorian (windowStart g)
in ceiling $ (fromIntegral ((((fromIntegral y) - (fromIntegral st_y)) * 12) + m)) / 3
Yearly -> let (y, m, _) = toGregorian day
(st_y, _, _) = toGregorian (windowStart g)
in (fromIntegral y) - (fromIntegral st_y)
otherwise -> let (y, m, _) = toGregorian day
(st_y, st_m, _) = toGregorian (windowStart g)
in (((fromIntegral y) - (fromIntegral st_y)) * 12) + (m - st_m + 1)
calcStart :: Day -> Reader Gantt Int
calcStart day = do
g <- ask
e <- calcEnd day
let p = inSize g
s = windowStart g
return $ case p of
Daily -> e
Weekly -> (+) 1 $ round $ (fromIntegral $ diffDays day s) / 7
otherwise -> e
convert a chart start offset into a Day . The start period is
-- actually the *end* of the previous period.
startToDay :: Int -> Reader Gantt Day
startToDay offset = do
g <- ask
return $ let offset' = toInteger (offset)
st = start g
in
case (inSize g) of
Daily -> addDays offset' st
Weekly -> addDays (toInteger (offset' * 7) + 0) st
Quarterly -> addGregorianMonthsClip (offset' * 3) st
Yearly -> addGregorianMonthsClip (offset' * 12) st
otherwise -> addGregorianMonthsClip offset' st
endOfMonth :: Day -> Day
endOfMonth day = let (y, m, _) = toGregorian day
move to end of month ; months w. less than 31 days get correct last day .
offsetToDay :: Day -> Integer -> Period -> Day
offsetToDay st offset p = case p of
Daily -> addDays offset st -- no adjustment necessary?
Weekly -> addDays ((offset * 7) + 6) st
Quarterly -> endOfMonth $ addGregorianMonthsClip (toInteger (offset * 3) - 1) st
Yearly -> endOfMonth $ addGregorianMonthsClip (toInteger (offset * 12) - 1) st
Monthly is default
Convert a chart end offset into a Day . The calculated date has to
be at the * end * of the period ( for example , 28 Feb not 1 Feb ) .
endToDay :: Int -> Reader Gantt Day
endToDay offset = do
g <- ask
let p = inSize g
st = start g
offset' = toInteger (offset - 1)
return $ offsetToDay st offset' p
before :: Day -> Day -> Bool
before a b = if diffDays a b <= 0 then True else False
after :: Day -> Day -> Bool
--after a b = if diffDays a b >= 0 then True else False
after a b = if diffDays a b > 0 then True else False
computeRange :: Day -> Day -> Day -> Day -> (Day, Day, Clipped)
computeRange s e start end
| (before s start) && (after e end) = (start, end, BothClipped)
| (before s start) && (before e end) = (start, e, StartClipped)
| (after s start) && (after e end) = (s, end, EndClipped)
| (after s start) && (before e end) = (s, e, NeitherClipped)
| otherwise = (s, e, UhOh) -- XXX should never happen
dayRange :: Int -> Int -> Reader Gantt (Maybe (Day, Day, Clipped))
dayRange s e = do
g <- ask
let start = windowStart g
end = offsetToDay start (toInteger ((windowDur g) - 1)) (inSize g)
s' <- startToDay s
e' <- endToDay e
let r = if before e' start || after s' end then Nothing
else Just $ computeRange s' e' start end
return r
msInRange :: Int -> Reader Gantt (Maybe Day)
msInRange d = do
g <- ask
let start = windowStart g
end = offsetToDay start (toInteger ((windowDur g) - 1)) (inSize g)
due <- endToDay d
return $ if after due start && before due end then Just due else Nothing
| null | https://raw.githubusercontent.com/jnoll/gantt/e7099e1786177580526d8da43d62e0182f00e681/DateRange.hs | haskell | calcPeriods is for calendar 'window' view, so use window start
calcEnd is for calendar 'window' view, so used window start
actually the *end* of the previous period.
no adjustment necessary?
after a b = if diffDays a b >= 0 then True else False
XXX should never happen | module DateRange where
import Parse
import Control.Monad.Reader
import Data.Time.Calendar (addDays, diffDays, addGregorianMonthsClip, addGregorianMonthsRollOver, addGregorianYearsRollOver, fromGregorian, toGregorian, gregorianMonthLength,)
import Data.Time.Calendar.WeekDate (toWeekDate)
import Data.Time.Clock (utctDay, getCurrentTime)
import Data.Time.Format (formatTime)
import Data.Time.Locale.Compat (defaultTimeLocale)
1 for Monday , 7 for Sunday
dayOfWeek :: Day -> Int
dayOfWeek d = let (_, _, n) = toWeekDate d in n
data Clipped = StartClipped | EndClipped | BothClipped | NeitherClipped | UhOh
calcPeriods :: Int -> Reader Gantt Int
calcPeriods dur = do
g <- ask
end_day <- endToDay dur
let p = inSize g
st_day = windowStart g
return $ case p of
Daily -> fromIntegral $ (+) 1 $ diffDays end_day st_day
Weekly -> ceiling $ (fromIntegral (diffDays end_day st_day)) / 7
Quarterly -> ceiling $ (fromIntegral (diffDays end_day st_day)) / 365 * 4
Yearly -> ceiling $ (fromIntegral (diffDays end_day st_day)) / 365
otherwise -> ceiling $ (fromIntegral (diffDays end_day st_day)) / 365 * 12
calcEnd :: Day -> Reader Gantt Int
calcEnd day = do
g <- ask
return $ case (inSize g) of
Daily -> fromIntegral $ (+) 1 $ diffDays day (windowStart g)
Weekly -> round $ (fromIntegral (diffDays day (windowStart g))) / 7
Quarterly -> let (y, m, _) = toGregorian day
(st_y, _, _) = toGregorian (windowStart g)
in ceiling $ (fromIntegral ((((fromIntegral y) - (fromIntegral st_y)) * 12) + m)) / 3
Yearly -> let (y, m, _) = toGregorian day
(st_y, _, _) = toGregorian (windowStart g)
in (fromIntegral y) - (fromIntegral st_y)
otherwise -> let (y, m, _) = toGregorian day
(st_y, st_m, _) = toGregorian (windowStart g)
in (((fromIntegral y) - (fromIntegral st_y)) * 12) + (m - st_m + 1)
calcStart :: Day -> Reader Gantt Int
calcStart day = do
g <- ask
e <- calcEnd day
let p = inSize g
s = windowStart g
return $ case p of
Daily -> e
Weekly -> (+) 1 $ round $ (fromIntegral $ diffDays day s) / 7
otherwise -> e
convert a chart start offset into a Day . The start period is
startToDay :: Int -> Reader Gantt Day
startToDay offset = do
g <- ask
return $ let offset' = toInteger (offset)
st = start g
in
case (inSize g) of
Daily -> addDays offset' st
Weekly -> addDays (toInteger (offset' * 7) + 0) st
Quarterly -> addGregorianMonthsClip (offset' * 3) st
Yearly -> addGregorianMonthsClip (offset' * 12) st
otherwise -> addGregorianMonthsClip offset' st
endOfMonth :: Day -> Day
endOfMonth day = let (y, m, _) = toGregorian day
move to end of month ; months w. less than 31 days get correct last day .
offsetToDay :: Day -> Integer -> Period -> Day
offsetToDay st offset p = case p of
Weekly -> addDays ((offset * 7) + 6) st
Quarterly -> endOfMonth $ addGregorianMonthsClip (toInteger (offset * 3) - 1) st
Yearly -> endOfMonth $ addGregorianMonthsClip (toInteger (offset * 12) - 1) st
Monthly is default
Convert a chart end offset into a Day . The calculated date has to
be at the * end * of the period ( for example , 28 Feb not 1 Feb ) .
endToDay :: Int -> Reader Gantt Day
endToDay offset = do
g <- ask
let p = inSize g
st = start g
offset' = toInteger (offset - 1)
return $ offsetToDay st offset' p
before :: Day -> Day -> Bool
before a b = if diffDays a b <= 0 then True else False
after :: Day -> Day -> Bool
after a b = if diffDays a b > 0 then True else False
computeRange :: Day -> Day -> Day -> Day -> (Day, Day, Clipped)
computeRange s e start end
| (before s start) && (after e end) = (start, end, BothClipped)
| (before s start) && (before e end) = (start, e, StartClipped)
| (after s start) && (after e end) = (s, end, EndClipped)
| (after s start) && (before e end) = (s, e, NeitherClipped)
dayRange :: Int -> Int -> Reader Gantt (Maybe (Day, Day, Clipped))
dayRange s e = do
g <- ask
let start = windowStart g
end = offsetToDay start (toInteger ((windowDur g) - 1)) (inSize g)
s' <- startToDay s
e' <- endToDay e
let r = if before e' start || after s' end then Nothing
else Just $ computeRange s' e' start end
return r
msInRange :: Int -> Reader Gantt (Maybe Day)
msInRange d = do
g <- ask
let start = windowStart g
end = offsetToDay start (toInteger ((windowDur g) - 1)) (inSize g)
due <- endToDay d
return $ if after due start && before due end then Just due else Nothing
|
be3572160d271bd3b5c7804f0afa9ccaf92b62ea5fa87a67fbee0133f9d5fd77 | monadfix/ormolu-live | NameEnv.hs |
( c ) The University of Glasgow 2006
( c ) The GRASP / AQUA Project , Glasgow University , 1992 - 1998
\section[NameEnv]{@NameEnv@ : name environments }
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[NameEnv]{@NameEnv@: name environments}
-}
# LANGUAGE CPP #
module NameEnv (
* , I d and TyVar environments ( maps )
NameEnv,
-- ** Manipulating these environments
mkNameEnv, mkNameEnvWith,
emptyNameEnv, isEmptyNameEnv,
unitNameEnv, nameEnvElts,
extendNameEnv_C, extendNameEnv_Acc, extendNameEnv,
extendNameEnvList, extendNameEnvList_C,
filterNameEnv, anyNameEnv,
plusNameEnv, plusNameEnv_C, alterNameEnv,
lookupNameEnv, lookupNameEnv_NF, delFromNameEnv, delListFromNameEnv,
elemNameEnv, mapNameEnv, disjointNameEnv,
DNameEnv,
emptyDNameEnv,
lookupDNameEnv,
delFromDNameEnv, filterDNameEnv,
mapDNameEnv,
adjustDNameEnv, alterDNameEnv, extendDNameEnv,
-- ** Dependency analysis
depAnal
) where
#include "HsVersions2.h"
import GhcPrelude
import Digraph
import Name
import UniqFM
import UniqDFM
import Maybes
{-
************************************************************************
* *
\subsection{Name environment}
* *
************************************************************************
-}
Note [ depAnal determinism ]
~~~~~~~~~~~~~~~~~~~~~~~~~~
depAnal is deterministic provided it gets the nodes in a deterministic order .
The order of lists that get_defs and get_uses return does n't matter , as these
are only used to construct the edges , and stronglyConnCompFromEdgedVertices is
deterministic even when the edges are not in deterministic order as explained
in Note [ Deterministic SCC ] in .
Note [depAnal determinism]
~~~~~~~~~~~~~~~~~~~~~~~~~~
depAnal is deterministic provided it gets the nodes in a deterministic order.
The order of lists that get_defs and get_uses return doesn't matter, as these
are only used to construct the edges, and stronglyConnCompFromEdgedVertices is
deterministic even when the edges are not in deterministic order as explained
in Note [Deterministic SCC] in Digraph.
-}
depAnal :: (node -> [Name]) -- Defs
-> (node -> [Name]) -- Uses
-> [node]
-> [SCC node]
-- Perform dependency analysis on a group of definitions,
where each definition may define more than one Name
--
The get_defs and get_uses functions are called only once per node
depAnal get_defs get_uses nodes
= stronglyConnCompFromEdgedVerticesUniq (map mk_node keyed_nodes)
where
keyed_nodes = nodes `zip` [(1::Int)..]
mk_node (node, key) =
DigraphNode node key (mapMaybe (lookupNameEnv key_map) (get_uses node))
key_map :: NameEnv Int -- Maps a Name to the key of the decl that defines it
key_map = mkNameEnv [(name,key) | (node, key) <- keyed_nodes, name <- get_defs node]
{-
************************************************************************
* *
\subsection{Name environment}
* *
************************************************************************
-}
-- | Name Environment
type NameEnv a = UniqFM a -- Domain is Name
emptyNameEnv :: NameEnv a
isEmptyNameEnv :: NameEnv a -> Bool
mkNameEnv :: [(Name,a)] -> NameEnv a
mkNameEnvWith :: (a -> Name) -> [a] -> NameEnv a
nameEnvElts :: NameEnv a -> [a]
alterNameEnv :: (Maybe a-> Maybe a) -> NameEnv a -> Name -> NameEnv a
extendNameEnv_C :: (a->a->a) -> NameEnv a -> Name -> a -> NameEnv a
extendNameEnv_Acc :: (a->b->b) -> (a->b) -> NameEnv b -> Name -> a -> NameEnv b
extendNameEnv :: NameEnv a -> Name -> a -> NameEnv a
plusNameEnv :: NameEnv a -> NameEnv a -> NameEnv a
plusNameEnv_C :: (a->a->a) -> NameEnv a -> NameEnv a -> NameEnv a
extendNameEnvList :: NameEnv a -> [(Name,a)] -> NameEnv a
extendNameEnvList_C :: (a->a->a) -> NameEnv a -> [(Name,a)] -> NameEnv a
delFromNameEnv :: NameEnv a -> Name -> NameEnv a
delListFromNameEnv :: NameEnv a -> [Name] -> NameEnv a
elemNameEnv :: Name -> NameEnv a -> Bool
unitNameEnv :: Name -> a -> NameEnv a
lookupNameEnv :: NameEnv a -> Name -> Maybe a
lookupNameEnv_NF :: NameEnv a -> Name -> a
filterNameEnv :: (elt -> Bool) -> NameEnv elt -> NameEnv elt
anyNameEnv :: (elt -> Bool) -> NameEnv elt -> Bool
mapNameEnv :: (elt1 -> elt2) -> NameEnv elt1 -> NameEnv elt2
disjointNameEnv :: NameEnv a -> NameEnv a -> Bool
nameEnvElts x = eltsUFM x
emptyNameEnv = emptyUFM
isEmptyNameEnv = isNullUFM
unitNameEnv x y = unitUFM x y
extendNameEnv x y z = addToUFM x y z
extendNameEnvList x l = addListToUFM x l
lookupNameEnv x y = lookupUFM x y
alterNameEnv = alterUFM
mkNameEnv l = listToUFM l
mkNameEnvWith f = mkNameEnv . map (\a -> (f a, a))
elemNameEnv x y = elemUFM x y
plusNameEnv x y = plusUFM x y
plusNameEnv_C f x y = plusUFM_C f x y
extendNameEnv_C f x y z = addToUFM_C f x y z
mapNameEnv f x = mapUFM f x
extendNameEnv_Acc x y z a b = addToUFM_Acc x y z a b
extendNameEnvList_C x y z = addListToUFM_C x y z
delFromNameEnv x y = delFromUFM x y
delListFromNameEnv x y = delListFromUFM x y
filterNameEnv x y = filterUFM x y
anyNameEnv f x = foldUFM ((||) . f) False x
disjointNameEnv x y = isNullUFM (intersectUFM x y)
lookupNameEnv_NF env n = expectJust "lookupNameEnv_NF" (lookupNameEnv env n)
-- | Deterministic Name Environment
--
-- See Note [Deterministic UniqFM] in UniqDFM for explanation why we need
DNameEnv .
type DNameEnv a = UniqDFM a
emptyDNameEnv :: DNameEnv a
emptyDNameEnv = emptyUDFM
lookupDNameEnv :: DNameEnv a -> Name -> Maybe a
lookupDNameEnv = lookupUDFM
delFromDNameEnv :: DNameEnv a -> Name -> DNameEnv a
delFromDNameEnv = delFromUDFM
filterDNameEnv :: (a -> Bool) -> DNameEnv a -> DNameEnv a
filterDNameEnv = filterUDFM
mapDNameEnv :: (a -> b) -> DNameEnv a -> DNameEnv b
mapDNameEnv = mapUDFM
adjustDNameEnv :: (a -> a) -> DNameEnv a -> Name -> DNameEnv a
adjustDNameEnv = adjustUDFM
alterDNameEnv :: (Maybe a -> Maybe a) -> DNameEnv a -> Name -> DNameEnv a
alterDNameEnv = alterUDFM
extendDNameEnv :: DNameEnv a -> Name -> a -> DNameEnv a
extendDNameEnv = addToUDFM
| null | https://raw.githubusercontent.com/monadfix/ormolu-live/d8ae72ef168b98a8d179d642f70352c88b3ac226/ghc-lib-parser-8.10.1.20200412/compiler/basicTypes/NameEnv.hs | haskell | ** Manipulating these environments
** Dependency analysis
************************************************************************
* *
\subsection{Name environment}
* *
************************************************************************
Defs
Uses
Perform dependency analysis on a group of definitions,
Maps a Name to the key of the decl that defines it
************************************************************************
* *
\subsection{Name environment}
* *
************************************************************************
| Name Environment
Domain is Name
| Deterministic Name Environment
See Note [Deterministic UniqFM] in UniqDFM for explanation why we need |
( c ) The University of Glasgow 2006
( c ) The GRASP / AQUA Project , Glasgow University , 1992 - 1998
\section[NameEnv]{@NameEnv@ : name environments }
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[NameEnv]{@NameEnv@: name environments}
-}
# LANGUAGE CPP #
module NameEnv (
* , I d and TyVar environments ( maps )
NameEnv,
mkNameEnv, mkNameEnvWith,
emptyNameEnv, isEmptyNameEnv,
unitNameEnv, nameEnvElts,
extendNameEnv_C, extendNameEnv_Acc, extendNameEnv,
extendNameEnvList, extendNameEnvList_C,
filterNameEnv, anyNameEnv,
plusNameEnv, plusNameEnv_C, alterNameEnv,
lookupNameEnv, lookupNameEnv_NF, delFromNameEnv, delListFromNameEnv,
elemNameEnv, mapNameEnv, disjointNameEnv,
DNameEnv,
emptyDNameEnv,
lookupDNameEnv,
delFromDNameEnv, filterDNameEnv,
mapDNameEnv,
adjustDNameEnv, alterDNameEnv, extendDNameEnv,
depAnal
) where
#include "HsVersions2.h"
import GhcPrelude
import Digraph
import Name
import UniqFM
import UniqDFM
import Maybes
Note [ depAnal determinism ]
~~~~~~~~~~~~~~~~~~~~~~~~~~
depAnal is deterministic provided it gets the nodes in a deterministic order .
The order of lists that get_defs and get_uses return does n't matter , as these
are only used to construct the edges , and stronglyConnCompFromEdgedVertices is
deterministic even when the edges are not in deterministic order as explained
in Note [ Deterministic SCC ] in .
Note [depAnal determinism]
~~~~~~~~~~~~~~~~~~~~~~~~~~
depAnal is deterministic provided it gets the nodes in a deterministic order.
The order of lists that get_defs and get_uses return doesn't matter, as these
are only used to construct the edges, and stronglyConnCompFromEdgedVertices is
deterministic even when the edges are not in deterministic order as explained
in Note [Deterministic SCC] in Digraph.
-}
-> [node]
-> [SCC node]
where each definition may define more than one Name
The get_defs and get_uses functions are called only once per node
depAnal get_defs get_uses nodes
= stronglyConnCompFromEdgedVerticesUniq (map mk_node keyed_nodes)
where
keyed_nodes = nodes `zip` [(1::Int)..]
mk_node (node, key) =
DigraphNode node key (mapMaybe (lookupNameEnv key_map) (get_uses node))
key_map = mkNameEnv [(name,key) | (node, key) <- keyed_nodes, name <- get_defs node]
emptyNameEnv :: NameEnv a
isEmptyNameEnv :: NameEnv a -> Bool
mkNameEnv :: [(Name,a)] -> NameEnv a
mkNameEnvWith :: (a -> Name) -> [a] -> NameEnv a
nameEnvElts :: NameEnv a -> [a]
alterNameEnv :: (Maybe a-> Maybe a) -> NameEnv a -> Name -> NameEnv a
extendNameEnv_C :: (a->a->a) -> NameEnv a -> Name -> a -> NameEnv a
extendNameEnv_Acc :: (a->b->b) -> (a->b) -> NameEnv b -> Name -> a -> NameEnv b
extendNameEnv :: NameEnv a -> Name -> a -> NameEnv a
plusNameEnv :: NameEnv a -> NameEnv a -> NameEnv a
plusNameEnv_C :: (a->a->a) -> NameEnv a -> NameEnv a -> NameEnv a
extendNameEnvList :: NameEnv a -> [(Name,a)] -> NameEnv a
extendNameEnvList_C :: (a->a->a) -> NameEnv a -> [(Name,a)] -> NameEnv a
delFromNameEnv :: NameEnv a -> Name -> NameEnv a
delListFromNameEnv :: NameEnv a -> [Name] -> NameEnv a
elemNameEnv :: Name -> NameEnv a -> Bool
unitNameEnv :: Name -> a -> NameEnv a
lookupNameEnv :: NameEnv a -> Name -> Maybe a
lookupNameEnv_NF :: NameEnv a -> Name -> a
filterNameEnv :: (elt -> Bool) -> NameEnv elt -> NameEnv elt
anyNameEnv :: (elt -> Bool) -> NameEnv elt -> Bool
mapNameEnv :: (elt1 -> elt2) -> NameEnv elt1 -> NameEnv elt2
disjointNameEnv :: NameEnv a -> NameEnv a -> Bool
nameEnvElts x = eltsUFM x
emptyNameEnv = emptyUFM
isEmptyNameEnv = isNullUFM
unitNameEnv x y = unitUFM x y
extendNameEnv x y z = addToUFM x y z
extendNameEnvList x l = addListToUFM x l
lookupNameEnv x y = lookupUFM x y
alterNameEnv = alterUFM
mkNameEnv l = listToUFM l
mkNameEnvWith f = mkNameEnv . map (\a -> (f a, a))
elemNameEnv x y = elemUFM x y
plusNameEnv x y = plusUFM x y
plusNameEnv_C f x y = plusUFM_C f x y
extendNameEnv_C f x y z = addToUFM_C f x y z
mapNameEnv f x = mapUFM f x
extendNameEnv_Acc x y z a b = addToUFM_Acc x y z a b
extendNameEnvList_C x y z = addListToUFM_C x y z
delFromNameEnv x y = delFromUFM x y
delListFromNameEnv x y = delListFromUFM x y
filterNameEnv x y = filterUFM x y
anyNameEnv f x = foldUFM ((||) . f) False x
disjointNameEnv x y = isNullUFM (intersectUFM x y)
lookupNameEnv_NF env n = expectJust "lookupNameEnv_NF" (lookupNameEnv env n)
DNameEnv .
type DNameEnv a = UniqDFM a
emptyDNameEnv :: DNameEnv a
emptyDNameEnv = emptyUDFM
lookupDNameEnv :: DNameEnv a -> Name -> Maybe a
lookupDNameEnv = lookupUDFM
delFromDNameEnv :: DNameEnv a -> Name -> DNameEnv a
delFromDNameEnv = delFromUDFM
filterDNameEnv :: (a -> Bool) -> DNameEnv a -> DNameEnv a
filterDNameEnv = filterUDFM
mapDNameEnv :: (a -> b) -> DNameEnv a -> DNameEnv b
mapDNameEnv = mapUDFM
adjustDNameEnv :: (a -> a) -> DNameEnv a -> Name -> DNameEnv a
adjustDNameEnv = adjustUDFM
alterDNameEnv :: (Maybe a -> Maybe a) -> DNameEnv a -> Name -> DNameEnv a
alterDNameEnv = alterUDFM
extendDNameEnv :: DNameEnv a -> Name -> a -> DNameEnv a
extendDNameEnv = addToUDFM
|
23b1abdaccfd6893cf11744b7e077af3f76b7274405caf67b9b168f2eead5a90 | jyh/metaprl | itt_field2.mli |
* Fields .
*
* ----------------------------------------------------------------
*
* This file is part of MetaPRL , a modular , higher order
* logical framework that provides a logical programming
* environment for OCaml and other languages .
*
* See the file doc / htmlman / default.html or visit /
* for more information .
*
* Copyright ( C ) 1997 - 2004 MetaPRL Group
*
* This program is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 675 Mass Ave , Cambridge , , USA .
*
* Author :
* Email :
* Fields.
*
* ----------------------------------------------------------------
*
* This file is part of MetaPRL, a modular, higher order
* logical framework that provides a logical programming
* environment for OCaml and other languages.
*
* See the file doc/htmlman/default.html or visit /
* for more information.
*
* Copyright (C) 1997-2004 MetaPRL Group
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Author: Xin Yu
* Email :
*)
extends Itt_ring2
extends Itt_record_renaming
open Tactic_type.Tactic
(************************************************************************
* SYNTAX *
************************************************************************)
declare prefield[i:l]
declare isField{'f}
declare field[i:l]
declare carNo0{'r}
(************************************************************************
* TACTICS *
************************************************************************)
topval unfold_prefield : conv
topval unfold_isField : conv
topval unfold_field : conv
topval fold_prefield1 : conv
topval fold_prefield : conv
topval fold_isField1 : conv
topval fold_isField : conv
topval fold_field1 : conv
topval fold_field : conv
topval unfold_carNo0 : conv
(*
* -*-
* Local Variables:
* Caml-master: "editor.run"
* End:
* -*-
*)
| null | https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/theories/itt/applications/algebra/itt_field2.mli | ocaml | ***********************************************************************
* SYNTAX *
***********************************************************************
***********************************************************************
* TACTICS *
***********************************************************************
* -*-
* Local Variables:
* Caml-master: "editor.run"
* End:
* -*-
|
* Fields .
*
* ----------------------------------------------------------------
*
* This file is part of MetaPRL , a modular , higher order
* logical framework that provides a logical programming
* environment for OCaml and other languages .
*
* See the file doc / htmlman / default.html or visit /
* for more information .
*
* Copyright ( C ) 1997 - 2004 MetaPRL Group
*
* This program is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 675 Mass Ave , Cambridge , , USA .
*
* Author :
* Email :
* Fields.
*
* ----------------------------------------------------------------
*
* This file is part of MetaPRL, a modular, higher order
* logical framework that provides a logical programming
* environment for OCaml and other languages.
*
* See the file doc/htmlman/default.html or visit /
* for more information.
*
* Copyright (C) 1997-2004 MetaPRL Group
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Author: Xin Yu
* Email :
*)
extends Itt_ring2
extends Itt_record_renaming
open Tactic_type.Tactic
declare prefield[i:l]
declare isField{'f}
declare field[i:l]
declare carNo0{'r}
topval unfold_prefield : conv
topval unfold_isField : conv
topval unfold_field : conv
topval fold_prefield1 : conv
topval fold_prefield : conv
topval fold_isField1 : conv
topval fold_isField : conv
topval fold_field1 : conv
topval fold_field : conv
topval unfold_carNo0 : conv
|
b0b65cc59717606779eff5219a4c084bb19074a20d344a020282cf7d12a57f1b | lemenkov/erlrtpproxy | ser_proto.erl | %%%----------------------------------------------------------------------
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 3 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License
%%% along with this program; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
%%%
%%%----------------------------------------------------------------------
-module(ser_proto).
-author('').
-export([decode/1]).
-export([encode/1]).
-include("common.hrl").
-define(SAFE_PARTY(Val0), case Val0 of null -> null; _ -> [Val, _] = ensure_mediaid(binary_split(Val0, $;)), #party{tag = Val} end).
decode(Msg) when is_binary(Msg) ->
% Cut last \n (if exist) and drop accidental zeroes - OpenSIPs inserts
% them sometimes (bug in OpenSIPS)
[Cookie,C|Rest] = binary_split(<< <<X>> || <<X>> <= Msg, X /= 0, X /= $\n>>, $ ),
case parse_splitted([binary_to_upper(C)|Rest]) of
#cmd{} = Cmd ->
Cmd#cmd{
cookie=Cookie,
origin=#origin{
type=ser,
pid=self()
}
};
#response{} = Response ->
case Response#response.type of
stats ->
Response#response{
cookie = Cookie,
data = binary_to_list(Msg) % I contains it's own formatting
};
_ ->
Response#response{
cookie=Cookie
}
end
end.
encode({error, syntax, Msg}) when is_binary(Msg) ->
[Cookie|_] = binary_split(Msg, $ ),
<<Cookie/binary, " E1\n">>;
encode({error, software, Msg}) when is_binary(Msg) ->
[Cookie|_] = binary_split(Msg, $ ),
<<Cookie/binary, " E7\n">>;
encode(#response{cookie = Cookie, type = reply, data = ok}) ->
<<Cookie/binary, " 0\n">>;
encode(#response{cookie = Cookie, type = reply, data = {ok, {stats, Number}}}) when is_integer(Number) ->
N = list_to_binary(integer_to_list(Number)),
<<Cookie/binary, " active sessions: ", N/binary, "\n">>;
encode(#response{cookie = Cookie, type = reply, data = {ok, {stats, NumberTotal, NumberActive}}}) when is_integer(NumberTotal), is_integer(NumberActive) ->
Nt = list_to_binary(integer_to_list(NumberTotal)),
Na = list_to_binary(integer_to_list(NumberActive)),
<<Cookie/binary, " sessions created: ", Nt/binary, " active sessions: ", Na/binary, "\n">>;
encode(#response{cookie = Cookie, type = reply, data = supported}) ->
<<Cookie/binary, " 1\n">>;
encode(#response{cookie = Cookie, type = reply, data = {version, Version}}) when is_binary(Version) ->
<<Cookie/binary, " ", Version/binary, "\n">>;
encode(#response{cookie = Cookie, type = reply, data = {{{I0,I1,I2,I3} = IPv4, Port}, _}}) when
is_integer(I0), I0 >= 0, I0 < 256,
is_integer(I1), I1 >= 0, I1 < 256,
is_integer(I2), I2 >= 0, I2 < 256,
is_integer(I3), I3 >= 0, I3 < 256 ->
I = list_to_binary(inet_parse:ntoa(IPv4)),
P = list_to_binary(integer_to_list(Port)),
<<Cookie/binary, " ", P/binary, " ", I/binary, "\n">>;
encode(#response{cookie = Cookie, type = reply, data = {{{I0,I1,I2,I3,I4,I5,I6,I7} = IPv6, Port}, _}}) when
is_integer(I0), I0 >= 0, I0 < 65535,
is_integer(I1), I1 >= 0, I1 < 65535,
is_integer(I2), I2 >= 0, I2 < 65535,
is_integer(I3), I3 >= 0, I3 < 65535,
is_integer(I4), I4 >= 0, I4 < 65535,
is_integer(I5), I5 >= 0, I5 < 65535,
is_integer(I6), I6 >= 0, I6 < 65535,
is_integer(I7), I7 >= 0, I7 < 65535 ->
I = list_to_binary(inet_parse:ntoa(IPv6)),
P = list_to_binary(integer_to_list(Port)),
<<Cookie/binary, " ", P/binary, " ", I/binary, "\n">>;
encode(#response{cookie = Cookie, type = error, data = syntax}) ->
<<Cookie/binary, " E1\n">>;
encode(#response{cookie = Cookie, type = error, data = software}) ->
<<Cookie/binary, " E7\n">>;
encode(#response{cookie = Cookie, type = error, data = notfound}) ->
<<Cookie/binary, " E8\n">>;
encode(#response{} = Unknown) ->
error_logger:error_msg("Unknown response: ~p~n", [Unknown]),
throw({error_syntax, "Unknown (or unsupported) #response"});
encode(#cmd{cookie = Cookie, type = ?CMD_V}) ->
<<Cookie/binary, " V\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_VF, params = Version}) ->
<<Cookie/binary, " VF ", Version/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_U, callid = CallId, mediaid = MediaId, from = #party{tag = FromTag, addr = {GuessIp, GuessPort}}, to = null, params = Params}) ->
ParamsBin = encode_params(Params),
Ip = list_to_binary(inet_parse:ntoa(GuessIp)),
Port = list_to_binary(io_lib:format("~b", [GuessPort])),
FT = print_tag_mediaid(FromTag, MediaId),
<<Cookie/binary, " U", ParamsBin/binary, " ", CallId/binary, " ", Ip/binary, " ", Port/binary, " ", FT/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_U, callid = CallId, mediaid = MediaId, from = #party{tag = FromTag, addr = Addr}, to = #party{tag = ToTag}, params = Params}) ->
ParamsBin = encode_params(Params),
BinAddr = binary_print_addr(Addr),
FT = print_tag_mediaid(FromTag, MediaId),
TT = print_tag_mediaid(ToTag, MediaId),
<<Cookie/binary, " U", ParamsBin/binary, " ", CallId/binary, " ", BinAddr/binary, " ", FT/binary, " ", TT/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_L, callid = CallId, mediaid = MediaId, from = #party{tag = FromTag, addr = Addr}, to = #party{tag = ToTag}, params = Params}) ->
ParamsBin = encode_params(Params),
BinAddr = binary_print_addr(Addr),
FT = print_tag_mediaid(FromTag, MediaId),
TT = print_tag_mediaid(ToTag, MediaId),
<<Cookie/binary, <<" L">>/binary, ParamsBin/binary, " ", CallId/binary, " ", BinAddr/binary, " ", TT/binary, " ", FT/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_D, callid = CallId, from = #party{tag = FromTag}, to = null}) ->
<<Cookie/binary, <<" D ">>/binary, CallId/binary, " ", FromTag/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_D, callid = CallId, from = #party{tag = FromTag}, to = #party{tag = ToTag}}) ->
<<Cookie/binary, <<" D ">>/binary, CallId/binary, " ", FromTag/binary, " ", ToTag/binary, "\n">>;
encode(
#cmd{
cookie = Cookie,
type = ?CMD_P,
callid = CallId,
mediaid = MediaId,
from = #party{tag = FromTag},
to = null,
params = [
{codecs, Codecs},
{filename, Filename},
{playcount, Playcount}
]
}) ->
P = list_to_binary(io_lib:format("~b", [Playcount])),
C = list_to_binary(print_codecs(Codecs)),
FT = print_tag_mediaid(FromTag, MediaId),
<<Cookie/binary, <<" P">>/binary, P/binary, " ", CallId/binary, " ", Filename/binary, " ", C/binary, " ", FT/binary, "\n">>;
encode(
#cmd{
cookie = Cookie,
type = ?CMD_P,
callid = CallId,
mediaid = MediaId,
from = #party{tag = FromTag},
to = #party{tag = ToTag},
params = [
{codecs, Codecs},
{filename, Filename},
{playcount, Playcount}
]
}) ->
P = list_to_binary(io_lib:format("~b", [Playcount])),
C = list_to_binary(print_codecs(Codecs)),
FT = print_tag_mediaid(FromTag, MediaId),
TT = print_tag_mediaid(ToTag, MediaId),
<<Cookie/binary, <<" P">>/binary, P/binary, " ", CallId/binary, " ", Filename/binary, " ", C/binary, " ", FT/binary, " ", TT/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_S, callid = CallId, mediaid = MediaId, from = #party{tag = FromTag}, to = null}) ->
FT = print_tag_mediaid(FromTag, MediaId),
<<Cookie/binary, <<" S ">>/binary, CallId/binary, " ", FT/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_S, callid = CallId, mediaid = MediaId, from = #party{tag = FromTag}, to = #party{tag = ToTag}}) ->
FT = print_tag_mediaid(FromTag, MediaId),
TT = print_tag_mediaid(ToTag, MediaId),
<<Cookie/binary, <<" S ">>/binary, CallId/binary, " ", FT/binary, " ", TT/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_R, callid = CallId, from = #party{tag = FromTag}, to = null}) ->
<<Cookie/binary, <<" R ">>/binary, CallId/binary, " ", FromTag/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_R, callid = CallId, from = #party{tag = FromTag}, to = #party{tag = ToTag}}) ->
<<Cookie/binary, <<" R ">>/binary, CallId/binary, " ", FromTag/binary, " ", ToTag/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_Q, callid = CallId, mediaid = MediaId, from = #party{tag = FromTag}, to = #party{tag = ToTag}}) ->
FT = print_tag_mediaid(FromTag, MediaId),
TT = print_tag_mediaid(ToTag, MediaId),
<<Cookie/binary, <<" Q ">>/binary, CallId/binary, " ", FT/binary, " ", TT/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_X}) ->
<<Cookie/binary, <<" X\n">>/binary>>;
encode(#cmd{cookie = Cookie, type = ?CMD_I, params = []}) ->
<<Cookie/binary, <<" I\n">>/binary>>;
encode(#cmd{cookie = Cookie, type = ?CMD_I, params = [brief]}) ->
<<Cookie/binary, <<" IB\n">>/binary>>;
encode(#cmd{} = Unknown) ->
error_logger:error_msg("Unknown command: ~p~n", [Unknown]),
throw({error_syntax, "Unknown (or unsupported) #cmd"}).
%%
%% Private functions
%%
%%
%% Requests
%%
% Request basic supported rtpproxy protocol version
parse_splitted([<<"V">>]) ->
#cmd{
type=?CMD_V
};
% Request additional rtpproxy protocol extensions
parse_splitted([<<"VF">>, Version]) when
Version == <<"20040107">>; % Basic RTP proxy functionality
Support for multiple RTP streams and MOH
Version == <<"20060704">>; % Support for extra parameter in the V command
Version == <<"20071116">>; % Support for RTP re-packetization
Version == <<"20071218">>; % Support for forking (copying) RTP stream
Version == <<"20080403">>; % Support for RTP statistics querying
Version == <<"20081102">>; % Support for setting codecs in the update/lookup command
Version == <<"20081224">>; % Support for session timeout notifications
Version == <<"20090810">> -> % Support for automatic bridging
#cmd{type=?CMD_VF, params = Version};
parse_splitted([<<"VF">>, Unknown]) ->
throw({error_syntax, "Unknown version: " ++ binary_to_list(Unknown)});
Create session ( no ToTag , no Notify extension )
parse_splitted([<<$U:8,Args/binary>>, CallId, ProbableIp, ProbablePort, FromTag]) ->
parse_splitted([<<$U:8,Args/binary>>, CallId, ProbableIp, ProbablePort, FromTag, null, null, null]);
% Reinvite, Hold and Resume (no Notify extension)
parse_splitted([<<$U:8,Args/binary>>, CallId, ProbableIp, ProbablePort, FromTag, ToTag]) ->
parse_splitted([<<$U:8,Args/binary>>, CallId, ProbableIp, ProbablePort, FromTag, ToTag, null, null]);
parse_splitted([<<$U:8,Args/binary>>, CallId, ProbableIp, ProbablePort, FromTag0, ToTag, NotifyAddr, NotifyTag]) ->
[FromTag, MediaId] = ensure_mediaid(binary_split(FromTag0, $;)),
{GuessIp, GuessPort} = parse_addr(binary_to_list(ProbableIp), binary_to_list(ProbablePort)),
Params0 = case {NotifyAddr, NotifyTag} of
{null, null} -> decode_params(Args);
_ -> decode_params(Args) ++ [{notify, [{addr, parse_notify_addr(NotifyAddr)}, {tag, NotifyTag}]}]
end,
% Discard address if it's not consistent with direction
Addr = case {proplists:get_value(direction, Params0), utils:is_rfc1918(GuessIp)} of
{{external, _}, true} -> null;
{{internal, _}, true} -> {GuessIp, GuessPort};
{{internal, _}, false} -> null;
{{external, _}, false} -> {GuessIp, GuessPort};
{_, ipv6} -> {GuessIp, GuessPort}
end,
Params1 = case utils:is_rfc1918(GuessIp) of
ipv6 -> ensure_alone(Params0, ipv6);
_ -> Params0
end,
% Try to guess RTCP address
RtcpAddr = case Addr of
null -> null;
{GuessIp, GuessPort} -> {GuessIp, GuessPort + 1}
end,
#cmd{
type = ?CMD_U,
callid = CallId,
mediaid = MediaId,
from = #party{tag=FromTag, addr=Addr, rtcpaddr=RtcpAddr, proto=proplists:get_value(proto, Params1, udp)},
to = ?SAFE_PARTY(ToTag),
params = lists:sort(proplists:delete(proto, Params1))
};
% Lookup existing session
% In fact it differs from CMD_U only by the order of tags
parse_splitted([<<$L:8,Args/binary>>, CallId, ProbableIp, ProbablePort, FromTag, ToTag]) ->
Cmd = parse_splitted([<<$U:8,Args/binary>>, CallId, ProbableIp, ProbablePort, ToTag, FromTag]),
Cmd#cmd{type = ?CMD_L};
delete session ( no MediaIds and no ToTag ) - Cancel
parse_splitted([<<"D">>, CallId, FromTag]) ->
parse_splitted([<<"D">>, CallId, FromTag, null]);
% delete session (no MediaIds) - Bye
parse_splitted([<<"D">>, CallId, FromTag, ToTag]) ->
#cmd{
type=?CMD_D,
callid=CallId,
from=#party{tag=FromTag},
to = case ToTag of null -> null; _ -> #party{tag=ToTag} end
};
Playback pre - recorded audio ( Music - on - hold and resume , no ToTag )
parse_splitted([<<$P:8,Args/binary>>, CallId, PlayName, Codecs, FromTag0]) ->
[FromTag, MediaId] = ensure_mediaid(binary_split(FromTag0, $;)),
#cmd{
type=?CMD_P,
callid=CallId,
mediaid=MediaId,
from=#party{tag=FromTag},
params=lists:sort(parse_playcount(Args) ++ [{filename, PlayName}, {codecs, parse_codecs(Codecs)}])
};
Playback pre - recorded audio ( Music - on - hold and resume )
parse_splitted([<<$P:8,Args/binary>>, CallId, PlayName, Codecs, FromTag0, ToTag]) ->
[FromTag, MediaId] = ensure_mediaid(binary_split(FromTag0, $;)),
#cmd{
type=?CMD_P,
callid=CallId,
mediaid=MediaId,
from=#party{tag=FromTag},
to = ?SAFE_PARTY(ToTag),
params=lists:sort(parse_playcount(Args) ++ [{filename, PlayName}, {codecs, parse_codecs(Codecs)}])
};
Playback pre - recorded audio ( Music - on - hold and resume )
parse_splitted([<<$P:8,Args/binary>>, CallId, PlayName, Codecs, FromTag0, ToTag, ProbableIp, ProbablePort]) ->
[FromTag, MediaId] = ensure_mediaid(binary_split(FromTag0, $;)),
{GuessIp, GuessPort} = parse_addr(binary_to_list(ProbableIp), binary_to_list(ProbablePort)),
#cmd{
type=?CMD_P,
callid=CallId,
mediaid=MediaId,
from=#party{tag=FromTag},
to = ?SAFE_PARTY(ToTag),
params=lists:sort(parse_playcount(Args) ++ [{filename, PlayName}, {codecs, parse_codecs(Codecs)}, {addr, {GuessIp, GuessPort}}])
};
Stop playback or record ( no ToTag )
parse_splitted([<<"S">>, CallId, FromTag]) ->
parse_splitted([<<"S">>, CallId, FromTag, null]);
% Stop playback or record
parse_splitted([<<"S">>, CallId, FromTag0, ToTag]) ->
[FromTag, MediaId] = ensure_mediaid(binary_split(FromTag0, $;)),
#cmd{
type=?CMD_S,
callid=CallId,
mediaid=MediaId,
from=#party{tag=FromTag},
to = ?SAFE_PARTY(ToTag)
};
% Record (obsoleted in favor of Copy)
% No MediaIds and no ToTag
parse_splitted([<<"R">>, CallId, FromTag]) ->
Cmd = parse_splitted([<<"C">>, CallId, default, <<FromTag/binary, <<";0">>/binary>>, null]),
Cmd#cmd{type = ?CMD_R};
% Record (obsoleted in favor of Copy)
% No MediaIds
parse_splitted([<<"R">>, CallId, FromTag, ToTag]) ->
Cmd = parse_splitted([<<"C">>, CallId, default, <<FromTag/binary, <<";0">>/binary>>, <<ToTag/binary, <<";0">>/binary>>]),
Cmd#cmd{type = ?CMD_R};
% Copy session (same as record, which is now obsolete)
parse_splitted([<<"C">>, CallId, RecordName, FromTag0, ToTag]) ->
[FromTag, MediaId] = ensure_mediaid(binary_split(FromTag0, $;)),
#cmd{
type=?CMD_C,
callid=CallId,
mediaid=MediaId,
from=#party{tag=FromTag},
to = ?SAFE_PARTY(ToTag),
params=[{filename, RecordName}]
};
Query information about one particular session
parse_splitted([<<"Q">>, CallId, FromTag0, ToTag0]) ->
[FromTag, MediaId] = ensure_mediaid(binary_split(FromTag0, $;)),
[ToTag, _] = binary_split(ToTag0, $;),
#cmd{
type=?CMD_Q,
callid=CallId,
mediaid=MediaId,
from=#party{tag=FromTag},
to=#party{tag=ToTag}
};
% Stop all active sessions
parse_splitted([<<"X">>]) ->
#cmd{
type=?CMD_X
};
% Get overall statistics
parse_splitted([<<"I">>]) ->
#cmd{
type=?CMD_I,
params=[]
};
parse_splitted([<<"IB">>]) ->
#cmd{
type=?CMD_I,
params=[brief]
};
%%
%% Replies
%%
parse_splitted([<<"0">>]) ->
#response{type = reply, data = ok};
parse_splitted([<<"1">>]) ->
% This really should be ok - that's another one shortcoming
#response{type = reply, data = supported};
parse_splitted([<<"20040107">>]) ->
#response{type = reply, data = {version, <<"20040107">>}};
parse_splitted([<<"20050322">>]) ->
#response{type = reply, data = {version, <<"20050322">>}};
parse_splitted([<<"20060704">>]) ->
#response{type = reply, data = {version, <<"20060704">>}};
parse_splitted([<<"20071116">>]) ->
#response{type = reply, data = {version, <<"20071116">>}};
parse_splitted([<<"20071218">>]) ->
#response{type = reply, data = {version, <<"20071218">>}};
parse_splitted([<<"20080403">>]) ->
#response{type = reply, data = {version, <<"20080403">>}};
parse_splitted([<<"20081102">>]) ->
#response{type = reply, data = {version, <<"20081102">>}};
parse_splitted([<<"20081224">>]) ->
#response{type = reply, data = {version, <<"20081224">>}};
parse_splitted([<<"20090810">>]) ->
#response{type = reply, data = {version, <<"20090810">>}};
parse_splitted([<<"E1">>]) ->
#response{type = error, data = syntax};
parse_splitted([<<"E7">>]) ->
#response{type = error, data = software};
parse_splitted([<<"E8">>]) ->
#response{type = error, data = notfound};
parse_splitted([P, I]) ->
{Ip, Port} = parse_addr(binary_to_list(I), binary_to_list(P)),
#response{type = reply, data = {{Ip, Port}, {Ip, Port+1}}};
% FIXME Special case - stats
parse_splitted(["SESSIONS", "created:" | Rest]) ->
#response{type = stats};
%%
%% Error / Unknown request or reply
%%
parse_splitted(Unknown) ->
error_logger:error_msg("Unknown command: ~p~n", [Unknown]),
throw({error_syntax, "Unknown command"}).
%%
Internal functions
%%
parse_addr(ProbableIp, ProbablePort) ->
try inet_parse:address(ProbableIp) of
{ok, GuessIp} ->
try list_to_integer(ProbablePort) of
GuessPort when GuessPort >= 0, GuessPort < 65536 ->
{GuessIp, GuessPort};
_ ->
throw({error_syntax, {"Wrong port", ProbablePort}})
catch
_:_ ->
throw({error_syntax, {"Wrong port", ProbablePort}})
end;
_ ->
throw({error_syntax, {"Wrong IP", ProbableIp}})
catch
_:_ ->
throw({error_syntax, {"Wrong IP", ProbableIp}})
end.
parse_playcount(ProbablePlayCount) ->
try [{playcount, list_to_integer (binary_to_list(ProbablePlayCount))}]
catch
_:_ ->
throw({error_syntax, {"Wrong PlayCount", ProbablePlayCount}})
end.
parse_notify_addr(NotifyAddr) ->
case binary_split(NotifyAddr, $:) of
[Port] ->
list_to_integer(binary_to_list(Port));
[IP, Port] ->
parse_addr(binary_to_list(IP), binary_to_list(Port));
IPv6 probably FIXME
throw({error, ipv6notsupported})
end.
parse_codecs(CodecBin) when is_binary(CodecBin) ->
parse_codecs(binary_to_list(CodecBin));
parse_codecs("session") ->
% A very special case - we don't know what codec is used so rtpproxy must use the same as client uses
[session];
parse_codecs(CodecStr) ->
[ begin {Y, []} = string:to_integer(X), rtp_utils:get_codec_from_payload(Y) end || X <- string:tokens(CodecStr, ",")].
decode_params(A) ->
decode_params(binary_to_list(A), []).
decode_params([], Result) ->
Default parameters are - symmetric NAT , non - RFC1918 IPv4 network
R1 = case proplists:get_value(direction, Result) of
undefined ->
Result ++ [{direction, {external, external}}];
_ ->
Result
end,
R2 = case {proplists:get_value(asymmetric, R1), proplists:get_value(symmetric, R1)} of
{true, true} ->
throw({error_syntax, "Both symmetric and asymmetric modifiers are defined"});
{true, _} ->
proplists:delete(asymmetric, R1) ++ [{symmetric, false}];
_ ->
proplists:delete(symmetric, R1) ++ [{symmetric, true}]
end,
lists:sort(R2);
% IPv6
decode_params([$6|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, ipv6));
% Asymmetric
decode_params([$A|Rest], Result) ->
decode_params(Rest, ensure_alone(proplists:delete(symmetric, Result), asymmetric));
% c0,101,100 - Codecs (a bit tricky)
decode_params([$C|Rest], Result) ->
case string:span(Rest, "0123456789,") of
0 ->
% Bogus - skip incomplete modifier
error_logger:warning_msg("Found C parameter w/o necessary values - skipping~n"),
decode_params(Rest, Result);
Ret ->
Rest1 = string:substr(Rest, Ret + 1),
Codecs = parse_codecs(string:substr(Rest, 1, Ret)),
decode_params(Rest1, ensure_alone(Result, codecs, Codecs))
end;
% Direction:
% External (non-RFC1918) network
% Internal (RFC1918) network
% External to External
decode_params([$E, $E|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, direction, {external, external}));
% External to Internal
decode_params([$E, $I|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, direction, {external, internal}));
% External to External (single E)
decode_params([$E|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, direction, {external, external}));
Internal to External
decode_params([$I, $E|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, direction, {internal, external}));
% Internal to Internal
decode_params([$I, $I|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, direction, {internal, internal}));
Internal to Internal ( single I )
decode_params([$I|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, direction, {internal, internal}));
% l - local address
decode_params([$L|Rest], Result) ->
case string:span(Rest, "0123456789.") of
0 ->
% Bogus - skip incomplete modifier
error_logger:warning_msg("Found L parameter w/o necessary values - skipping~n"),
decode_params(Rest, Result);
Ret ->
Rest1 = string:substr(Rest, Ret + 1),
{IpAddr, _} = parse_addr(string:substr(Rest, 1, Ret), "0"),
decode_params(Rest1, ensure_alone(Result, local, IpAddr))
end;
% r - remote address
decode_params([$R|Rest], Result) ->
case string:span(Rest, "0123456789.") of
0 ->
% Bogus - skip incomplete modifier
error_logger:warning_msg("Found R parameter w/o necessary values - skipping~n"),
decode_params(Rest, Result);
Ret ->
Rest1 = string:substr(Rest, Ret + 1),
{IpAddr, _} = parse_addr(string:substr(Rest, 1, Ret), "0"),
decode_params(Rest1, ensure_alone(Result, remote, IpAddr))
end;
Symmetric
decode_params([$S|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, symmetric));
% Weak
decode_params([$W|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, weak));
zNN - repacketization , NN in msec , for the most codecs its value should be
% in 10ms increments, however for some codecs the increment could differ
( e.g. 30ms for GSM or 20ms for G.723 ) .
decode_params([$Z|Rest], Result) ->
case cut_number(Rest) of
{error, _} ->
% Bogus - skip incomplete modifier
error_logger:warning_msg("Found Z parameter w/o necessary values - skipping~n"),
decode_params(Rest, Result);
{Value, Rest1} ->
decode_params(Rest1, ensure_alone(Result, repacketize, Value))
end;
%% Extensions
Protocol - unofficial extension
decode_params([$P, $0 |Rest], Result) ->
decode_params(Rest, ensure_alone(Result, proto, udp));
decode_params([$P, $1 |Rest], Result) ->
decode_params(Rest, ensure_alone(Result, proto, tcp));
decode_params([$P, $2 |Rest], Result) ->
decode_params(Rest, ensure_alone(Result, proto, sctp));
Transcode - unofficial extension
decode_params([$T|Rest], Result) ->
case cut_number(Rest) of
{error, _} ->
% Bogus - skip incomplete modifier
error_logger:warning_msg("Found T parameter w/o necessary values - skipping~n"),
decode_params(Rest, Result);
{Value, Rest1} ->
decode_params(Rest1, ensure_alone(Result, transcode, rtp_utils:get_codec_from_payload(Value)))
end;
% Accounting - unofficial extension
decode_params([$V, $0 |Rest], Result) ->
decode_params(Rest, ensure_alone(Result, acc, start));
decode_params([$V, $1 |Rest], Result) ->
decode_params(Rest, ensure_alone(Result, acc, interim_update));
decode_params([$V, $2 |Rest], Result) ->
decode_params(Rest, ensure_alone(Result, acc, stop));
% DTMF mapping
decode_params([$D|Rest], Result) ->
case cut_number(Rest) of
{error, _} ->
% Bogus - skip incomplete modifier
error_logger:warning_msg("Found D parameter w/o necessary values - skipping~n"),
decode_params(Rest, Result);
{Value, Rest1} ->
decode_params(Rest1, ensure_alone(Result, dtmf, Value))
end;
% Codec mapping
% M<RTP payload ID>=<internal type>
decode_params([$M|Rest], Result) ->
{ok, KV, Rest1} = cut_kv(Rest),
KV1 = lists:map(fun
({K,0}) -> {K, {'ILBC',8000,1}};
({K,10}) -> {K, {'OPUS',8000,1}};
({K,20}) -> {K, {'SPEEX',8000,1}};
({K,V}) -> {K,V}
end, KV),
decode_params(Rest1, ensure_alone(Result, cmap, KV1));
% Unknown parameter - just skip it
decode_params([Unknown|Rest], Result) ->
error_logger:warning_msg("Unsupported parameter while encoding: [~p]~n", [Unknown]),
decode_params(Rest, Result).
encode_params(Params) ->
encode_params(Params, []).
encode_params([], Result) ->
list_to_binary(Result);
encode_params([ipv6|Rest], Result) ->
encode_params(Rest, Result ++ [$6]);
encode_params([{direction, {external, external}}|Rest], Result) ->
FIXME
% encode_params(Rest, Result ++ "ee");
encode_params(Rest, Result);
encode_params([{direction, {external, internal}}|Rest], Result) ->
encode_params(Rest, Result ++ "ei");
encode_params([{direction, {internal, external}}|Rest], Result) ->
encode_params(Rest, Result ++ "ie");
encode_params([{direction, {internal, internal}}|Rest], Result) ->
encode_params(Rest, Result ++ "ii");
encode_params([local|Rest], Result) ->
encode_params(Rest, Result ++ [$l]);
encode_params([remote|Rest], Result) ->
encode_params(Rest, Result ++ [$r]);
encode_params([{symmetric, true}|Rest], Result) ->
FIXME
% encode_params(Rest, Result ++ [$s]);
encode_params(Rest, Result);
encode_params([{symmetric, false}|Rest], Result) ->
encode_params(Rest, Result ++ [$a]);
encode_params([weak|Rest], Result) ->
encode_params(Rest, Result ++ [$w]);
encode_params([{codecs, Codecs}|[]], Result) ->
% Codecs must be placed at the end of the parameters' list
encode_params([], Result ++ [$c] ++ print_codecs(Codecs));
encode_params([{codecs, Codecs}|Rest], Result) ->
encode_params(Rest ++ [{codecs, Codecs}], Result);
encode_params([Unknown|Rest], Result) ->
error_logger:warning_msg("Unsupported parameter while encoding: [~p]~n", [Unknown]),
encode_params(Rest, Result).
print_codecs([session]) ->
"session";
print_codecs(Codecs) ->
print_codecs(Codecs, []).
print_codecs([], Result) ->
Result;
print_codecs([Codec|[]], Result) ->
print_codecs([], Result ++ print_codec(Codec));
print_codecs([Codec|Rest], Result) ->
print_codecs(Rest, Result ++ print_codec(Codec) ++ ",").
ensure_alone(Proplist, Param) ->
proplists:delete(Param, Proplist) ++ [Param].
ensure_alone(Proplist, Param, Value) ->
proplists:delete(Param, Proplist) ++ [{Param, Value}].
ensure_mediaid([Tag, MediaId]) -> [Tag, MediaId];
ensure_mediaid([Tag]) -> [Tag, <<"0">>].
print_tag_mediaid(Tag, <<"0">>) ->
Tag;
print_tag_mediaid(Tag, MediaId) ->
<<Tag/binary, ";", MediaId/binary>>.
print_codec(Codec) ->
Num = rtp_utils:get_payload_from_codec(Codec),
[Str] = io_lib:format("~b", [Num]),
Str.
%%
%% Binary helper functions
%%
binary_to_upper(Binary) when is_binary(Binary) ->
binary_to_upper(<<>>, Binary).
binary_to_upper(Result, <<>>) ->
Result;
binary_to_upper(Result, <<C:8, Rest/binary>>) when $a =< C, C =< $z ->
Symbol = C - 32,
binary_to_upper(<<Result/binary, Symbol:8>>, Rest);
binary_to_upper(Result, <<C:8, Rest/binary>>) ->
binary_to_upper(<<Result/binary, C:8>>, Rest).
binary_split(Binary, Val) when is_binary(Binary) ->
binary_split(<<>>, Binary, Val, []).
binary_split(Head, <<>>, _Val, Result) ->
lists:reverse([Head | Result]);
binary_split(Head, <<Val:8, Rest/binary>>, Val, Result) ->
binary_split(<<>>, Rest, Val, [Head | Result]);
binary_split(Head, <<OtherVal:8, Rest/binary>>, Val, Result) ->
binary_split(<<Head/binary, OtherVal:8>>, Rest, Val, Result).
binary_print_addr({Ip, Port}) ->
BinIp = list_to_binary(inet_parse:ntoa(Ip)),
BinPort = list_to_binary(io_lib:format("~b", [Port])),
<<BinIp/binary, " ", BinPort/binary>>;
binary_print_addr(null) ->
<<"127.0.0.1 10000">>.
cut(String, Span) ->
Ret = string:span(String, "0123456789"),
Rest = string:substr(String, Ret + 1),
Value = string:substr(String, 1, Ret),
{Value, Rest}.
cut_number(String) ->
{V, Rest} = cut(String, "0123456789"),
{Value, _} = string:to_integer(V),
{Value, Rest}.
cut_kv(String) ->
cut_kv(String, []).
cut_kv(String, Ret) ->
{Key, [ $= | Rest0]} = cut_number(String),
case cut_number(Rest0) of
{Val, [ $, | Rest1]} ->
cut_kv(Rest1, Ret ++ [{Key, Val}]);
{Val, Rest2} ->
{ok, Ret ++ [{Key, Val}], Rest2}
end.
| null | https://raw.githubusercontent.com/lemenkov/erlrtpproxy/47b0bb92f6cf9dbc012ea6f1bb757d07ea06734d/src/ser_proto.erl | erlang | ----------------------------------------------------------------------
This program is free software; you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
along with this program; if not, write to the Free Software
----------------------------------------------------------------------
Cut last \n (if exist) and drop accidental zeroes - OpenSIPs inserts
them sometimes (bug in OpenSIPS)
I contains it's own formatting
Private functions
Requests
Request basic supported rtpproxy protocol version
Request additional rtpproxy protocol extensions
Basic RTP proxy functionality
Support for extra parameter in the V command
Support for RTP re-packetization
Support for forking (copying) RTP stream
Support for RTP statistics querying
Support for setting codecs in the update/lookup command
Support for session timeout notifications
Support for automatic bridging
Reinvite, Hold and Resume (no Notify extension)
Discard address if it's not consistent with direction
Try to guess RTCP address
Lookup existing session
In fact it differs from CMD_U only by the order of tags
delete session (no MediaIds) - Bye
Stop playback or record
Record (obsoleted in favor of Copy)
No MediaIds and no ToTag
Record (obsoleted in favor of Copy)
No MediaIds
Copy session (same as record, which is now obsolete)
Stop all active sessions
Get overall statistics
Replies
This really should be ok - that's another one shortcoming
FIXME Special case - stats
Error / Unknown request or reply
A very special case - we don't know what codec is used so rtpproxy must use the same as client uses
IPv6
Asymmetric
c0,101,100 - Codecs (a bit tricky)
Bogus - skip incomplete modifier
Direction:
External (non-RFC1918) network
Internal (RFC1918) network
External to External
External to Internal
External to External (single E)
Internal to Internal
l - local address
Bogus - skip incomplete modifier
r - remote address
Bogus - skip incomplete modifier
Weak
in 10ms increments, however for some codecs the increment could differ
Bogus - skip incomplete modifier
Extensions
Bogus - skip incomplete modifier
Accounting - unofficial extension
DTMF mapping
Bogus - skip incomplete modifier
Codec mapping
M<RTP payload ID>=<internal type>
Unknown parameter - just skip it
encode_params(Rest, Result ++ "ee");
encode_params(Rest, Result ++ [$s]);
Codecs must be placed at the end of the parameters' list
Binary helper functions
| modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 3 of the
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
-module(ser_proto).
-author('').
-export([decode/1]).
-export([encode/1]).
-include("common.hrl").
-define(SAFE_PARTY(Val0), case Val0 of null -> null; _ -> [Val, _] = ensure_mediaid(binary_split(Val0, $;)), #party{tag = Val} end).
decode(Msg) when is_binary(Msg) ->
[Cookie,C|Rest] = binary_split(<< <<X>> || <<X>> <= Msg, X /= 0, X /= $\n>>, $ ),
case parse_splitted([binary_to_upper(C)|Rest]) of
#cmd{} = Cmd ->
Cmd#cmd{
cookie=Cookie,
origin=#origin{
type=ser,
pid=self()
}
};
#response{} = Response ->
case Response#response.type of
stats ->
Response#response{
cookie = Cookie,
};
_ ->
Response#response{
cookie=Cookie
}
end
end.
encode({error, syntax, Msg}) when is_binary(Msg) ->
[Cookie|_] = binary_split(Msg, $ ),
<<Cookie/binary, " E1\n">>;
encode({error, software, Msg}) when is_binary(Msg) ->
[Cookie|_] = binary_split(Msg, $ ),
<<Cookie/binary, " E7\n">>;
encode(#response{cookie = Cookie, type = reply, data = ok}) ->
<<Cookie/binary, " 0\n">>;
encode(#response{cookie = Cookie, type = reply, data = {ok, {stats, Number}}}) when is_integer(Number) ->
N = list_to_binary(integer_to_list(Number)),
<<Cookie/binary, " active sessions: ", N/binary, "\n">>;
encode(#response{cookie = Cookie, type = reply, data = {ok, {stats, NumberTotal, NumberActive}}}) when is_integer(NumberTotal), is_integer(NumberActive) ->
Nt = list_to_binary(integer_to_list(NumberTotal)),
Na = list_to_binary(integer_to_list(NumberActive)),
<<Cookie/binary, " sessions created: ", Nt/binary, " active sessions: ", Na/binary, "\n">>;
encode(#response{cookie = Cookie, type = reply, data = supported}) ->
<<Cookie/binary, " 1\n">>;
encode(#response{cookie = Cookie, type = reply, data = {version, Version}}) when is_binary(Version) ->
<<Cookie/binary, " ", Version/binary, "\n">>;
encode(#response{cookie = Cookie, type = reply, data = {{{I0,I1,I2,I3} = IPv4, Port}, _}}) when
is_integer(I0), I0 >= 0, I0 < 256,
is_integer(I1), I1 >= 0, I1 < 256,
is_integer(I2), I2 >= 0, I2 < 256,
is_integer(I3), I3 >= 0, I3 < 256 ->
I = list_to_binary(inet_parse:ntoa(IPv4)),
P = list_to_binary(integer_to_list(Port)),
<<Cookie/binary, " ", P/binary, " ", I/binary, "\n">>;
encode(#response{cookie = Cookie, type = reply, data = {{{I0,I1,I2,I3,I4,I5,I6,I7} = IPv6, Port}, _}}) when
is_integer(I0), I0 >= 0, I0 < 65535,
is_integer(I1), I1 >= 0, I1 < 65535,
is_integer(I2), I2 >= 0, I2 < 65535,
is_integer(I3), I3 >= 0, I3 < 65535,
is_integer(I4), I4 >= 0, I4 < 65535,
is_integer(I5), I5 >= 0, I5 < 65535,
is_integer(I6), I6 >= 0, I6 < 65535,
is_integer(I7), I7 >= 0, I7 < 65535 ->
I = list_to_binary(inet_parse:ntoa(IPv6)),
P = list_to_binary(integer_to_list(Port)),
<<Cookie/binary, " ", P/binary, " ", I/binary, "\n">>;
encode(#response{cookie = Cookie, type = error, data = syntax}) ->
<<Cookie/binary, " E1\n">>;
encode(#response{cookie = Cookie, type = error, data = software}) ->
<<Cookie/binary, " E7\n">>;
encode(#response{cookie = Cookie, type = error, data = notfound}) ->
<<Cookie/binary, " E8\n">>;
encode(#response{} = Unknown) ->
error_logger:error_msg("Unknown response: ~p~n", [Unknown]),
throw({error_syntax, "Unknown (or unsupported) #response"});
encode(#cmd{cookie = Cookie, type = ?CMD_V}) ->
<<Cookie/binary, " V\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_VF, params = Version}) ->
<<Cookie/binary, " VF ", Version/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_U, callid = CallId, mediaid = MediaId, from = #party{tag = FromTag, addr = {GuessIp, GuessPort}}, to = null, params = Params}) ->
ParamsBin = encode_params(Params),
Ip = list_to_binary(inet_parse:ntoa(GuessIp)),
Port = list_to_binary(io_lib:format("~b", [GuessPort])),
FT = print_tag_mediaid(FromTag, MediaId),
<<Cookie/binary, " U", ParamsBin/binary, " ", CallId/binary, " ", Ip/binary, " ", Port/binary, " ", FT/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_U, callid = CallId, mediaid = MediaId, from = #party{tag = FromTag, addr = Addr}, to = #party{tag = ToTag}, params = Params}) ->
ParamsBin = encode_params(Params),
BinAddr = binary_print_addr(Addr),
FT = print_tag_mediaid(FromTag, MediaId),
TT = print_tag_mediaid(ToTag, MediaId),
<<Cookie/binary, " U", ParamsBin/binary, " ", CallId/binary, " ", BinAddr/binary, " ", FT/binary, " ", TT/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_L, callid = CallId, mediaid = MediaId, from = #party{tag = FromTag, addr = Addr}, to = #party{tag = ToTag}, params = Params}) ->
ParamsBin = encode_params(Params),
BinAddr = binary_print_addr(Addr),
FT = print_tag_mediaid(FromTag, MediaId),
TT = print_tag_mediaid(ToTag, MediaId),
<<Cookie/binary, <<" L">>/binary, ParamsBin/binary, " ", CallId/binary, " ", BinAddr/binary, " ", TT/binary, " ", FT/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_D, callid = CallId, from = #party{tag = FromTag}, to = null}) ->
<<Cookie/binary, <<" D ">>/binary, CallId/binary, " ", FromTag/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_D, callid = CallId, from = #party{tag = FromTag}, to = #party{tag = ToTag}}) ->
<<Cookie/binary, <<" D ">>/binary, CallId/binary, " ", FromTag/binary, " ", ToTag/binary, "\n">>;
encode(
#cmd{
cookie = Cookie,
type = ?CMD_P,
callid = CallId,
mediaid = MediaId,
from = #party{tag = FromTag},
to = null,
params = [
{codecs, Codecs},
{filename, Filename},
{playcount, Playcount}
]
}) ->
P = list_to_binary(io_lib:format("~b", [Playcount])),
C = list_to_binary(print_codecs(Codecs)),
FT = print_tag_mediaid(FromTag, MediaId),
<<Cookie/binary, <<" P">>/binary, P/binary, " ", CallId/binary, " ", Filename/binary, " ", C/binary, " ", FT/binary, "\n">>;
encode(
#cmd{
cookie = Cookie,
type = ?CMD_P,
callid = CallId,
mediaid = MediaId,
from = #party{tag = FromTag},
to = #party{tag = ToTag},
params = [
{codecs, Codecs},
{filename, Filename},
{playcount, Playcount}
]
}) ->
P = list_to_binary(io_lib:format("~b", [Playcount])),
C = list_to_binary(print_codecs(Codecs)),
FT = print_tag_mediaid(FromTag, MediaId),
TT = print_tag_mediaid(ToTag, MediaId),
<<Cookie/binary, <<" P">>/binary, P/binary, " ", CallId/binary, " ", Filename/binary, " ", C/binary, " ", FT/binary, " ", TT/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_S, callid = CallId, mediaid = MediaId, from = #party{tag = FromTag}, to = null}) ->
FT = print_tag_mediaid(FromTag, MediaId),
<<Cookie/binary, <<" S ">>/binary, CallId/binary, " ", FT/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_S, callid = CallId, mediaid = MediaId, from = #party{tag = FromTag}, to = #party{tag = ToTag}}) ->
FT = print_tag_mediaid(FromTag, MediaId),
TT = print_tag_mediaid(ToTag, MediaId),
<<Cookie/binary, <<" S ">>/binary, CallId/binary, " ", FT/binary, " ", TT/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_R, callid = CallId, from = #party{tag = FromTag}, to = null}) ->
<<Cookie/binary, <<" R ">>/binary, CallId/binary, " ", FromTag/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_R, callid = CallId, from = #party{tag = FromTag}, to = #party{tag = ToTag}}) ->
<<Cookie/binary, <<" R ">>/binary, CallId/binary, " ", FromTag/binary, " ", ToTag/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_Q, callid = CallId, mediaid = MediaId, from = #party{tag = FromTag}, to = #party{tag = ToTag}}) ->
FT = print_tag_mediaid(FromTag, MediaId),
TT = print_tag_mediaid(ToTag, MediaId),
<<Cookie/binary, <<" Q ">>/binary, CallId/binary, " ", FT/binary, " ", TT/binary, "\n">>;
encode(#cmd{cookie = Cookie, type = ?CMD_X}) ->
<<Cookie/binary, <<" X\n">>/binary>>;
encode(#cmd{cookie = Cookie, type = ?CMD_I, params = []}) ->
<<Cookie/binary, <<" I\n">>/binary>>;
encode(#cmd{cookie = Cookie, type = ?CMD_I, params = [brief]}) ->
<<Cookie/binary, <<" IB\n">>/binary>>;
encode(#cmd{} = Unknown) ->
error_logger:error_msg("Unknown command: ~p~n", [Unknown]),
throw({error_syntax, "Unknown (or unsupported) #cmd"}).
parse_splitted([<<"V">>]) ->
#cmd{
type=?CMD_V
};
parse_splitted([<<"VF">>, Version]) when
Support for multiple RTP streams and MOH
#cmd{type=?CMD_VF, params = Version};
parse_splitted([<<"VF">>, Unknown]) ->
throw({error_syntax, "Unknown version: " ++ binary_to_list(Unknown)});
Create session ( no ToTag , no Notify extension )
parse_splitted([<<$U:8,Args/binary>>, CallId, ProbableIp, ProbablePort, FromTag]) ->
parse_splitted([<<$U:8,Args/binary>>, CallId, ProbableIp, ProbablePort, FromTag, null, null, null]);
parse_splitted([<<$U:8,Args/binary>>, CallId, ProbableIp, ProbablePort, FromTag, ToTag]) ->
parse_splitted([<<$U:8,Args/binary>>, CallId, ProbableIp, ProbablePort, FromTag, ToTag, null, null]);
parse_splitted([<<$U:8,Args/binary>>, CallId, ProbableIp, ProbablePort, FromTag0, ToTag, NotifyAddr, NotifyTag]) ->
[FromTag, MediaId] = ensure_mediaid(binary_split(FromTag0, $;)),
{GuessIp, GuessPort} = parse_addr(binary_to_list(ProbableIp), binary_to_list(ProbablePort)),
Params0 = case {NotifyAddr, NotifyTag} of
{null, null} -> decode_params(Args);
_ -> decode_params(Args) ++ [{notify, [{addr, parse_notify_addr(NotifyAddr)}, {tag, NotifyTag}]}]
end,
Addr = case {proplists:get_value(direction, Params0), utils:is_rfc1918(GuessIp)} of
{{external, _}, true} -> null;
{{internal, _}, true} -> {GuessIp, GuessPort};
{{internal, _}, false} -> null;
{{external, _}, false} -> {GuessIp, GuessPort};
{_, ipv6} -> {GuessIp, GuessPort}
end,
Params1 = case utils:is_rfc1918(GuessIp) of
ipv6 -> ensure_alone(Params0, ipv6);
_ -> Params0
end,
RtcpAddr = case Addr of
null -> null;
{GuessIp, GuessPort} -> {GuessIp, GuessPort + 1}
end,
#cmd{
type = ?CMD_U,
callid = CallId,
mediaid = MediaId,
from = #party{tag=FromTag, addr=Addr, rtcpaddr=RtcpAddr, proto=proplists:get_value(proto, Params1, udp)},
to = ?SAFE_PARTY(ToTag),
params = lists:sort(proplists:delete(proto, Params1))
};
parse_splitted([<<$L:8,Args/binary>>, CallId, ProbableIp, ProbablePort, FromTag, ToTag]) ->
Cmd = parse_splitted([<<$U:8,Args/binary>>, CallId, ProbableIp, ProbablePort, ToTag, FromTag]),
Cmd#cmd{type = ?CMD_L};
delete session ( no MediaIds and no ToTag ) - Cancel
parse_splitted([<<"D">>, CallId, FromTag]) ->
parse_splitted([<<"D">>, CallId, FromTag, null]);
parse_splitted([<<"D">>, CallId, FromTag, ToTag]) ->
#cmd{
type=?CMD_D,
callid=CallId,
from=#party{tag=FromTag},
to = case ToTag of null -> null; _ -> #party{tag=ToTag} end
};
Playback pre - recorded audio ( Music - on - hold and resume , no ToTag )
parse_splitted([<<$P:8,Args/binary>>, CallId, PlayName, Codecs, FromTag0]) ->
[FromTag, MediaId] = ensure_mediaid(binary_split(FromTag0, $;)),
#cmd{
type=?CMD_P,
callid=CallId,
mediaid=MediaId,
from=#party{tag=FromTag},
params=lists:sort(parse_playcount(Args) ++ [{filename, PlayName}, {codecs, parse_codecs(Codecs)}])
};
Playback pre - recorded audio ( Music - on - hold and resume )
parse_splitted([<<$P:8,Args/binary>>, CallId, PlayName, Codecs, FromTag0, ToTag]) ->
[FromTag, MediaId] = ensure_mediaid(binary_split(FromTag0, $;)),
#cmd{
type=?CMD_P,
callid=CallId,
mediaid=MediaId,
from=#party{tag=FromTag},
to = ?SAFE_PARTY(ToTag),
params=lists:sort(parse_playcount(Args) ++ [{filename, PlayName}, {codecs, parse_codecs(Codecs)}])
};
Playback pre - recorded audio ( Music - on - hold and resume )
parse_splitted([<<$P:8,Args/binary>>, CallId, PlayName, Codecs, FromTag0, ToTag, ProbableIp, ProbablePort]) ->
[FromTag, MediaId] = ensure_mediaid(binary_split(FromTag0, $;)),
{GuessIp, GuessPort} = parse_addr(binary_to_list(ProbableIp), binary_to_list(ProbablePort)),
#cmd{
type=?CMD_P,
callid=CallId,
mediaid=MediaId,
from=#party{tag=FromTag},
to = ?SAFE_PARTY(ToTag),
params=lists:sort(parse_playcount(Args) ++ [{filename, PlayName}, {codecs, parse_codecs(Codecs)}, {addr, {GuessIp, GuessPort}}])
};
Stop playback or record ( no ToTag )
parse_splitted([<<"S">>, CallId, FromTag]) ->
parse_splitted([<<"S">>, CallId, FromTag, null]);
parse_splitted([<<"S">>, CallId, FromTag0, ToTag]) ->
[FromTag, MediaId] = ensure_mediaid(binary_split(FromTag0, $;)),
#cmd{
type=?CMD_S,
callid=CallId,
mediaid=MediaId,
from=#party{tag=FromTag},
to = ?SAFE_PARTY(ToTag)
};
parse_splitted([<<"R">>, CallId, FromTag]) ->
Cmd = parse_splitted([<<"C">>, CallId, default, <<FromTag/binary, <<";0">>/binary>>, null]),
Cmd#cmd{type = ?CMD_R};
parse_splitted([<<"R">>, CallId, FromTag, ToTag]) ->
Cmd = parse_splitted([<<"C">>, CallId, default, <<FromTag/binary, <<";0">>/binary>>, <<ToTag/binary, <<";0">>/binary>>]),
Cmd#cmd{type = ?CMD_R};
parse_splitted([<<"C">>, CallId, RecordName, FromTag0, ToTag]) ->
[FromTag, MediaId] = ensure_mediaid(binary_split(FromTag0, $;)),
#cmd{
type=?CMD_C,
callid=CallId,
mediaid=MediaId,
from=#party{tag=FromTag},
to = ?SAFE_PARTY(ToTag),
params=[{filename, RecordName}]
};
Query information about one particular session
parse_splitted([<<"Q">>, CallId, FromTag0, ToTag0]) ->
[FromTag, MediaId] = ensure_mediaid(binary_split(FromTag0, $;)),
[ToTag, _] = binary_split(ToTag0, $;),
#cmd{
type=?CMD_Q,
callid=CallId,
mediaid=MediaId,
from=#party{tag=FromTag},
to=#party{tag=ToTag}
};
parse_splitted([<<"X">>]) ->
#cmd{
type=?CMD_X
};
parse_splitted([<<"I">>]) ->
#cmd{
type=?CMD_I,
params=[]
};
parse_splitted([<<"IB">>]) ->
#cmd{
type=?CMD_I,
params=[brief]
};
parse_splitted([<<"0">>]) ->
#response{type = reply, data = ok};
parse_splitted([<<"1">>]) ->
#response{type = reply, data = supported};
parse_splitted([<<"20040107">>]) ->
#response{type = reply, data = {version, <<"20040107">>}};
parse_splitted([<<"20050322">>]) ->
#response{type = reply, data = {version, <<"20050322">>}};
parse_splitted([<<"20060704">>]) ->
#response{type = reply, data = {version, <<"20060704">>}};
parse_splitted([<<"20071116">>]) ->
#response{type = reply, data = {version, <<"20071116">>}};
parse_splitted([<<"20071218">>]) ->
#response{type = reply, data = {version, <<"20071218">>}};
parse_splitted([<<"20080403">>]) ->
#response{type = reply, data = {version, <<"20080403">>}};
parse_splitted([<<"20081102">>]) ->
#response{type = reply, data = {version, <<"20081102">>}};
parse_splitted([<<"20081224">>]) ->
#response{type = reply, data = {version, <<"20081224">>}};
parse_splitted([<<"20090810">>]) ->
#response{type = reply, data = {version, <<"20090810">>}};
parse_splitted([<<"E1">>]) ->
#response{type = error, data = syntax};
parse_splitted([<<"E7">>]) ->
#response{type = error, data = software};
parse_splitted([<<"E8">>]) ->
#response{type = error, data = notfound};
parse_splitted([P, I]) ->
{Ip, Port} = parse_addr(binary_to_list(I), binary_to_list(P)),
#response{type = reply, data = {{Ip, Port}, {Ip, Port+1}}};
parse_splitted(["SESSIONS", "created:" | Rest]) ->
#response{type = stats};
parse_splitted(Unknown) ->
error_logger:error_msg("Unknown command: ~p~n", [Unknown]),
throw({error_syntax, "Unknown command"}).
Internal functions
parse_addr(ProbableIp, ProbablePort) ->
try inet_parse:address(ProbableIp) of
{ok, GuessIp} ->
try list_to_integer(ProbablePort) of
GuessPort when GuessPort >= 0, GuessPort < 65536 ->
{GuessIp, GuessPort};
_ ->
throw({error_syntax, {"Wrong port", ProbablePort}})
catch
_:_ ->
throw({error_syntax, {"Wrong port", ProbablePort}})
end;
_ ->
throw({error_syntax, {"Wrong IP", ProbableIp}})
catch
_:_ ->
throw({error_syntax, {"Wrong IP", ProbableIp}})
end.
parse_playcount(ProbablePlayCount) ->
try [{playcount, list_to_integer (binary_to_list(ProbablePlayCount))}]
catch
_:_ ->
throw({error_syntax, {"Wrong PlayCount", ProbablePlayCount}})
end.
parse_notify_addr(NotifyAddr) ->
case binary_split(NotifyAddr, $:) of
[Port] ->
list_to_integer(binary_to_list(Port));
[IP, Port] ->
parse_addr(binary_to_list(IP), binary_to_list(Port));
IPv6 probably FIXME
throw({error, ipv6notsupported})
end.
parse_codecs(CodecBin) when is_binary(CodecBin) ->
parse_codecs(binary_to_list(CodecBin));
parse_codecs("session") ->
[session];
parse_codecs(CodecStr) ->
[ begin {Y, []} = string:to_integer(X), rtp_utils:get_codec_from_payload(Y) end || X <- string:tokens(CodecStr, ",")].
decode_params(A) ->
decode_params(binary_to_list(A), []).
decode_params([], Result) ->
Default parameters are - symmetric NAT , non - RFC1918 IPv4 network
R1 = case proplists:get_value(direction, Result) of
undefined ->
Result ++ [{direction, {external, external}}];
_ ->
Result
end,
R2 = case {proplists:get_value(asymmetric, R1), proplists:get_value(symmetric, R1)} of
{true, true} ->
throw({error_syntax, "Both symmetric and asymmetric modifiers are defined"});
{true, _} ->
proplists:delete(asymmetric, R1) ++ [{symmetric, false}];
_ ->
proplists:delete(symmetric, R1) ++ [{symmetric, true}]
end,
lists:sort(R2);
decode_params([$6|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, ipv6));
decode_params([$A|Rest], Result) ->
decode_params(Rest, ensure_alone(proplists:delete(symmetric, Result), asymmetric));
decode_params([$C|Rest], Result) ->
case string:span(Rest, "0123456789,") of
0 ->
error_logger:warning_msg("Found C parameter w/o necessary values - skipping~n"),
decode_params(Rest, Result);
Ret ->
Rest1 = string:substr(Rest, Ret + 1),
Codecs = parse_codecs(string:substr(Rest, 1, Ret)),
decode_params(Rest1, ensure_alone(Result, codecs, Codecs))
end;
decode_params([$E, $E|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, direction, {external, external}));
decode_params([$E, $I|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, direction, {external, internal}));
decode_params([$E|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, direction, {external, external}));
Internal to External
decode_params([$I, $E|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, direction, {internal, external}));
decode_params([$I, $I|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, direction, {internal, internal}));
Internal to Internal ( single I )
decode_params([$I|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, direction, {internal, internal}));
decode_params([$L|Rest], Result) ->
case string:span(Rest, "0123456789.") of
0 ->
error_logger:warning_msg("Found L parameter w/o necessary values - skipping~n"),
decode_params(Rest, Result);
Ret ->
Rest1 = string:substr(Rest, Ret + 1),
{IpAddr, _} = parse_addr(string:substr(Rest, 1, Ret), "0"),
decode_params(Rest1, ensure_alone(Result, local, IpAddr))
end;
decode_params([$R|Rest], Result) ->
case string:span(Rest, "0123456789.") of
0 ->
error_logger:warning_msg("Found R parameter w/o necessary values - skipping~n"),
decode_params(Rest, Result);
Ret ->
Rest1 = string:substr(Rest, Ret + 1),
{IpAddr, _} = parse_addr(string:substr(Rest, 1, Ret), "0"),
decode_params(Rest1, ensure_alone(Result, remote, IpAddr))
end;
Symmetric
decode_params([$S|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, symmetric));
decode_params([$W|Rest], Result) ->
decode_params(Rest, ensure_alone(Result, weak));
zNN - repacketization , NN in msec , for the most codecs its value should be
( e.g. 30ms for GSM or 20ms for G.723 ) .
decode_params([$Z|Rest], Result) ->
case cut_number(Rest) of
{error, _} ->
error_logger:warning_msg("Found Z parameter w/o necessary values - skipping~n"),
decode_params(Rest, Result);
{Value, Rest1} ->
decode_params(Rest1, ensure_alone(Result, repacketize, Value))
end;
Protocol - unofficial extension
decode_params([$P, $0 |Rest], Result) ->
decode_params(Rest, ensure_alone(Result, proto, udp));
decode_params([$P, $1 |Rest], Result) ->
decode_params(Rest, ensure_alone(Result, proto, tcp));
decode_params([$P, $2 |Rest], Result) ->
decode_params(Rest, ensure_alone(Result, proto, sctp));
Transcode - unofficial extension
decode_params([$T|Rest], Result) ->
case cut_number(Rest) of
{error, _} ->
error_logger:warning_msg("Found T parameter w/o necessary values - skipping~n"),
decode_params(Rest, Result);
{Value, Rest1} ->
decode_params(Rest1, ensure_alone(Result, transcode, rtp_utils:get_codec_from_payload(Value)))
end;
decode_params([$V, $0 |Rest], Result) ->
decode_params(Rest, ensure_alone(Result, acc, start));
decode_params([$V, $1 |Rest], Result) ->
decode_params(Rest, ensure_alone(Result, acc, interim_update));
decode_params([$V, $2 |Rest], Result) ->
decode_params(Rest, ensure_alone(Result, acc, stop));
decode_params([$D|Rest], Result) ->
case cut_number(Rest) of
{error, _} ->
error_logger:warning_msg("Found D parameter w/o necessary values - skipping~n"),
decode_params(Rest, Result);
{Value, Rest1} ->
decode_params(Rest1, ensure_alone(Result, dtmf, Value))
end;
decode_params([$M|Rest], Result) ->
{ok, KV, Rest1} = cut_kv(Rest),
KV1 = lists:map(fun
({K,0}) -> {K, {'ILBC',8000,1}};
({K,10}) -> {K, {'OPUS',8000,1}};
({K,20}) -> {K, {'SPEEX',8000,1}};
({K,V}) -> {K,V}
end, KV),
decode_params(Rest1, ensure_alone(Result, cmap, KV1));
decode_params([Unknown|Rest], Result) ->
error_logger:warning_msg("Unsupported parameter while encoding: [~p]~n", [Unknown]),
decode_params(Rest, Result).
encode_params(Params) ->
encode_params(Params, []).
encode_params([], Result) ->
list_to_binary(Result);
encode_params([ipv6|Rest], Result) ->
encode_params(Rest, Result ++ [$6]);
encode_params([{direction, {external, external}}|Rest], Result) ->
FIXME
encode_params(Rest, Result);
encode_params([{direction, {external, internal}}|Rest], Result) ->
encode_params(Rest, Result ++ "ei");
encode_params([{direction, {internal, external}}|Rest], Result) ->
encode_params(Rest, Result ++ "ie");
encode_params([{direction, {internal, internal}}|Rest], Result) ->
encode_params(Rest, Result ++ "ii");
encode_params([local|Rest], Result) ->
encode_params(Rest, Result ++ [$l]);
encode_params([remote|Rest], Result) ->
encode_params(Rest, Result ++ [$r]);
encode_params([{symmetric, true}|Rest], Result) ->
FIXME
encode_params(Rest, Result);
encode_params([{symmetric, false}|Rest], Result) ->
encode_params(Rest, Result ++ [$a]);
encode_params([weak|Rest], Result) ->
encode_params(Rest, Result ++ [$w]);
encode_params([{codecs, Codecs}|[]], Result) ->
encode_params([], Result ++ [$c] ++ print_codecs(Codecs));
encode_params([{codecs, Codecs}|Rest], Result) ->
encode_params(Rest ++ [{codecs, Codecs}], Result);
encode_params([Unknown|Rest], Result) ->
error_logger:warning_msg("Unsupported parameter while encoding: [~p]~n", [Unknown]),
encode_params(Rest, Result).
print_codecs([session]) ->
"session";
print_codecs(Codecs) ->
print_codecs(Codecs, []).
print_codecs([], Result) ->
Result;
print_codecs([Codec|[]], Result) ->
print_codecs([], Result ++ print_codec(Codec));
print_codecs([Codec|Rest], Result) ->
print_codecs(Rest, Result ++ print_codec(Codec) ++ ",").
ensure_alone(Proplist, Param) ->
proplists:delete(Param, Proplist) ++ [Param].
ensure_alone(Proplist, Param, Value) ->
proplists:delete(Param, Proplist) ++ [{Param, Value}].
ensure_mediaid([Tag, MediaId]) -> [Tag, MediaId];
ensure_mediaid([Tag]) -> [Tag, <<"0">>].
print_tag_mediaid(Tag, <<"0">>) ->
Tag;
print_tag_mediaid(Tag, MediaId) ->
<<Tag/binary, ";", MediaId/binary>>.
print_codec(Codec) ->
Num = rtp_utils:get_payload_from_codec(Codec),
[Str] = io_lib:format("~b", [Num]),
Str.
binary_to_upper(Binary) when is_binary(Binary) ->
binary_to_upper(<<>>, Binary).
binary_to_upper(Result, <<>>) ->
Result;
binary_to_upper(Result, <<C:8, Rest/binary>>) when $a =< C, C =< $z ->
Symbol = C - 32,
binary_to_upper(<<Result/binary, Symbol:8>>, Rest);
binary_to_upper(Result, <<C:8, Rest/binary>>) ->
binary_to_upper(<<Result/binary, C:8>>, Rest).
binary_split(Binary, Val) when is_binary(Binary) ->
binary_split(<<>>, Binary, Val, []).
binary_split(Head, <<>>, _Val, Result) ->
lists:reverse([Head | Result]);
binary_split(Head, <<Val:8, Rest/binary>>, Val, Result) ->
binary_split(<<>>, Rest, Val, [Head | Result]);
binary_split(Head, <<OtherVal:8, Rest/binary>>, Val, Result) ->
binary_split(<<Head/binary, OtherVal:8>>, Rest, Val, Result).
binary_print_addr({Ip, Port}) ->
BinIp = list_to_binary(inet_parse:ntoa(Ip)),
BinPort = list_to_binary(io_lib:format("~b", [Port])),
<<BinIp/binary, " ", BinPort/binary>>;
binary_print_addr(null) ->
<<"127.0.0.1 10000">>.
cut(String, Span) ->
Ret = string:span(String, "0123456789"),
Rest = string:substr(String, Ret + 1),
Value = string:substr(String, 1, Ret),
{Value, Rest}.
cut_number(String) ->
{V, Rest} = cut(String, "0123456789"),
{Value, _} = string:to_integer(V),
{Value, Rest}.
cut_kv(String) ->
cut_kv(String, []).
cut_kv(String, Ret) ->
{Key, [ $= | Rest0]} = cut_number(String),
case cut_number(Rest0) of
{Val, [ $, | Rest1]} ->
cut_kv(Rest1, Ret ++ [{Key, Val}]);
{Val, Rest2} ->
{ok, Ret ++ [{Key, Val}], Rest2}
end.
|
b5301ea9a04944625133ed6ca16b5bef3189f236de265b5c9891da0a15e2ab34 | TerrorJack/ghc-alter | Zip.hs | {-# LANGUAGE Safe #-}
# LANGUAGE TypeOperators #
-----------------------------------------------------------------------------
-- |
Module : Control . . Zip
Copyright : ( c ) 2011 ,
( c ) 2011
( c ) University Tuebingen 2011
-- License : BSD-style (see the file libraries/base/LICENSE)
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
Monadic zipping ( used for monad comprehensions )
--
-----------------------------------------------------------------------------
module Control.Monad.Zip where
import Control.Monad (liftM, liftM2)
import Data.Functor.Identity
import Data.Monoid
import Data.Proxy
import GHC.Generics
| ` MonadZip ` type class . Minimal definition : ` mzip ` or ` mzipWith `
--
-- Instances should satisfy the laws:
--
* Naturality :
--
> liftM ( f * * * g ) ( mzip ma mb ) = mzip ( liftM f ma ) ( liftM g mb )
--
-- * Information Preservation:
--
-- > liftM (const ()) ma = liftM (const ()) mb
-- > ==>
( mzip ma mb ) = ( ma , )
--
class Monad m => MonadZip m where
# MINIMAL mzip | mzipWith #
mzip :: m a -> m b -> m (a,b)
mzip = mzipWith (,)
mzipWith :: (a -> b -> c) -> m a -> m b -> m c
mzipWith f ma mb = liftM (uncurry f) (mzip ma mb)
munzip :: m (a,b) -> (m a, m b)
munzip mab = (liftM fst mab, liftM snd mab)
-- munzip is a member of the class because sometimes
-- you can implement it more efficiently than the
above default code . See Trac # 4370 comment by
| @since 4.3.1.0
instance MonadZip [] where
mzip = zip
mzipWith = zipWith
munzip = unzip
| @since 4.8.0.0
instance MonadZip Identity where
mzipWith = liftM2
munzip (Identity (a, b)) = (Identity a, Identity b)
| @since 4.8.0.0
instance MonadZip Dual where
-- Cannot use coerce, it's unsafe
mzipWith = liftM2
| @since 4.8.0.0
instance MonadZip Sum where
mzipWith = liftM2
| @since 4.8.0.0
instance MonadZip Product where
mzipWith = liftM2
| @since 4.8.0.0
instance MonadZip Maybe where
mzipWith = liftM2
| @since 4.8.0.0
instance MonadZip First where
mzipWith = liftM2
| @since 4.8.0.0
instance MonadZip Last where
mzipWith = liftM2
| @since 4.8.0.0
instance MonadZip f => MonadZip (Alt f) where
mzipWith f (Alt ma) (Alt mb) = Alt (mzipWith f ma mb)
| @since 4.9.0.0
instance MonadZip Proxy where
mzipWith _ _ _ = Proxy
-- Instances for GHC.Generics
| @since 4.9.0.0
instance MonadZip U1 where
mzipWith _ _ _ = U1
| @since 4.9.0.0
instance MonadZip Par1 where
mzipWith = liftM2
| @since 4.9.0.0
instance MonadZip f => MonadZip (Rec1 f) where
mzipWith f (Rec1 fa) (Rec1 fb) = Rec1 (mzipWith f fa fb)
| @since 4.9.0.0
instance MonadZip f => MonadZip (M1 i c f) where
mzipWith f (M1 fa) (M1 fb) = M1 (mzipWith f fa fb)
| @since 4.9.0.0
instance (MonadZip f, MonadZip g) => MonadZip (f :*: g) where
mzipWith f (x1 :*: y1) (x2 :*: y2) = mzipWith f x1 x2 :*: mzipWith f y1 y2
| null | https://raw.githubusercontent.com/TerrorJack/ghc-alter/db736f34095eef416b7e077f9b26fc03aa78c311/ghc-alter/boot-lib/base/Control/Monad/Zip.hs | haskell | # LANGUAGE Safe #
---------------------------------------------------------------------------
|
License : BSD-style (see the file libraries/base/LICENSE)
Maintainer :
Stability : experimental
Portability : portable
---------------------------------------------------------------------------
Instances should satisfy the laws:
* Information Preservation:
> liftM (const ()) ma = liftM (const ()) mb
> ==>
munzip is a member of the class because sometimes
you can implement it more efficiently than the
Cannot use coerce, it's unsafe
Instances for GHC.Generics | # LANGUAGE TypeOperators #
Module : Control . . Zip
Copyright : ( c ) 2011 ,
( c ) 2011
( c ) University Tuebingen 2011
Monadic zipping ( used for monad comprehensions )
module Control.Monad.Zip where
import Control.Monad (liftM, liftM2)
import Data.Functor.Identity
import Data.Monoid
import Data.Proxy
import GHC.Generics
| ` MonadZip ` type class . Minimal definition : ` mzip ` or ` mzipWith `
* Naturality :
> liftM ( f * * * g ) ( mzip ma mb ) = mzip ( liftM f ma ) ( liftM g mb )
( mzip ma mb ) = ( ma , )
class Monad m => MonadZip m where
# MINIMAL mzip | mzipWith #
mzip :: m a -> m b -> m (a,b)
mzip = mzipWith (,)
mzipWith :: (a -> b -> c) -> m a -> m b -> m c
mzipWith f ma mb = liftM (uncurry f) (mzip ma mb)
munzip :: m (a,b) -> (m a, m b)
munzip mab = (liftM fst mab, liftM snd mab)
above default code . See Trac # 4370 comment by
| @since 4.3.1.0
instance MonadZip [] where
mzip = zip
mzipWith = zipWith
munzip = unzip
| @since 4.8.0.0
instance MonadZip Identity where
mzipWith = liftM2
munzip (Identity (a, b)) = (Identity a, Identity b)
| @since 4.8.0.0
instance MonadZip Dual where
mzipWith = liftM2
| @since 4.8.0.0
instance MonadZip Sum where
mzipWith = liftM2
| @since 4.8.0.0
instance MonadZip Product where
mzipWith = liftM2
| @since 4.8.0.0
instance MonadZip Maybe where
mzipWith = liftM2
| @since 4.8.0.0
instance MonadZip First where
mzipWith = liftM2
| @since 4.8.0.0
instance MonadZip Last where
mzipWith = liftM2
| @since 4.8.0.0
instance MonadZip f => MonadZip (Alt f) where
mzipWith f (Alt ma) (Alt mb) = Alt (mzipWith f ma mb)
| @since 4.9.0.0
instance MonadZip Proxy where
mzipWith _ _ _ = Proxy
| @since 4.9.0.0
instance MonadZip U1 where
mzipWith _ _ _ = U1
| @since 4.9.0.0
instance MonadZip Par1 where
mzipWith = liftM2
| @since 4.9.0.0
instance MonadZip f => MonadZip (Rec1 f) where
mzipWith f (Rec1 fa) (Rec1 fb) = Rec1 (mzipWith f fa fb)
| @since 4.9.0.0
instance MonadZip f => MonadZip (M1 i c f) where
mzipWith f (M1 fa) (M1 fb) = M1 (mzipWith f fa fb)
| @since 4.9.0.0
instance (MonadZip f, MonadZip g) => MonadZip (f :*: g) where
mzipWith f (x1 :*: y1) (x2 :*: y2) = mzipWith f x1 x2 :*: mzipWith f y1 y2
|
a50805a8c8bced0b01747517203c8001ee8c69b1728c275d9e97e2f7e906d758 | wz1000/hie-lsp | DynamicWriter.hs | module Reflex.DynamicWriter
# DEPRECATED " Use ' Reflex . DynamicWriter . Class ' and ' Reflex . DynamicWrite . Base ' instead , or just import ' Reflex ' " #
( module X
) where
import Reflex.DynamicWriter.Base as X
import Reflex.DynamicWriter.Class as X
| null | https://raw.githubusercontent.com/wz1000/hie-lsp/dbb3caa97c0acbff0e4fd86fc46eeea748f65e89/reflex-0.6.1/src/Reflex/DynamicWriter.hs | haskell | module Reflex.DynamicWriter
# DEPRECATED " Use ' Reflex . DynamicWriter . Class ' and ' Reflex . DynamicWrite . Base ' instead , or just import ' Reflex ' " #
( module X
) where
import Reflex.DynamicWriter.Base as X
import Reflex.DynamicWriter.Class as X
|
|
b28c03730630808c8247f934ecea5faad01ae37b1f7ecac4d18be919bf22e110 | alekras/erl.mqtt.server | mqtt_rest_tests.erl | %%
Copyright ( C ) 2015 - 2022 by ( )
%%
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.
%%
%% @hidden
@since 2022 - 06 - 01
2015 - 2022
@author < > [ / ]
%% @version {@version}
%% @doc This module is running erlang unit tests.
-module(mqtt_rest_tests).
%%
%% Include files
%%
-include_lib("eunit/include/eunit.hrl").
-include("test_rest.hrl").
%%
%% API Functions
%%
mqtt_server_test_() ->
[
{ setup,
fun mqtt_rest_test_utils:do_start/0,
fun mqtt_rest_test_utils:do_stop/1,
{inorder, [
{"rest service", timeout, 15, fun restful:post/0},
{"rest service", fun restful:get_user/0},
{"rest service", fun restful:get_status/0},
{"rest service", fun restful:get_all_statuses/0},
{"rest service", fun restful:delete/0},
{foreachx,
fun mqtt_rest_test_utils:do_setup/1,
fun mqtt_rest_test_utils:do_cleanup/2,
[
{{1, keep_alive}, fun keep_alive/2}
]
}
]}
}
].
keep_alive(_, _Conn) -> {"keep alive test", timeout, 15, fun() ->
?PASSED
end}.
| null | https://raw.githubusercontent.com/alekras/erl.mqtt.server/8d3d2a24a089ccb502e3be8ab56f430358a7952c/apps/mqtt_rest/test/mqtt_rest_tests.erl | erlang |
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.
@hidden
@version {@version}
@doc This module is running erlang unit tests.
Include files
API Functions
| Copyright ( C ) 2015 - 2022 by ( )
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@since 2022 - 06 - 01
2015 - 2022
@author < > [ / ]
-module(mqtt_rest_tests).
-include_lib("eunit/include/eunit.hrl").
-include("test_rest.hrl").
mqtt_server_test_() ->
[
{ setup,
fun mqtt_rest_test_utils:do_start/0,
fun mqtt_rest_test_utils:do_stop/1,
{inorder, [
{"rest service", timeout, 15, fun restful:post/0},
{"rest service", fun restful:get_user/0},
{"rest service", fun restful:get_status/0},
{"rest service", fun restful:get_all_statuses/0},
{"rest service", fun restful:delete/0},
{foreachx,
fun mqtt_rest_test_utils:do_setup/1,
fun mqtt_rest_test_utils:do_cleanup/2,
[
{{1, keep_alive}, fun keep_alive/2}
]
}
]}
}
].
keep_alive(_, _Conn) -> {"keep alive test", timeout, 15, fun() ->
?PASSED
end}.
|
01543c1b76740f1b7f67c00657b7e1f9eb465aa1b04cd37c0af7916d8e7f1495 | theodormoroianu/SecondYearCourses | LambdaChurch_20210415164230.hs | module LambdaChurch where
import Data.Char (isLetter)
import Data.List ( nub )
class ShowNice a where
showNice :: a -> String
class ReadNice a where
readNice :: String -> (a, String)
data Variable
= Variable
{ name :: String
, count :: Int
}
deriving (Show, Eq, Ord)
var :: String -> Variable
var x = Variable x 0
instance ShowNice Variable where
showNice (Variable x 0) = x
showNice (Variable x cnt) = x <> "_" <> show cnt
instance ReadNice Variable where
readNice s
| null x = error $ "expected variable but found " <> s
| otherwise = (var x, s')
where
(x, s') = span isLetter s
freshVariable :: Variable -> [Variable] -> Variable
freshVariable var vars = Variable x (cnt + 1)
where
x = name var
varsWithName = filter ((== x) . name) vars
Variable _ cnt = maximum (var : varsWithName)
data Term
= V Variable
| App Term Term
| Lam Variable Term
deriving (Show)
-- alpha-equivalence
aEq :: Term -> Term -> Bool
aEq (V x) (V x') = x == x'
aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2'
aEq (Lam x t) (Lam x' t')
| x == x' = aEq t t'
| otherwise = aEq (subst (V y) x t) (subst (V y) x' t')
where
fvT = freeVars t
fvT' = freeVars t'
allFV = nub ([x, x'] ++ fvT ++ fvT')
y = freshVariable x allFV
aEq _ _ = False
v :: String -> Term
v x = V (var x)
lam :: String -> Term -> Term
lam x = Lam (var x)
lams :: [String] -> Term -> Term
lams xs t = foldr lam t xs
($$) :: Term -> Term -> Term
($$) = App
infixl 9 $$
instance ShowNice Term where
showNice (V var) = showNice var
showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")"
showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")"
instance ReadNice Term where
readNice [] = error "Nothing to read"
readNice ('(' : '\\' : s) = (Lam var t, s'')
where
(var, '.' : s') = readNice s
(t, ')' : s'') = readNice s'
readNice ('(' : s) = (App t1 t2, s'')
where
(t1, ' ' : s') = readNice s
(t2, ')' : s'') = readNice s'
readNice s = (V var, s')
where
(var, s') = readNice s
freeVars :: Term -> [Variable]
freeVars (V var) = [var]
freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2
freeVars (Lam var t) = filter (/= var) (freeVars t)
-- subst u x t defines [u/x]t, i.e., substituting u for x in t
for example [ 3 / x](x + x ) = = 3 + 3
-- This substitution avoids variable captures so it is safe to be used when
-- reducing terms with free variables (e.g., if evaluating inside lambda abstractions)
subst
:: Term -- ^ substitution term
-> Variable -- ^ variable to be substitutes
-> Term -- ^ term in which the substitution occurs
-> Term
subst u x (V y)
| x == y = u
| otherwise = V y
subst u x (App t1 t2) = App (subst u x t1) (subst u x t2)
subst u x (Lam y t)
| x == y = Lam y t
| y `notElem` fvU = Lam y (subst u x t)
| x `notElem` fvT = Lam y t
| otherwise = Lam y' (subst u x (subst (V y') y t))
where
fvT = freeVars t
fvU = freeVars u
allFV = nub ([x] ++ fvU ++ fvT)
y' = freshVariable y allFV
-- Normal order reduction
-- - like call by name
-- - but also reduce under lambda abstractions if no application is possible
-- - guarantees reaching a normal form if it exists
normalReduceStep :: Term -> Maybe Term
normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t
normalReduceStep (App t1 t2)
| Just t1' <- normalReduceStep t1 = Just $ App t1' t2
| Just t2' <- normalReduceStep t2 = Just $ App t1 t2'
normalReduceStep (Lam x t)
| Just t' <- normalReduceStep t = Just $ Lam x t'
normalReduceStep _ = Nothing
normalReduce :: Term -> Term
normalReduce t
| Just t' <- normalReduceStep t = normalReduce t'
| otherwise = t
reduce :: Term -> Term
reduce = normalReduce
-- alpha-beta equivalence (for strongly normalizing terms) is obtained by
-- fully evaluating the terms using beta-reduction, then checking their
-- alpha-equivalence.
abEq :: Term -> Term -> Bool
abEq t1 t2 = aEq (reduce t1) (reduce t2)
evaluate :: String -> String
evaluate s = showNice (reduce t)
where
(t, "") = readNice s
-- Church Encodings in Lambda
churchTrue :: Term
churchTrue = lams ["t", "f"] (v "t")
churchFalse :: Term
churchFalse = lams ["t", "f"] (v "f")
cFalse :: CBool
cFalse = CBool $ \t f -> f
churchIf :: Term
churchIf = lams ["c", "then", "else"] (v "c" $$ v "then" $$ v "else")
churchNot :: Term
churchNot = lam "b" (v "b" $$ churchFalse $$ churchTrue)
cNot :: CBool -> CBool
cNot = \b -> CBool $ \t f -> cIf b f t
churchAnd :: Term
churchAnd = lams ["b1", "b2"] (v "b1" $$ v "b2" $$ churchFalse)
(&&:) :: CBool -> CBool -> CBool
(&&:) = \b1 b2 -> cIf b1 b2 cFalse
infixr 3 &&:
churchOr :: Term
churchOr = lams ["b1", "b2"] (v "b1" $$ churchTrue $$ v "b2")
(||:) :: CBool -> CBool -> CBool
(||:) = \b1 b2 -> cIf b1 cTrue b2
infixr 2 ||:
newtype CNat = CNat { cFor :: forall t. (t -> t) -> t -> t }
instance Show CNat where
show n = show $ cFor n (1 +) (0 :: Integer)
church0 :: Term
church0 = lams ["s", "z"] (v "z") -- note that it's the same as churchFalse
church1 :: Term
church1 = lams ["s", "z"] (v "s" $$ v "z")
church2 :: Term
church2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z"))
churchS :: Term
churchS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z"))
cS :: CNat -> CNat
cS = \t -> CNat $ \s z -> s (cFor t s z)
iterate' :: (Ord t, Num t) => t -> (p -> p) -> p -> p
iterate' n f a = go n
where
go n
| n <= 0 = a
| otherwise = f (go (n - 1))
churchNat :: Integer -> Term
churchNat n = lams ["s", "z"] (iterate' n (v "s" $$) (v "z"))
cNat :: (Ord p, Num p) => p -> CNat
cNat n = CNat $ \s z -> (iterate' n (s $) z)
churchPlus :: Term
churchPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z"))
(+:) :: CNat -> CNat -> CNat
(+:) = \n m -> CNat $ \s -> cFor n s . cFor m s
infixl 6 +:
churchPlus' :: Term
churchPlus' = lams ["n", "m"] (v "n" $$ churchS $$ v "m")
churchMul :: Term
churchMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s"))
(*:) :: CNat -> CNat -> CNat
(*:) = \n m -> CNat $ cFor n . cFor m
infixl 7 *:
churchMul' :: Term
churchMul' = lams ["n", "m"] (v "n" $$ (churchPlus' $$ v "m") $$ church0)
churchPow :: Term
churchPow = lams ["m", "n"] (v "n" $$ v "m")
(^:) :: CNat -> CNat -> CNat
(^:) = \m n -> CNat $ cFor n (cFor m)
infixr 8 ^:
churchPow' :: Term
churchPow' = lams ["m", "n"] (v "n" $$ (churchMul' $$ v "m") $$ church1)
churchIs0 :: Term
churchIs0 = lam "n" (v "n" $$ (churchAnd $$ churchFalse) $$ churchTrue)
cIs0 :: CNat -> CBool
cIs0 = \n -> cFor n (cFalse &&:) cTrue
churchS' :: Term
churchS' = lam "n" (v "n" $$ churchS $$ church1)
churchS'Rev0 :: Term
churchS'Rev0 = lams ["s","z"] church0
churchPred :: Term
churchPred =
lam "n"
(churchIf
$$ (churchIs0 $$ v "n")
$$ church0
$$ (v "n" $$ churchS' $$ churchS'Rev0))
churchSub :: Term
churchSub = lams ["m", "n"] (v "n" $$ churchPred $$ v "m")
(-:) :: CNat -> CNat -> CNat
(-:) = \m n -> cFor n cPred m
instance Num CNat where
(+) = (+:)
(*) = (*:)
(-) = (-:)
abs = id
signum n = cIf (cIs0 n) 0 1
fromInteger = cNat
instance Enum CNat where
toEnum = cNat
fromEnum n = cFor n succ 0
churchLte :: Term
churchLte = lams ["m", "n"] (churchIs0 $$ (churchSub $$ v "m" $$ v "n"))
(<=:) :: CNat -> CNat -> CBool
(<=:) = \m n -> cIs0 (m - n)
infix 4 <=:
churchGte :: Term
churchGte = lams ["m", "n"] (churchLte $$ v "n" $$ v "m")
(>=:) :: CNat -> CNat -> CBool
(>=:) = \m n -> n <=: m
infix 4 >=:
churchLt :: Term
churchLt = lams ["m", "n"] (churchNot $$ (churchGte $$ v "m" $$ v "n"))
(<:) :: CNat -> CNat -> CBool
(<:) = \m n -> cNot (m >=: n)
infix 4 <:
churchGt :: Term
churchGt = lams ["m", "n"] (churchLt $$ v "n" $$ v "m")
(>:) :: CNat -> CNat -> CBool
(>:) = \m n -> n <: m
infix 4 >:
churchEq :: Term
churchEq = lams ["m", "n"] (churchAnd $$ (churchLte $$ v "m" $$ v "n") $$ (churchLte $$ v "n" $$ v "m"))
(==:) :: CNat -> CNat -> CBool
(==:) = \m n -> m <=: n &&: n <=: m
instance Eq CNat where
m == n = cIf (m ==: n) True False
instance Ord CNat where
m <= n = cIf (m <=: n) True False
newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c }
instance (Show a, Show b) => Show (CPair a b) where
show p = show $ cOn p (,)
churchPair :: Term
churchPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s")
cPair :: a -> b -> CPair a b
cPair = \x y -> CPair $ \action -> action x y
churchFst :: Term
churchFst = lam "pair" (v "pair" $$ churchTrue)
cFst :: CPair a b -> a
cFst = \p -> (cOn p $ \x y -> x)
churchSnd :: Term
churchSnd = lam "pair" (v "pair" $$ churchFalse)
cSnd :: CPair a b -> b
cSnd = \p -> (cOn p $ \x y -> y)
churchPred' :: Term
churchPred' = lam "n" (churchFst $$
(v "n"
$$ lam "p" (lam "x" (churchPair $$ v "x" $$ (churchS $$ v "x"))
$$ (churchSnd $$ v "p"))
$$ (churchPair $$ church0 $$ church0)
))
cPred :: CNat -> CNat
cPred = \n -> cFst $
cFor n (\p -> (\x -> cPair x (cS x)) (cSnd p)) (cPair 0 0)
churchFactorial :: Term
churchFactorial = lam "n" (churchSnd $$
(v "n"
$$ lam "p"
(churchPair
$$ (churchS $$ (churchFst $$ v "p"))
$$ (churchMul $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p"))
)
$$ (churchPair $$ church1 $$ church1)
))
cFactorial :: CNat -> CNat
cFactorial = \n -> cSnd $ cFor n (\p -> cPair (cFst p) (cFst p * cSnd p)) (cPair 1 1)
churchFibonacci :: Term
churchFibonacci = lam "n" (churchFst $$
(v "n"
$$ lam "p"
(churchPair
$$ (churchSnd $$ v "p")
$$ (churchPlus $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p"))
)
$$ (churchPair $$ church0 $$ church1)
))
cFibonacci :: CNat -> CNat
cFibonacci = \n -> cFst $ cFor n (\p -> cPair (cSnd p) (cFst p + cSnd p)) (cPair 0 1)
churchDivMod :: Term
churchDivMod =
lams ["m", "n"]
(v "m"
$$ lam "pair"
(churchIf
$$ (churchLte $$ v "n" $$ (churchSnd $$ v "pair"))
$$ (churchPair
$$ (churchS $$ (churchFst $$ v "pair"))
$$ (churchSub
$$ (churchSnd $$ v "pair")
$$ v "n"
)
)
$$ v "pair"
)
$$ (churchPair $$ church0 $$ v "m")
)
cDivMod :: CNat -> CNat -> CPair CNat CNat
cDivMod = \m n -> cFor m (\p -> cIf (n <=: cSnd p) (cPair (cS (cFst p)) (cSnd p - n)) p) (cPair 0 m)
newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b }
instance Foldable CList where
foldr agg init xs = cFoldR xs agg init
churchNil :: Term
churchNil = lams ["agg", "init"] (v "init")
cNil :: CList a
cNil = CList $ \agg init -> init
churchCons :: Term
churchCons = lams ["x","l","agg", "init"]
(v "agg"
$$ v "x"
$$ (v "l" $$ v "agg" $$ v "init")
)
(.:) :: a -> CList a -> CList a
(.:) = \x xs -> CList $ \agg init -> agg x (cFoldR xs agg init)
churchList :: [Term] -> Term
churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil
cList :: [a] -> CList a
cList = foldr (.:) cNil
churchNatList :: [Integer] -> Term
churchNatList = churchList . map churchNat
cNatList :: [Integer] -> CList CNat
cNatList = cList . map cNat
churchSum :: Term
churchSum = lam "l" (v "l" $$ churchPlus $$ church0)
cSum :: CList CNat -> CNat
since CList is an instance of Foldable ; otherwise : \l - > cFoldR l ( + ) 0
churchIsNil :: Term
churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue)
cIsNil :: CList a -> CBool
cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue
churchHead :: Term
churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default")
cHead :: CList a -> a -> a
cHead = \l d -> cFoldR l (\x _ -> x) d
churchTail :: Term
churchTail = lam "l" (churchFst $$
(v "l"
$$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t"))
$$ (churchSnd $$ v "p"))
$$ (churchPair $$ churchNil $$ churchNil)
))
cTail :: CList a -> CList a
cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil)
cLength :: CList a -> CNat
cLength = \l -> cFoldR l (\_ n -> cS n) 0
fix :: Term
fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x")))
divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b)
divmod m n = divmod' (0, 0)
where
divmod' (x, y)
| x' <= m = divmod' (x', succ y)
| otherwise = (y, m - x)
where x' = x + n
divmod' m n =
if n == 0 then (0, m)
else
Function.fix
(\f p ->
(\x' ->
if x' > 0 then f ((,) (succ (fst p)) x')
else if (<=) n (snd p) then ((,) (succ (fst p)) 0)
else p)
((-) (snd p) n))
(0, m)
churchDivMod' :: Term
churchDivMod' = lams ["m", "n"]
(churchIs0 $$ v "n"
$$ (churchPair $$ church0 $$ v "m")
$$ (fix
$$ lams ["f", "p"]
(lam "x"
(churchIs0 $$ v "x"
$$ (churchLte $$ v "n" $$ (churchSnd $$ v "p")
$$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0)
$$ v "p"
)
$$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x"))
)
$$ (churchSub $$ (churchSnd $$ v "p") $$ v "n")
)
$$ (churchPair $$ church0 $$ v "m")
)
)
churchSudan :: Term
churchSudan = fix $$ lam "f" (lams ["n", "x", "y"]
(churchIs0 $$ v "n"
$$ (churchPlus $$ v "x" $$ v "y")
$$ (churchIs0 $$ v "y"
$$ v "x"
$$ (lam "fnpy"
(v "f" $$ (churchPred $$ v "n")
$$ v "fnpy"
$$ (churchPlus $$ v "fnpy" $$ v "y")
)
$$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y"))
)
)
))
churchAckermann :: Term
churchAckermann = fix $$ lam "A" (lams ["m", "n"]
(churchIs0 $$ v "m"
$$ (churchS $$ v "n")
$$ (churchIs0 $$ v "n"
$$ (v "A" $$ (churchPred $$ v "m") $$ church1)
$$ (v "A" $$ (churchPred $$ v "m")
$$ (v "A" $$ v "m" $$ (churchPred $$ v "n")))
)
)
)
| null | https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/LambdaChurch_20210415164230.hs | haskell | alpha-equivalence
subst u x t defines [u/x]t, i.e., substituting u for x in t
This substitution avoids variable captures so it is safe to be used when
reducing terms with free variables (e.g., if evaluating inside lambda abstractions)
^ substitution term
^ variable to be substitutes
^ term in which the substitution occurs
Normal order reduction
- like call by name
- but also reduce under lambda abstractions if no application is possible
- guarantees reaching a normal form if it exists
alpha-beta equivalence (for strongly normalizing terms) is obtained by
fully evaluating the terms using beta-reduction, then checking their
alpha-equivalence.
Church Encodings in Lambda
note that it's the same as churchFalse | module LambdaChurch where
import Data.Char (isLetter)
import Data.List ( nub )
class ShowNice a where
showNice :: a -> String
class ReadNice a where
readNice :: String -> (a, String)
data Variable
= Variable
{ name :: String
, count :: Int
}
deriving (Show, Eq, Ord)
var :: String -> Variable
var x = Variable x 0
instance ShowNice Variable where
showNice (Variable x 0) = x
showNice (Variable x cnt) = x <> "_" <> show cnt
instance ReadNice Variable where
readNice s
| null x = error $ "expected variable but found " <> s
| otherwise = (var x, s')
where
(x, s') = span isLetter s
freshVariable :: Variable -> [Variable] -> Variable
freshVariable var vars = Variable x (cnt + 1)
where
x = name var
varsWithName = filter ((== x) . name) vars
Variable _ cnt = maximum (var : varsWithName)
data Term
= V Variable
| App Term Term
| Lam Variable Term
deriving (Show)
aEq :: Term -> Term -> Bool
aEq (V x) (V x') = x == x'
aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2'
aEq (Lam x t) (Lam x' t')
| x == x' = aEq t t'
| otherwise = aEq (subst (V y) x t) (subst (V y) x' t')
where
fvT = freeVars t
fvT' = freeVars t'
allFV = nub ([x, x'] ++ fvT ++ fvT')
y = freshVariable x allFV
aEq _ _ = False
v :: String -> Term
v x = V (var x)
lam :: String -> Term -> Term
lam x = Lam (var x)
lams :: [String] -> Term -> Term
lams xs t = foldr lam t xs
($$) :: Term -> Term -> Term
($$) = App
infixl 9 $$
instance ShowNice Term where
showNice (V var) = showNice var
showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")"
showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")"
instance ReadNice Term where
readNice [] = error "Nothing to read"
readNice ('(' : '\\' : s) = (Lam var t, s'')
where
(var, '.' : s') = readNice s
(t, ')' : s'') = readNice s'
readNice ('(' : s) = (App t1 t2, s'')
where
(t1, ' ' : s') = readNice s
(t2, ')' : s'') = readNice s'
readNice s = (V var, s')
where
(var, s') = readNice s
freeVars :: Term -> [Variable]
freeVars (V var) = [var]
freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2
freeVars (Lam var t) = filter (/= var) (freeVars t)
for example [ 3 / x](x + x ) = = 3 + 3
subst
-> Term
subst u x (V y)
| x == y = u
| otherwise = V y
subst u x (App t1 t2) = App (subst u x t1) (subst u x t2)
subst u x (Lam y t)
| x == y = Lam y t
| y `notElem` fvU = Lam y (subst u x t)
| x `notElem` fvT = Lam y t
| otherwise = Lam y' (subst u x (subst (V y') y t))
where
fvT = freeVars t
fvU = freeVars u
allFV = nub ([x] ++ fvU ++ fvT)
y' = freshVariable y allFV
normalReduceStep :: Term -> Maybe Term
normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t
normalReduceStep (App t1 t2)
| Just t1' <- normalReduceStep t1 = Just $ App t1' t2
| Just t2' <- normalReduceStep t2 = Just $ App t1 t2'
normalReduceStep (Lam x t)
| Just t' <- normalReduceStep t = Just $ Lam x t'
normalReduceStep _ = Nothing
normalReduce :: Term -> Term
normalReduce t
| Just t' <- normalReduceStep t = normalReduce t'
| otherwise = t
reduce :: Term -> Term
reduce = normalReduce
abEq :: Term -> Term -> Bool
abEq t1 t2 = aEq (reduce t1) (reduce t2)
evaluate :: String -> String
evaluate s = showNice (reduce t)
where
(t, "") = readNice s
churchTrue :: Term
churchTrue = lams ["t", "f"] (v "t")
churchFalse :: Term
churchFalse = lams ["t", "f"] (v "f")
cFalse :: CBool
cFalse = CBool $ \t f -> f
churchIf :: Term
churchIf = lams ["c", "then", "else"] (v "c" $$ v "then" $$ v "else")
churchNot :: Term
churchNot = lam "b" (v "b" $$ churchFalse $$ churchTrue)
cNot :: CBool -> CBool
cNot = \b -> CBool $ \t f -> cIf b f t
churchAnd :: Term
churchAnd = lams ["b1", "b2"] (v "b1" $$ v "b2" $$ churchFalse)
(&&:) :: CBool -> CBool -> CBool
(&&:) = \b1 b2 -> cIf b1 b2 cFalse
infixr 3 &&:
churchOr :: Term
churchOr = lams ["b1", "b2"] (v "b1" $$ churchTrue $$ v "b2")
(||:) :: CBool -> CBool -> CBool
(||:) = \b1 b2 -> cIf b1 cTrue b2
infixr 2 ||:
newtype CNat = CNat { cFor :: forall t. (t -> t) -> t -> t }
instance Show CNat where
show n = show $ cFor n (1 +) (0 :: Integer)
church0 :: Term
church1 :: Term
church1 = lams ["s", "z"] (v "s" $$ v "z")
church2 :: Term
church2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z"))
churchS :: Term
churchS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z"))
cS :: CNat -> CNat
cS = \t -> CNat $ \s z -> s (cFor t s z)
iterate' :: (Ord t, Num t) => t -> (p -> p) -> p -> p
iterate' n f a = go n
where
go n
| n <= 0 = a
| otherwise = f (go (n - 1))
churchNat :: Integer -> Term
churchNat n = lams ["s", "z"] (iterate' n (v "s" $$) (v "z"))
cNat :: (Ord p, Num p) => p -> CNat
cNat n = CNat $ \s z -> (iterate' n (s $) z)
churchPlus :: Term
churchPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z"))
(+:) :: CNat -> CNat -> CNat
(+:) = \n m -> CNat $ \s -> cFor n s . cFor m s
infixl 6 +:
churchPlus' :: Term
churchPlus' = lams ["n", "m"] (v "n" $$ churchS $$ v "m")
churchMul :: Term
churchMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s"))
(*:) :: CNat -> CNat -> CNat
(*:) = \n m -> CNat $ cFor n . cFor m
infixl 7 *:
churchMul' :: Term
churchMul' = lams ["n", "m"] (v "n" $$ (churchPlus' $$ v "m") $$ church0)
churchPow :: Term
churchPow = lams ["m", "n"] (v "n" $$ v "m")
(^:) :: CNat -> CNat -> CNat
(^:) = \m n -> CNat $ cFor n (cFor m)
infixr 8 ^:
churchPow' :: Term
churchPow' = lams ["m", "n"] (v "n" $$ (churchMul' $$ v "m") $$ church1)
churchIs0 :: Term
churchIs0 = lam "n" (v "n" $$ (churchAnd $$ churchFalse) $$ churchTrue)
cIs0 :: CNat -> CBool
cIs0 = \n -> cFor n (cFalse &&:) cTrue
churchS' :: Term
churchS' = lam "n" (v "n" $$ churchS $$ church1)
churchS'Rev0 :: Term
churchS'Rev0 = lams ["s","z"] church0
churchPred :: Term
churchPred =
lam "n"
(churchIf
$$ (churchIs0 $$ v "n")
$$ church0
$$ (v "n" $$ churchS' $$ churchS'Rev0))
churchSub :: Term
churchSub = lams ["m", "n"] (v "n" $$ churchPred $$ v "m")
(-:) :: CNat -> CNat -> CNat
(-:) = \m n -> cFor n cPred m
instance Num CNat where
(+) = (+:)
(*) = (*:)
(-) = (-:)
abs = id
signum n = cIf (cIs0 n) 0 1
fromInteger = cNat
instance Enum CNat where
toEnum = cNat
fromEnum n = cFor n succ 0
churchLte :: Term
churchLte = lams ["m", "n"] (churchIs0 $$ (churchSub $$ v "m" $$ v "n"))
(<=:) :: CNat -> CNat -> CBool
(<=:) = \m n -> cIs0 (m - n)
infix 4 <=:
churchGte :: Term
churchGte = lams ["m", "n"] (churchLte $$ v "n" $$ v "m")
(>=:) :: CNat -> CNat -> CBool
(>=:) = \m n -> n <=: m
infix 4 >=:
churchLt :: Term
churchLt = lams ["m", "n"] (churchNot $$ (churchGte $$ v "m" $$ v "n"))
(<:) :: CNat -> CNat -> CBool
(<:) = \m n -> cNot (m >=: n)
infix 4 <:
churchGt :: Term
churchGt = lams ["m", "n"] (churchLt $$ v "n" $$ v "m")
(>:) :: CNat -> CNat -> CBool
(>:) = \m n -> n <: m
infix 4 >:
churchEq :: Term
churchEq = lams ["m", "n"] (churchAnd $$ (churchLte $$ v "m" $$ v "n") $$ (churchLte $$ v "n" $$ v "m"))
(==:) :: CNat -> CNat -> CBool
(==:) = \m n -> m <=: n &&: n <=: m
instance Eq CNat where
m == n = cIf (m ==: n) True False
instance Ord CNat where
m <= n = cIf (m <=: n) True False
newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c }
instance (Show a, Show b) => Show (CPair a b) where
show p = show $ cOn p (,)
churchPair :: Term
churchPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s")
cPair :: a -> b -> CPair a b
cPair = \x y -> CPair $ \action -> action x y
churchFst :: Term
churchFst = lam "pair" (v "pair" $$ churchTrue)
cFst :: CPair a b -> a
cFst = \p -> (cOn p $ \x y -> x)
churchSnd :: Term
churchSnd = lam "pair" (v "pair" $$ churchFalse)
cSnd :: CPair a b -> b
cSnd = \p -> (cOn p $ \x y -> y)
churchPred' :: Term
churchPred' = lam "n" (churchFst $$
(v "n"
$$ lam "p" (lam "x" (churchPair $$ v "x" $$ (churchS $$ v "x"))
$$ (churchSnd $$ v "p"))
$$ (churchPair $$ church0 $$ church0)
))
cPred :: CNat -> CNat
cPred = \n -> cFst $
cFor n (\p -> (\x -> cPair x (cS x)) (cSnd p)) (cPair 0 0)
churchFactorial :: Term
churchFactorial = lam "n" (churchSnd $$
(v "n"
$$ lam "p"
(churchPair
$$ (churchS $$ (churchFst $$ v "p"))
$$ (churchMul $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p"))
)
$$ (churchPair $$ church1 $$ church1)
))
cFactorial :: CNat -> CNat
cFactorial = \n -> cSnd $ cFor n (\p -> cPair (cFst p) (cFst p * cSnd p)) (cPair 1 1)
churchFibonacci :: Term
churchFibonacci = lam "n" (churchFst $$
(v "n"
$$ lam "p"
(churchPair
$$ (churchSnd $$ v "p")
$$ (churchPlus $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p"))
)
$$ (churchPair $$ church0 $$ church1)
))
cFibonacci :: CNat -> CNat
cFibonacci = \n -> cFst $ cFor n (\p -> cPair (cSnd p) (cFst p + cSnd p)) (cPair 0 1)
churchDivMod :: Term
churchDivMod =
lams ["m", "n"]
(v "m"
$$ lam "pair"
(churchIf
$$ (churchLte $$ v "n" $$ (churchSnd $$ v "pair"))
$$ (churchPair
$$ (churchS $$ (churchFst $$ v "pair"))
$$ (churchSub
$$ (churchSnd $$ v "pair")
$$ v "n"
)
)
$$ v "pair"
)
$$ (churchPair $$ church0 $$ v "m")
)
cDivMod :: CNat -> CNat -> CPair CNat CNat
cDivMod = \m n -> cFor m (\p -> cIf (n <=: cSnd p) (cPair (cS (cFst p)) (cSnd p - n)) p) (cPair 0 m)
newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b }
instance Foldable CList where
foldr agg init xs = cFoldR xs agg init
churchNil :: Term
churchNil = lams ["agg", "init"] (v "init")
cNil :: CList a
cNil = CList $ \agg init -> init
churchCons :: Term
churchCons = lams ["x","l","agg", "init"]
(v "agg"
$$ v "x"
$$ (v "l" $$ v "agg" $$ v "init")
)
(.:) :: a -> CList a -> CList a
(.:) = \x xs -> CList $ \agg init -> agg x (cFoldR xs agg init)
churchList :: [Term] -> Term
churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil
cList :: [a] -> CList a
cList = foldr (.:) cNil
churchNatList :: [Integer] -> Term
churchNatList = churchList . map churchNat
cNatList :: [Integer] -> CList CNat
cNatList = cList . map cNat
churchSum :: Term
churchSum = lam "l" (v "l" $$ churchPlus $$ church0)
cSum :: CList CNat -> CNat
since CList is an instance of Foldable ; otherwise : \l - > cFoldR l ( + ) 0
churchIsNil :: Term
churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue)
cIsNil :: CList a -> CBool
cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue
churchHead :: Term
churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default")
cHead :: CList a -> a -> a
cHead = \l d -> cFoldR l (\x _ -> x) d
churchTail :: Term
churchTail = lam "l" (churchFst $$
(v "l"
$$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t"))
$$ (churchSnd $$ v "p"))
$$ (churchPair $$ churchNil $$ churchNil)
))
cTail :: CList a -> CList a
cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil)
cLength :: CList a -> CNat
cLength = \l -> cFoldR l (\_ n -> cS n) 0
fix :: Term
fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x")))
divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b)
divmod m n = divmod' (0, 0)
where
divmod' (x, y)
| x' <= m = divmod' (x', succ y)
| otherwise = (y, m - x)
where x' = x + n
divmod' m n =
if n == 0 then (0, m)
else
Function.fix
(\f p ->
(\x' ->
if x' > 0 then f ((,) (succ (fst p)) x')
else if (<=) n (snd p) then ((,) (succ (fst p)) 0)
else p)
((-) (snd p) n))
(0, m)
churchDivMod' :: Term
churchDivMod' = lams ["m", "n"]
(churchIs0 $$ v "n"
$$ (churchPair $$ church0 $$ v "m")
$$ (fix
$$ lams ["f", "p"]
(lam "x"
(churchIs0 $$ v "x"
$$ (churchLte $$ v "n" $$ (churchSnd $$ v "p")
$$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0)
$$ v "p"
)
$$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x"))
)
$$ (churchSub $$ (churchSnd $$ v "p") $$ v "n")
)
$$ (churchPair $$ church0 $$ v "m")
)
)
churchSudan :: Term
churchSudan = fix $$ lam "f" (lams ["n", "x", "y"]
(churchIs0 $$ v "n"
$$ (churchPlus $$ v "x" $$ v "y")
$$ (churchIs0 $$ v "y"
$$ v "x"
$$ (lam "fnpy"
(v "f" $$ (churchPred $$ v "n")
$$ v "fnpy"
$$ (churchPlus $$ v "fnpy" $$ v "y")
)
$$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y"))
)
)
))
churchAckermann :: Term
churchAckermann = fix $$ lam "A" (lams ["m", "n"]
(churchIs0 $$ v "m"
$$ (churchS $$ v "n")
$$ (churchIs0 $$ v "n"
$$ (v "A" $$ (churchPred $$ v "m") $$ church1)
$$ (v "A" $$ (churchPred $$ v "m")
$$ (v "A" $$ v "m" $$ (churchPred $$ v "n")))
)
)
)
|
9a9f0740c193810fd0e84cc123f1dc8ab1b894291ae9568abccf2fb9688a8e75 | Gbury/archsat | index_test.mli | This file is free software , part of Archsat . See file " LICENSE " for more details .
val correct_qtests : QCheck.Test.t list
(** Serie of tests to verify the soundeness of the various indexes. *)
val complete_qtests : QCheck.Test.t list
(** Serie of tests to verify the soundeness of the various indexes. *)
| null | https://raw.githubusercontent.com/Gbury/archsat/322fbefa4a58023ddafb3fa1a51f8199c25cde3d/src/test/index_test.mli | ocaml | * Serie of tests to verify the soundeness of the various indexes.
* Serie of tests to verify the soundeness of the various indexes. | This file is free software , part of Archsat . See file " LICENSE " for more details .
val correct_qtests : QCheck.Test.t list
val complete_qtests : QCheck.Test.t list
|
40ec1ecce832c09985008999f9b5d444a9c1f5e63ee733cad60f26a9d32dadaf | judah/haskeline | Completion.hs | module System.Console.Haskeline.Completion(
CompletionFunc,
Completion(..),
noCompletion,
simpleCompletion,
fallbackCompletion,
-- * Word completion
completeWord,
completeWord',
completeWordWithPrev,
completeWordWithPrev',
completeQuotedWord,
-- * Filename completion
completeFilename,
listFiles,
filenameWordBreakChars
) where
import System.FilePath
import Data.List(isPrefixOf)
import Control.Monad(forM)
import System.Console.Haskeline.Directory
import System.Console.Haskeline.Monads
-- | Performs completions from the given line state.
--
The first ' String ' argument is the contents of the line to the left of the cursor ,
-- reversed.
The second ' String ' argument is the contents of the line to the right of the cursor .
--
The output ' String ' is the unused portion of the left half of the line , reversed .
type CompletionFunc m = (String,String) -> m (String, [Completion])
data Completion = Completion {replacement :: String, -- ^ Text to insert in line.
display :: String,
-- ^ Text to display when listing
-- alternatives.
isFinished :: Bool
-- ^ Whether this word should be followed by a
-- space, end quote, etc.
}
deriving (Eq, Ord, Show)
-- | Disable completion altogether.
noCompletion :: Monad m => CompletionFunc m
noCompletion (s,_) = return (s,[])
--------------
-- Word break functions
| A custom ' CompletionFunc ' which completes the word immediately to the left of the cursor .
--
-- A word begins either at the start of the line or after an unescaped whitespace character.
completeWord :: Monad m => Maybe Char
-- ^ An optional escape character
-> [Char]-- ^ Characters which count as whitespace
-> (String -> m [Completion]) -- ^ Function to produce a list of possible completions
-> CompletionFunc m
completeWord esc ws = completeWordWithPrev esc ws . const
-- | The same as 'completeWord' but takes a predicate for the whitespace characters
completeWord' :: Monad m => Maybe Char
-- ^ An optional escape character
-> (Char -> Bool) -- ^ Characters which count as whitespace
-> (String -> m [Completion]) -- ^ Function to produce a list of possible completions
-> CompletionFunc m
completeWord' esc ws = completeWordWithPrev' esc ws . const
| A custom ' CompletionFunc ' which completes the word immediately to the left of the cursor ,
-- and takes into account the line contents to the left of the word.
--
-- A word begins either at the start of the line or after an unescaped whitespace character.
completeWordWithPrev :: Monad m => Maybe Char
-- ^ An optional escape character
-> [Char]-- ^ Characters which count as whitespace
-> (String -> String -> m [Completion])
^ Function to produce a list of possible completions . The first argument is the
line contents to the left of the word , reversed . The second argument is the word
-- to be completed.
-> CompletionFunc m
completeWordWithPrev esc ws = completeWordWithPrev' esc (`elem` ws)
-- | The same as 'completeWordWithPrev' but takes a predicate for the whitespace characters
completeWordWithPrev' :: Monad m => Maybe Char
-- ^ An optional escape character
-> (Char -> Bool) -- ^ Characters which count as whitespace
-> (String -> String -> m [Completion])
^ Function to produce a list of possible completions . The first argument is the
line contents to the left of the word , reversed . The second argument is the word
-- to be completed.
-> CompletionFunc m
completeWordWithPrev' esc wpred f (line, _) = do
let (word,rest) = case esc of
Nothing -> break wpred line
Just e -> escapedBreak e line
completions <- f rest (reverse word)
return (rest,map (escapeReplacement esc wpred) completions)
where
escapedBreak e (c:d:cs) | d == e && (c == e || wpred c)
= let (xs,ys) = escapedBreak e cs in (c:xs,ys)
escapedBreak e (c:cs) | not $ wpred c
= let (xs,ys) = escapedBreak e cs in (c:xs,ys)
escapedBreak _ cs = ("",cs)
-- | Create a finished completion out of the given word.
simpleCompletion :: String -> Completion
simpleCompletion = completion
-- NOTE: this is the same as for readline, except that I took out the '\\'
-- so they can be used as a path separator.
filenameWordBreakChars :: String
filenameWordBreakChars = " \t\n`@$><=;|&{("
-- A completion command for file and folder names.
completeFilename :: MonadIO m => CompletionFunc m
completeFilename = completeQuotedWord (Just '\\') "\"'" listFiles
$ completeWord (Just '\\') ("\"\'" ++ filenameWordBreakChars)
listFiles
completion :: String -> Completion
completion str = Completion str str True
setReplacement :: (String -> String) -> Completion -> Completion
setReplacement f c = c {replacement = f $ replacement c}
escapeReplacement :: Maybe Char -> (Char -> Bool) -> Completion -> Completion
escapeReplacement esc wpred f = case esc of
Nothing -> f
Just e -> f {replacement = escape e (replacement f)}
where
escape e (c:cs) | c == e || wpred c = e : c : escape e cs
| otherwise = c : escape e cs
escape _ "" = ""
---------
-- Quoted completion
completeQuotedWord :: Monad m => Maybe Char -- ^ An optional escape character
-> [Char] -- ^ Characters which set off quotes
-> (String -> m [Completion]) -- ^ Function to produce a list of possible completions
-> CompletionFunc m -- ^ Alternate completion to perform if the
-- cursor is not at a quoted word
-> CompletionFunc m
completeQuotedWord esc qs completer alterative line@(left,_)
= case splitAtQuote esc qs left of
Just (w,rest) | isUnquoted esc qs rest -> do
cs <- completer (reverse w)
return (rest, map (addQuotes . escapeReplacement esc (`elem` qs)) cs)
_ -> alterative line
addQuotes :: Completion -> Completion
addQuotes c = if isFinished c
then c {replacement = "\"" ++ replacement c ++ "\""}
else c {replacement = "\"" ++ replacement c}
splitAtQuote :: Maybe Char -> String -> String -> Maybe (String,String)
splitAtQuote esc qs line = case line of
c:e:cs | isEscape e && isEscapable c
-> do
(w,rest) <- splitAtQuote esc qs cs
return (c:w,rest)
q:cs | isQuote q -> Just ("",cs)
c:cs -> do
(w,rest) <- splitAtQuote esc qs cs
return (c:w,rest)
"" -> Nothing
where
isQuote = (`elem` qs)
isEscape c = Just c == esc
isEscapable c = isEscape c || isQuote c
isUnquoted :: Maybe Char -> String -> String -> Bool
isUnquoted esc qs s = case splitAtQuote esc qs s of
Just (_,s') -> not (isUnquoted esc qs s')
_ -> True
-- | List all of the files or folders beginning with this path.
listFiles :: MonadIO m => FilePath -> m [Completion]
listFiles path = liftIO $ do
fixedDir <- fixPath dir
dirExists <- doesDirectoryExist fixedDir
-- get all of the files in that directory, as basenames
allFiles <- if not dirExists
then return []
else fmap (map completion . filterPrefix)
$ getDirectoryContents fixedDir
-- The replacement text should include the directory part, and also
-- have a trailing slash if it's itself a directory.
forM allFiles $ \c -> do
isDir <- doesDirectoryExist (fixedDir </> replacement c)
return $ setReplacement fullName $ alterIfDir isDir c
where
(dir, file) = splitFileName path
filterPrefix = filter (\f -> notElem f [".",".."]
&& file `isPrefixOf` f)
alterIfDir False c = c
alterIfDir True c = c {replacement = addTrailingPathSeparator (replacement c),
isFinished = False}
fullName = replaceFileName path
turn a user - visible path into an internal version useable by System . FilePath .
fixPath :: String -> IO String
For versions of filepath < 1.2
fixPath "" = return "."
fixPath ('~':c:path) | isPathSeparator c = do
home <- getHomeDirectory
return (home </> path)
fixPath path = return path
| If the first completer produces no suggestions , fallback to the second
-- completer's output.
fallbackCompletion :: Monad m => CompletionFunc m -> CompletionFunc m -> CompletionFunc m
fallbackCompletion a b input = do
aCompletions <- a input
if null (snd aCompletions)
then b input
else return aCompletions
| null | https://raw.githubusercontent.com/judah/haskeline/bcce5ca0878df935282cc9a1aca9b344a8b1eacc/System/Console/Haskeline/Completion.hs | haskell | * Word completion
* Filename completion
| Performs completions from the given line state.
reversed.
^ Text to insert in line.
^ Text to display when listing
alternatives.
^ Whether this word should be followed by a
space, end quote, etc.
| Disable completion altogether.
------------
Word break functions
A word begins either at the start of the line or after an unescaped whitespace character.
^ An optional escape character
^ Characters which count as whitespace
^ Function to produce a list of possible completions
| The same as 'completeWord' but takes a predicate for the whitespace characters
^ An optional escape character
^ Characters which count as whitespace
^ Function to produce a list of possible completions
and takes into account the line contents to the left of the word.
A word begins either at the start of the line or after an unescaped whitespace character.
^ An optional escape character
^ Characters which count as whitespace
to be completed.
| The same as 'completeWordWithPrev' but takes a predicate for the whitespace characters
^ An optional escape character
^ Characters which count as whitespace
to be completed.
| Create a finished completion out of the given word.
NOTE: this is the same as for readline, except that I took out the '\\'
so they can be used as a path separator.
A completion command for file and folder names.
-------
Quoted completion
^ An optional escape character
^ Characters which set off quotes
^ Function to produce a list of possible completions
^ Alternate completion to perform if the
cursor is not at a quoted word
| List all of the files or folders beginning with this path.
get all of the files in that directory, as basenames
The replacement text should include the directory part, and also
have a trailing slash if it's itself a directory.
completer's output. | module System.Console.Haskeline.Completion(
CompletionFunc,
Completion(..),
noCompletion,
simpleCompletion,
fallbackCompletion,
completeWord,
completeWord',
completeWordWithPrev,
completeWordWithPrev',
completeQuotedWord,
completeFilename,
listFiles,
filenameWordBreakChars
) where
import System.FilePath
import Data.List(isPrefixOf)
import Control.Monad(forM)
import System.Console.Haskeline.Directory
import System.Console.Haskeline.Monads
The first ' String ' argument is the contents of the line to the left of the cursor ,
The second ' String ' argument is the contents of the line to the right of the cursor .
The output ' String ' is the unused portion of the left half of the line , reversed .
type CompletionFunc m = (String,String) -> m (String, [Completion])
display :: String,
isFinished :: Bool
}
deriving (Eq, Ord, Show)
noCompletion :: Monad m => CompletionFunc m
noCompletion (s,_) = return (s,[])
| A custom ' CompletionFunc ' which completes the word immediately to the left of the cursor .
completeWord :: Monad m => Maybe Char
-> CompletionFunc m
completeWord esc ws = completeWordWithPrev esc ws . const
completeWord' :: Monad m => Maybe Char
-> CompletionFunc m
completeWord' esc ws = completeWordWithPrev' esc ws . const
| A custom ' CompletionFunc ' which completes the word immediately to the left of the cursor ,
completeWordWithPrev :: Monad m => Maybe Char
-> (String -> String -> m [Completion])
^ Function to produce a list of possible completions . The first argument is the
line contents to the left of the word , reversed . The second argument is the word
-> CompletionFunc m
completeWordWithPrev esc ws = completeWordWithPrev' esc (`elem` ws)
completeWordWithPrev' :: Monad m => Maybe Char
-> (String -> String -> m [Completion])
^ Function to produce a list of possible completions . The first argument is the
line contents to the left of the word , reversed . The second argument is the word
-> CompletionFunc m
completeWordWithPrev' esc wpred f (line, _) = do
let (word,rest) = case esc of
Nothing -> break wpred line
Just e -> escapedBreak e line
completions <- f rest (reverse word)
return (rest,map (escapeReplacement esc wpred) completions)
where
escapedBreak e (c:d:cs) | d == e && (c == e || wpred c)
= let (xs,ys) = escapedBreak e cs in (c:xs,ys)
escapedBreak e (c:cs) | not $ wpred c
= let (xs,ys) = escapedBreak e cs in (c:xs,ys)
escapedBreak _ cs = ("",cs)
simpleCompletion :: String -> Completion
simpleCompletion = completion
filenameWordBreakChars :: String
filenameWordBreakChars = " \t\n`@$><=;|&{("
completeFilename :: MonadIO m => CompletionFunc m
completeFilename = completeQuotedWord (Just '\\') "\"'" listFiles
$ completeWord (Just '\\') ("\"\'" ++ filenameWordBreakChars)
listFiles
completion :: String -> Completion
completion str = Completion str str True
setReplacement :: (String -> String) -> Completion -> Completion
setReplacement f c = c {replacement = f $ replacement c}
escapeReplacement :: Maybe Char -> (Char -> Bool) -> Completion -> Completion
escapeReplacement esc wpred f = case esc of
Nothing -> f
Just e -> f {replacement = escape e (replacement f)}
where
escape e (c:cs) | c == e || wpred c = e : c : escape e cs
| otherwise = c : escape e cs
escape _ "" = ""
-> CompletionFunc m
completeQuotedWord esc qs completer alterative line@(left,_)
= case splitAtQuote esc qs left of
Just (w,rest) | isUnquoted esc qs rest -> do
cs <- completer (reverse w)
return (rest, map (addQuotes . escapeReplacement esc (`elem` qs)) cs)
_ -> alterative line
addQuotes :: Completion -> Completion
addQuotes c = if isFinished c
then c {replacement = "\"" ++ replacement c ++ "\""}
else c {replacement = "\"" ++ replacement c}
splitAtQuote :: Maybe Char -> String -> String -> Maybe (String,String)
splitAtQuote esc qs line = case line of
c:e:cs | isEscape e && isEscapable c
-> do
(w,rest) <- splitAtQuote esc qs cs
return (c:w,rest)
q:cs | isQuote q -> Just ("",cs)
c:cs -> do
(w,rest) <- splitAtQuote esc qs cs
return (c:w,rest)
"" -> Nothing
where
isQuote = (`elem` qs)
isEscape c = Just c == esc
isEscapable c = isEscape c || isQuote c
isUnquoted :: Maybe Char -> String -> String -> Bool
isUnquoted esc qs s = case splitAtQuote esc qs s of
Just (_,s') -> not (isUnquoted esc qs s')
_ -> True
listFiles :: MonadIO m => FilePath -> m [Completion]
listFiles path = liftIO $ do
fixedDir <- fixPath dir
dirExists <- doesDirectoryExist fixedDir
allFiles <- if not dirExists
then return []
else fmap (map completion . filterPrefix)
$ getDirectoryContents fixedDir
forM allFiles $ \c -> do
isDir <- doesDirectoryExist (fixedDir </> replacement c)
return $ setReplacement fullName $ alterIfDir isDir c
where
(dir, file) = splitFileName path
filterPrefix = filter (\f -> notElem f [".",".."]
&& file `isPrefixOf` f)
alterIfDir False c = c
alterIfDir True c = c {replacement = addTrailingPathSeparator (replacement c),
isFinished = False}
fullName = replaceFileName path
turn a user - visible path into an internal version useable by System . FilePath .
fixPath :: String -> IO String
For versions of filepath < 1.2
fixPath "" = return "."
fixPath ('~':c:path) | isPathSeparator c = do
home <- getHomeDirectory
return (home </> path)
fixPath path = return path
| If the first completer produces no suggestions , fallback to the second
fallbackCompletion :: Monad m => CompletionFunc m -> CompletionFunc m -> CompletionFunc m
fallbackCompletion a b input = do
aCompletions <- a input
if null (snd aCompletions)
then b input
else return aCompletions
|
ba4e2486ba2543869ed3733a4295ee73a832aa93f50372e6ffd0afa0f09ab306 | ejgallego/coq-lsp | parsing.mli | module Parsable : sig
type t
val make : ?loc:Loc.t -> (unit, char) Gramlib.Stream.t -> t
val loc : t -> Loc.t
end
val parse : st:State.t -> Parsable.t -> (Ast.t option, Loc.t) Protect.E.t
val discard_to_dot : Parsable.t -> unit
| null | https://raw.githubusercontent.com/ejgallego/coq-lsp/f72982922d55689f9397283c525485ad26e952de/coq/parsing.mli | ocaml | module Parsable : sig
type t
val make : ?loc:Loc.t -> (unit, char) Gramlib.Stream.t -> t
val loc : t -> Loc.t
end
val parse : st:State.t -> Parsable.t -> (Ast.t option, Loc.t) Protect.E.t
val discard_to_dot : Parsable.t -> unit
|
|
2b3a59a5bdd3b1be264f81e3f56a77a0971638395e0efb9bb606cb96b462c89b | Decentralized-Pictures/T4L3NT | test_gas_costs.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2020 Nomadic Labs , < >
(* *)
(* 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. *)
(* *)
(*****************************************************************************)
(** Testing
-------
Component: Protocol (gas costs)
Invocation: dune exec src/proto_alpha/lib_protocol/test/main.exe -- test "^gas cost functions$"
Subject: Gas costs
Current limitations: for maps, sets & compare, we only test
integer comparable keys.
*)
open Protocol
module S = Saturation_repr
let dummy_list = Script_list.(cons 42 empty)
let forty_two = Alpha_context.Script_int.of_int 42
let forty_two_n = Alpha_context.Script_int.abs forty_two
let dummy_set =
let open Script_set in
update forty_two true (empty Script_typed_ir.(int_key ~annot:None))
let dummy_map =
let open Script_map in
update
forty_two
(Some forty_two)
(empty Script_typed_ir.(int_key ~annot:None))
let dummy_timestamp = Alpha_context.Script_timestamp.of_zint (Z.of_int 42)
let dummy_pk =
Signature.Public_key.of_b58check_exn
"edpkuFrRoDSEbJYgxRtLx2ps82UdaYc1WwfS9sE11yhauZt5DgCHbU"
let dummy_bytes = Bytes.of_string "dummy"
let dummy_string =
match Alpha_context.Script_string.of_string "dummy" with
| Ok s -> s
| Error _ -> assert false
let dummy_ty = Script_typed_ir.never_t ~annot:None
let free = ["balance"; "bool"; "parsing_unit"; "unparsing_unit"]
(* /!\ The compiler will only complain if costs are _removed_ /!\*)
let all_interpreter_costs =
let open Michelson_v1_gas.Cost_of.Interpreter in
[
("drop", drop);
("dup", dup);
("swap", swap);
("cons_some", cons_some);
("cons_none", cons_none);
("if_none", if_none);
("cons_pair", cons_pair);
("car", car);
("cdr", cdr);
("cons_left", cons_left);
("cons_right", cons_right);
("if_left", if_left);
("cons_list", cons_list);
("nil", nil);
("if_cons", if_cons);
("list_map", list_map dummy_list);
("list_size", list_size);
("list_iter", list_iter dummy_list);
("empty_set", empty_set);
("set_iter", set_iter dummy_set);
("set_mem", set_mem forty_two dummy_set);
("set_update", set_update forty_two dummy_set);
("set_size", set_size);
("empty_map", empty_map);
("map_map", map_map dummy_map);
("map_iter", map_iter dummy_map);
("map_mem", map_mem forty_two dummy_map);
("map_get", map_get forty_two dummy_map);
("map_update", map_update forty_two dummy_map);
("map_size", map_size);
("add_seconds_timestamp", add_seconds_timestamp forty_two dummy_timestamp);
("sub_timestamp_seconds", sub_timestamp_seconds dummy_timestamp forty_two);
("diff_timestamps", diff_timestamps dummy_timestamp dummy_timestamp);
("concat_string_pair", concat_string_pair dummy_string dummy_string);
("slice_string", slice_string dummy_string);
("string_size", string_size);
("concat_bytes_pair", concat_bytes_pair dummy_bytes dummy_bytes);
("slice_bytes", slice_bytes dummy_bytes);
("bytes_size", bytes_size);
("add_tez", add_tez);
("sub_tez", sub_tez);
("mul_teznat", mul_teznat);
("bool_or", bool_or);
("bool_and", bool_and);
("bool_xor", bool_xor);
("bool_not", bool_not);
("is_nat", is_nat);
("abs_int", abs_int forty_two);
("int_nat", int_nat);
("neg", neg forty_two);
("add_int", add_int forty_two forty_two);
("sub_int", sub_int forty_two forty_two);
("mul_int", mul_int forty_two forty_two);
("ediv_teznat", ediv_teznat Alpha_context.Tez.fifty_cents forty_two);
("ediv_tez", ediv_tez);
("ediv_int", ediv_int forty_two (Alpha_context.Script_int.of_int 1));
("eq", eq);
("lsl_nat", lsl_nat forty_two);
("lsr_nat", lsr_nat forty_two);
("or_nat", or_nat forty_two forty_two);
("and_nat", and_nat forty_two forty_two);
("xor_nat", xor_nat forty_two forty_two);
("not_int", not_int forty_two);
("if_", if_);
("loop", loop);
("loop_left", loop_left);
("dip", dip);
("check_signature", check_signature dummy_pk dummy_bytes);
("blake2b", blake2b dummy_bytes);
("sha256", sha256 dummy_bytes);
("sha512", sha512 dummy_bytes);
("dign", dign 42);
("dugn", dugn 42);
("dipn", dipn 42);
("dropn", dropn 42);
("neq", neq);
( "compare",
compare Script_typed_ir.(int_key ~annot:None) forty_two forty_two );
( "concat_string_precheck",
concat_string_precheck Script_list.(cons "42" empty) );
("concat_string", concat_string (S.safe_int 42));
("concat_bytes", concat_bytes (S.safe_int 42));
("exec", exec);
("apply", apply);
("lambda", lambda);
("address", address);
("contract", contract);
("transfer_tokens", transfer_tokens);
("implicit_account", implicit_account);
("create_contract", create_contract);
("set_delegate", set_delegate);
(* balance is free *)
("balance", balance);
("level", level);
("now", now);
("hash_key", hash_key dummy_pk);
("source", source);
("sender", sender);
("self", self);
("self_address", self_address);
("amount", amount);
("chain_id", chain_id);
("unpack_failed", unpack_failed "dummy");
]
(* /!\ The compiler will only complain if costs are _removed_ /!\*)
let all_parsing_costs =
let open Michelson_v1_gas.Cost_of.Typechecking in
[
("public_key_optimized", public_key_optimized);
("public_key_readable", public_key_readable);
("key_hash_optimized", key_hash_optimized);
("key_hash_readable", key_hash_readable);
("signature_optimized", signature_optimized);
("signature_readable", signature_readable);
("chain_id_optimized", chain_id_optimized);
("chain_id_readable", chain_id_readable);
("address_optimized", address_optimized);
("contract_optimized", contract_optimized);
("contract_readable", contract_readable);
("check_printable", check_printable "dummy");
("merge_cycle", merge_cycle);
("parse_type_cycle", parse_type_cycle);
("parse_instr_cycle", parse_instr_cycle);
("parse_data_cycle", parse_data_cycle);
("bool", bool);
("parsing_unit", unit);
("timestamp_readable", timestamp_readable);
("contract", contract);
("contract_exists", contract_exists);
("proof_argument", proof_argument 42);
]
(* /!\ The compiler will only complain if costs are _removed_ /!\*)
let all_unparsing_costs =
let open Michelson_v1_gas.Cost_of.Unparsing in
[
("public_key_optimized", public_key_optimized);
("public_key_readable", public_key_readable);
("key_hash_optimized", key_hash_optimized);
("key_hash_readable", key_hash_readable);
("signature_optimized", signature_optimized);
("signature_readable", signature_readable);
("chain_id_optimized", chain_id_optimized);
("chain_id_readable", chain_id_readable);
("timestamp_readable", timestamp_readable);
("address_optimized", address_optimized);
("contract_optimized", contract_optimized);
("contract_readable", contract_readable);
("unparse_type", unparse_type dummy_ty);
("unparse_instr_cycle", unparse_instr_cycle);
("unparse_data_cycle", unparse_data_cycle);
("unparsing_unit", unit);
("contract", contract);
("operation", operation dummy_bytes);
]
(* /!\ The compiler will only complain if costs are _removed_ /!\*)
let all_io_costs =
let open Storage_costs in
[
("read_access 0 0", read_access ~path_length:0 ~read_bytes:0);
("read_access 1 0", read_access ~path_length:1 ~read_bytes:0);
("read_access 0 1", read_access ~path_length:0 ~read_bytes:1);
("read_access 1 1", read_access ~path_length:1 ~read_bytes:1);
("write_access 0", write_access ~written_bytes:0);
("write_access 1", write_access ~written_bytes:1);
]
(* Here we're using knowledge of the internal representation of costs to
cast them to S ... *)
let cast_cost_to_s (c : Alpha_context.Gas.cost) : _ S.t =
Data_encoding.Binary.to_bytes_exn Alpha_context.Gas.cost_encoding c
|> Data_encoding.Binary.of_bytes_exn S.n_encoding
(** Checks that all costs are positive values. *)
let test_cost_reprs_are_all_positive list () =
List.iter_es
(fun (cost_name, cost) ->
if S.(cost > S.zero) then return_unit
else if S.equal cost S.zero && List.mem ~equal:String.equal cost_name free
then return_unit
else
fail
(Exn
(Failure (Format.asprintf "Gas cost test \"%s\" failed" cost_name))))
list
(** Checks that all costs are positive values. *)
let test_costs_are_all_positive list () =
let list =
List.map (fun (cost_name, cost) -> (cost_name, cast_cost_to_s cost)) list
in
test_cost_reprs_are_all_positive list ()
let tests =
[
Tztest.tztest
"Positivity of interpreter costs"
`Quick
(test_costs_are_all_positive all_interpreter_costs);
Tztest.tztest
"Positivity of typechecking costs"
`Quick
(test_costs_are_all_positive all_parsing_costs);
Tztest.tztest
"Positivity of unparsing costs"
`Quick
(test_costs_are_all_positive all_unparsing_costs);
Tztest.tztest
"Positivity of io costs"
`Quick
(test_cost_reprs_are_all_positive all_io_costs);
]
| null | https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/proto_alpha/lib_protocol/test/test_gas_costs.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
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.
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
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
* Testing
-------
Component: Protocol (gas costs)
Invocation: dune exec src/proto_alpha/lib_protocol/test/main.exe -- test "^gas cost functions$"
Subject: Gas costs
Current limitations: for maps, sets & compare, we only test
integer comparable keys.
/!\ The compiler will only complain if costs are _removed_ /!\
balance is free
/!\ The compiler will only complain if costs are _removed_ /!\
/!\ The compiler will only complain if costs are _removed_ /!\
/!\ The compiler will only complain if costs are _removed_ /!\
Here we're using knowledge of the internal representation of costs to
cast them to S ...
* Checks that all costs are positive values.
* Checks that all costs are positive values. | Copyright ( c ) 2020 Nomadic Labs , < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
open Protocol
module S = Saturation_repr
let dummy_list = Script_list.(cons 42 empty)
let forty_two = Alpha_context.Script_int.of_int 42
let forty_two_n = Alpha_context.Script_int.abs forty_two
let dummy_set =
let open Script_set in
update forty_two true (empty Script_typed_ir.(int_key ~annot:None))
let dummy_map =
let open Script_map in
update
forty_two
(Some forty_two)
(empty Script_typed_ir.(int_key ~annot:None))
let dummy_timestamp = Alpha_context.Script_timestamp.of_zint (Z.of_int 42)
let dummy_pk =
Signature.Public_key.of_b58check_exn
"edpkuFrRoDSEbJYgxRtLx2ps82UdaYc1WwfS9sE11yhauZt5DgCHbU"
let dummy_bytes = Bytes.of_string "dummy"
let dummy_string =
match Alpha_context.Script_string.of_string "dummy" with
| Ok s -> s
| Error _ -> assert false
let dummy_ty = Script_typed_ir.never_t ~annot:None
let free = ["balance"; "bool"; "parsing_unit"; "unparsing_unit"]
let all_interpreter_costs =
let open Michelson_v1_gas.Cost_of.Interpreter in
[
("drop", drop);
("dup", dup);
("swap", swap);
("cons_some", cons_some);
("cons_none", cons_none);
("if_none", if_none);
("cons_pair", cons_pair);
("car", car);
("cdr", cdr);
("cons_left", cons_left);
("cons_right", cons_right);
("if_left", if_left);
("cons_list", cons_list);
("nil", nil);
("if_cons", if_cons);
("list_map", list_map dummy_list);
("list_size", list_size);
("list_iter", list_iter dummy_list);
("empty_set", empty_set);
("set_iter", set_iter dummy_set);
("set_mem", set_mem forty_two dummy_set);
("set_update", set_update forty_two dummy_set);
("set_size", set_size);
("empty_map", empty_map);
("map_map", map_map dummy_map);
("map_iter", map_iter dummy_map);
("map_mem", map_mem forty_two dummy_map);
("map_get", map_get forty_two dummy_map);
("map_update", map_update forty_two dummy_map);
("map_size", map_size);
("add_seconds_timestamp", add_seconds_timestamp forty_two dummy_timestamp);
("sub_timestamp_seconds", sub_timestamp_seconds dummy_timestamp forty_two);
("diff_timestamps", diff_timestamps dummy_timestamp dummy_timestamp);
("concat_string_pair", concat_string_pair dummy_string dummy_string);
("slice_string", slice_string dummy_string);
("string_size", string_size);
("concat_bytes_pair", concat_bytes_pair dummy_bytes dummy_bytes);
("slice_bytes", slice_bytes dummy_bytes);
("bytes_size", bytes_size);
("add_tez", add_tez);
("sub_tez", sub_tez);
("mul_teznat", mul_teznat);
("bool_or", bool_or);
("bool_and", bool_and);
("bool_xor", bool_xor);
("bool_not", bool_not);
("is_nat", is_nat);
("abs_int", abs_int forty_two);
("int_nat", int_nat);
("neg", neg forty_two);
("add_int", add_int forty_two forty_two);
("sub_int", sub_int forty_two forty_two);
("mul_int", mul_int forty_two forty_two);
("ediv_teznat", ediv_teznat Alpha_context.Tez.fifty_cents forty_two);
("ediv_tez", ediv_tez);
("ediv_int", ediv_int forty_two (Alpha_context.Script_int.of_int 1));
("eq", eq);
("lsl_nat", lsl_nat forty_two);
("lsr_nat", lsr_nat forty_two);
("or_nat", or_nat forty_two forty_two);
("and_nat", and_nat forty_two forty_two);
("xor_nat", xor_nat forty_two forty_two);
("not_int", not_int forty_two);
("if_", if_);
("loop", loop);
("loop_left", loop_left);
("dip", dip);
("check_signature", check_signature dummy_pk dummy_bytes);
("blake2b", blake2b dummy_bytes);
("sha256", sha256 dummy_bytes);
("sha512", sha512 dummy_bytes);
("dign", dign 42);
("dugn", dugn 42);
("dipn", dipn 42);
("dropn", dropn 42);
("neq", neq);
( "compare",
compare Script_typed_ir.(int_key ~annot:None) forty_two forty_two );
( "concat_string_precheck",
concat_string_precheck Script_list.(cons "42" empty) );
("concat_string", concat_string (S.safe_int 42));
("concat_bytes", concat_bytes (S.safe_int 42));
("exec", exec);
("apply", apply);
("lambda", lambda);
("address", address);
("contract", contract);
("transfer_tokens", transfer_tokens);
("implicit_account", implicit_account);
("create_contract", create_contract);
("set_delegate", set_delegate);
("balance", balance);
("level", level);
("now", now);
("hash_key", hash_key dummy_pk);
("source", source);
("sender", sender);
("self", self);
("self_address", self_address);
("amount", amount);
("chain_id", chain_id);
("unpack_failed", unpack_failed "dummy");
]
let all_parsing_costs =
let open Michelson_v1_gas.Cost_of.Typechecking in
[
("public_key_optimized", public_key_optimized);
("public_key_readable", public_key_readable);
("key_hash_optimized", key_hash_optimized);
("key_hash_readable", key_hash_readable);
("signature_optimized", signature_optimized);
("signature_readable", signature_readable);
("chain_id_optimized", chain_id_optimized);
("chain_id_readable", chain_id_readable);
("address_optimized", address_optimized);
("contract_optimized", contract_optimized);
("contract_readable", contract_readable);
("check_printable", check_printable "dummy");
("merge_cycle", merge_cycle);
("parse_type_cycle", parse_type_cycle);
("parse_instr_cycle", parse_instr_cycle);
("parse_data_cycle", parse_data_cycle);
("bool", bool);
("parsing_unit", unit);
("timestamp_readable", timestamp_readable);
("contract", contract);
("contract_exists", contract_exists);
("proof_argument", proof_argument 42);
]
let all_unparsing_costs =
let open Michelson_v1_gas.Cost_of.Unparsing in
[
("public_key_optimized", public_key_optimized);
("public_key_readable", public_key_readable);
("key_hash_optimized", key_hash_optimized);
("key_hash_readable", key_hash_readable);
("signature_optimized", signature_optimized);
("signature_readable", signature_readable);
("chain_id_optimized", chain_id_optimized);
("chain_id_readable", chain_id_readable);
("timestamp_readable", timestamp_readable);
("address_optimized", address_optimized);
("contract_optimized", contract_optimized);
("contract_readable", contract_readable);
("unparse_type", unparse_type dummy_ty);
("unparse_instr_cycle", unparse_instr_cycle);
("unparse_data_cycle", unparse_data_cycle);
("unparsing_unit", unit);
("contract", contract);
("operation", operation dummy_bytes);
]
let all_io_costs =
let open Storage_costs in
[
("read_access 0 0", read_access ~path_length:0 ~read_bytes:0);
("read_access 1 0", read_access ~path_length:1 ~read_bytes:0);
("read_access 0 1", read_access ~path_length:0 ~read_bytes:1);
("read_access 1 1", read_access ~path_length:1 ~read_bytes:1);
("write_access 0", write_access ~written_bytes:0);
("write_access 1", write_access ~written_bytes:1);
]
let cast_cost_to_s (c : Alpha_context.Gas.cost) : _ S.t =
Data_encoding.Binary.to_bytes_exn Alpha_context.Gas.cost_encoding c
|> Data_encoding.Binary.of_bytes_exn S.n_encoding
let test_cost_reprs_are_all_positive list () =
List.iter_es
(fun (cost_name, cost) ->
if S.(cost > S.zero) then return_unit
else if S.equal cost S.zero && List.mem ~equal:String.equal cost_name free
then return_unit
else
fail
(Exn
(Failure (Format.asprintf "Gas cost test \"%s\" failed" cost_name))))
list
let test_costs_are_all_positive list () =
let list =
List.map (fun (cost_name, cost) -> (cost_name, cast_cost_to_s cost)) list
in
test_cost_reprs_are_all_positive list ()
let tests =
[
Tztest.tztest
"Positivity of interpreter costs"
`Quick
(test_costs_are_all_positive all_interpreter_costs);
Tztest.tztest
"Positivity of typechecking costs"
`Quick
(test_costs_are_all_positive all_parsing_costs);
Tztest.tztest
"Positivity of unparsing costs"
`Quick
(test_costs_are_all_positive all_unparsing_costs);
Tztest.tztest
"Positivity of io costs"
`Quick
(test_cost_reprs_are_all_positive all_io_costs);
]
|
f652f25398a8db00db13398be29d4fe1c6b76eb0e5dfc189f9026ebf6f687e1c | hirokai/PaperServer | Resource.hs | # LANGUAGE TemplateHaskell #
-- Handler.Resource
module Handler.Resource (
getResourceR
, getResourcesForPaperR
, postUploadResourceR
, postAttachFileR
, getAttachmentR
)
where
import Import
import qualified Data.Text as T
import Data.List hiding (insert)
import System.Directory (doesFileExist)
import qualified Data.ByteString as B
import qualified Data.ByteString.Base64 as B64
import Data.Text.Encoding
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Aeson as Ae
import Handler.Utils (requireAuthId')
import Model.PaperMongo (getPaperDB,getPaperMisc,updatePaperMisc)
-- Returns the resource list for the specified paper.
-- Client will download the image files (if not yet) and send them to server.
getResourcesForPaperR :: PaperId -> Handler TypedContent
getResourcesForPaperR pid = do
email <- requireAuthId'
mp <- getPaperDB email pid
case mp of
Just paper -> do
let title = citationTitle $ paperCitation paper
let urls = (map figureImg . paperFigures) paper ++
((map resourceUrl . paperResources) paper)
ids <- mapM (liftIO . resourceId) urls
let resources = zipWith (\mi u -> object (["exists" .= isJust mi, "url" .= u] ++ maybe [] (\i -> ["id" .= i]) mi)) ids urls
return $ toTypedContent $ object ["success" .= True, "resources" .= resources]
Nothing -> do
return $ toTypedContent $ object ["success" .= False, "message" .= ("ID not found."::Text)]
resourceId :: Url -> IO (Maybe Text)
resourceId url = do
let rid = mkFileName (T.unpack url)
ex <- doesFileExist (resourceRootFolder ++ rid)
return $ if ex then Just (T.pack rid) else Nothing
getResourceR :: String -> Handler ()
getResourceR hash = do
email <- requireAuthId'
-- liftIO $ putStrLn hash
sendFile ctype (resourceRootFolder++hash)
where
-- FIXME: Currently this does not have any effect.
ctype = case find (`isSuffixOf` hash) [".gif",".jpg",".jpeg",".png"] of
-- _ -> typeGif
Just ".gif" -> typeGif
Just ".jpg" -> typeJpeg
Just ".jpeg" -> typeJpeg
Just ".png" -> typePng
_ -> "" -- Not supported yet.
ToDo : we need a mechanism to avoid overwriting by wrong data by unknown users ,
-- probably by separating users.
postUploadResourceR :: Handler TypedContent
postUploadResourceR = do
email <- requireAuthId'
mtpid <- lookupPostParam "id"
let mpid = case mtpid of
Nothing -> Nothing
Just tpid -> fromPathPiece tpid
mftype <- lookupPostParam "type"
murl <- lookupPostParam "url"
mdat <- lookupPostParam "data"
$(logInfo) $ "postUploadResourceR: bytes: " `T.append` maybe "N/A" (T.pack . show . T.length) mdat
obj <- case (mpid,mftype,murl,mdat) of
(Just pid, Just ftype, Just url, Just dat) ->
saveUploadedImg pid ftype url dat
_ -> return $ object ["success" .= False, "message" .= ("Params missing."::String)]
return $ toTypedContent $ toJSON obj
saveUploadedImg :: PaperId -> Text -> Text -> Text -> Handler Value
saveUploadedImg pid ftype url dat = do
email <- requireAuthId'
let
file = imageCachePath url
dec = B64.decode (encodeUtf8 dat)
case dec of
Left err -> do
-- $(logInfo) $ T.pack err
return $ object ["success" .= False, "message" .= ("Base64 decode error." :: String)]
Right bs -> do
liftIO $ B.writeFile file bs
let img = Resource (T.pack $ mkFileName $ T.unpack url) url ftype file
rid <- runDB $ insert img
return $ object ["success" .= True, "resource_id" .= rid] -- "resource_id" is a DB id, not a resId field.
postAttachFileR :: PaperId -> Handler TypedContent
postAttachFileR pid = do
email <- requireAuthId'
mdat <- lookupPostParam "data"
json <- case mdat of
Just dat -> do
let bin = encodeUtf8 (T.drop 7 $ snd $ T.breakOn "base64," dat)
case B64.decode bin of -- Stub: Ad hoc: Drops "data:*****;base64,"
Right d -> doAttachFile email pid d
Left err -> return $ object ["success" .= False, "message" .= ("Base64 decode failed: " ++ err)]
Nothing -> return $ object ["success" .= False, "message" .= ("No data found." :: Text)]
return $ toTypedContent json
getAttachmentR :: Text -> Handler TypedContent
getAttachmentR resId = do
email <- requireAuthId'
sendFile "application/pdf" (attachmentFolder ++ (T.unpack $ resId))
-- Stub: Assuming PDF.
doAttachFile :: Text -> PaperId -> ByteString -> Handler Value
doAttachFile email pid dat = do
mval <- getPaperMisc email pid
datid <- return (toPathPiece pid) -- Stub
saveAttachment pid datid dat
let key = "attachedFile"
let newobj = case mval of
(Just (Ae.Object obj)) -> HashMap.insert key (Ae.String datid) obj
_ -> HashMap.singleton key (Ae.String datid) :: HashMap.HashMap Text Value
success <- updatePaperMisc email pid (Ae.Object newobj)
return $ case success of
True -> object ["success" .= True]
False -> object ["success" .= False, "message" .= ("Database error"::Text)]
saveAttachment :: PaperId -> Text -> ByteString -> Handler Bool
saveAttachment pid datid dat = do
liftIO $ B.writeFile (attachmentFolder ++ (T.unpack $ toPathPiece pid)) dat -- stub
return True
| null | https://raw.githubusercontent.com/hirokai/PaperServer/b577955af08660253d0cd11282cf141d1c174bc0/Handler/Resource.hs | haskell | Handler.Resource
Returns the resource list for the specified paper.
Client will download the image files (if not yet) and send them to server.
liftIO $ putStrLn hash
FIXME: Currently this does not have any effect.
_ -> typeGif
Not supported yet.
probably by separating users.
$(logInfo) $ T.pack err
"resource_id" is a DB id, not a resId field.
Stub: Ad hoc: Drops "data:*****;base64,"
Stub: Assuming PDF.
Stub
stub | # LANGUAGE TemplateHaskell #
module Handler.Resource (
getResourceR
, getResourcesForPaperR
, postUploadResourceR
, postAttachFileR
, getAttachmentR
)
where
import Import
import qualified Data.Text as T
import Data.List hiding (insert)
import System.Directory (doesFileExist)
import qualified Data.ByteString as B
import qualified Data.ByteString.Base64 as B64
import Data.Text.Encoding
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Aeson as Ae
import Handler.Utils (requireAuthId')
import Model.PaperMongo (getPaperDB,getPaperMisc,updatePaperMisc)
getResourcesForPaperR :: PaperId -> Handler TypedContent
getResourcesForPaperR pid = do
email <- requireAuthId'
mp <- getPaperDB email pid
case mp of
Just paper -> do
let title = citationTitle $ paperCitation paper
let urls = (map figureImg . paperFigures) paper ++
((map resourceUrl . paperResources) paper)
ids <- mapM (liftIO . resourceId) urls
let resources = zipWith (\mi u -> object (["exists" .= isJust mi, "url" .= u] ++ maybe [] (\i -> ["id" .= i]) mi)) ids urls
return $ toTypedContent $ object ["success" .= True, "resources" .= resources]
Nothing -> do
return $ toTypedContent $ object ["success" .= False, "message" .= ("ID not found."::Text)]
resourceId :: Url -> IO (Maybe Text)
resourceId url = do
let rid = mkFileName (T.unpack url)
ex <- doesFileExist (resourceRootFolder ++ rid)
return $ if ex then Just (T.pack rid) else Nothing
getResourceR :: String -> Handler ()
getResourceR hash = do
email <- requireAuthId'
sendFile ctype (resourceRootFolder++hash)
where
ctype = case find (`isSuffixOf` hash) [".gif",".jpg",".jpeg",".png"] of
Just ".gif" -> typeGif
Just ".jpg" -> typeJpeg
Just ".jpeg" -> typeJpeg
Just ".png" -> typePng
ToDo : we need a mechanism to avoid overwriting by wrong data by unknown users ,
postUploadResourceR :: Handler TypedContent
postUploadResourceR = do
email <- requireAuthId'
mtpid <- lookupPostParam "id"
let mpid = case mtpid of
Nothing -> Nothing
Just tpid -> fromPathPiece tpid
mftype <- lookupPostParam "type"
murl <- lookupPostParam "url"
mdat <- lookupPostParam "data"
$(logInfo) $ "postUploadResourceR: bytes: " `T.append` maybe "N/A" (T.pack . show . T.length) mdat
obj <- case (mpid,mftype,murl,mdat) of
(Just pid, Just ftype, Just url, Just dat) ->
saveUploadedImg pid ftype url dat
_ -> return $ object ["success" .= False, "message" .= ("Params missing."::String)]
return $ toTypedContent $ toJSON obj
saveUploadedImg :: PaperId -> Text -> Text -> Text -> Handler Value
saveUploadedImg pid ftype url dat = do
email <- requireAuthId'
let
file = imageCachePath url
dec = B64.decode (encodeUtf8 dat)
case dec of
Left err -> do
return $ object ["success" .= False, "message" .= ("Base64 decode error." :: String)]
Right bs -> do
liftIO $ B.writeFile file bs
let img = Resource (T.pack $ mkFileName $ T.unpack url) url ftype file
rid <- runDB $ insert img
postAttachFileR :: PaperId -> Handler TypedContent
postAttachFileR pid = do
email <- requireAuthId'
mdat <- lookupPostParam "data"
json <- case mdat of
Just dat -> do
let bin = encodeUtf8 (T.drop 7 $ snd $ T.breakOn "base64," dat)
Right d -> doAttachFile email pid d
Left err -> return $ object ["success" .= False, "message" .= ("Base64 decode failed: " ++ err)]
Nothing -> return $ object ["success" .= False, "message" .= ("No data found." :: Text)]
return $ toTypedContent json
getAttachmentR :: Text -> Handler TypedContent
getAttachmentR resId = do
email <- requireAuthId'
sendFile "application/pdf" (attachmentFolder ++ (T.unpack $ resId))
doAttachFile :: Text -> PaperId -> ByteString -> Handler Value
doAttachFile email pid dat = do
mval <- getPaperMisc email pid
saveAttachment pid datid dat
let key = "attachedFile"
let newobj = case mval of
(Just (Ae.Object obj)) -> HashMap.insert key (Ae.String datid) obj
_ -> HashMap.singleton key (Ae.String datid) :: HashMap.HashMap Text Value
success <- updatePaperMisc email pid (Ae.Object newobj)
return $ case success of
True -> object ["success" .= True]
False -> object ["success" .= False, "message" .= ("Database error"::Text)]
saveAttachment :: PaperId -> Text -> ByteString -> Handler Bool
saveAttachment pid datid dat = do
return True
|
9fa6f31b05867f61f886a5f5bed060c63924bdede9d0036334985d9675d089dd | j3pic/lisp-binary | integer.lisp | (defpackage :lisp-binary/integer
(:use :common-lisp :lisp-binary-utils)
(:export :get-lsb-byte :encode-lsb :decode-lsb :encode-msb :decode-msb
:signed->unsigned :unsigned->signed :unsigned->signed/bits
:signed->unsigned/bits
:read-integer :write-integer :read-bytes :write-bytes :pop-bits
:split-bit-field :join-field-bits :pop-bits/le
:push-bits :push-bits/le :bit-stream))
(in-package :lisp-binary/integer)
( declaim ( optimize ( debug 0 ) ( speed 3 ) ) )
(defun get-lsb-byte (number byte)
(declare (type integer number)
(type (signed-byte 32) byte))
(logand #xff (ash number (* byte -8))))
(defun encode-lsb (number bytes)
(declare (type integer number))
(let ((result (make-array (list bytes) :element-type '(unsigned-byte 8))))
(loop for x from 0 below bytes
do (setf (aref result x) (get-lsb-byte number x)))
result))
(declaim (inline encode-lsb))
(defun decode-lsb (bytes)
;; (declare (type (simple-array (unsigned-byte 8) (*)) bytes))
(let ((result 0))
(declare (type integer result))
(loop for b across bytes
for ix from 0 do
(setf result (logior result (ash b (* ix 8)))))
result))
(declaim (inline decode-lsb))
(defun decode-msb (bytes)
(decode-lsb (reverse bytes)))
(declaim (inline decode-msb))
(defun encode-msb (number bytes)
(declare (type integer number))
(reverse (encode-lsb number bytes)))
(declaim (inline encode-msb))
(defun signed->unsigned/bits (n bits)
(let ((negative-offset (expt 2 bits)))
(if (< n 0)
(the integer (+ n negative-offset))
n)))
(defun signed->unsigned (n bytes &optional (type :twos-complement))
(let ((n (ecase type
(:twos-complement n)
(:ones-complement (ones-complement->twos-complement n)))))
(signed->unsigned/bits n (* 8 bytes))))
(defun twos-complement->ones-complement (n bits)
"Given a number that has been decoded as two's complement,
correct it to what its value should be if the original bits
were a one's complement representation."
(cond ((>= n 0)
n)
((= n (1- (expt 2 bits)))
0)
(t
(1+ n))))
(defun ones-complement->twos-complement (n)
"Given a number that has been decoded as one's complement,
correct it to what its value should be if the original bits
were a two's complement representation. This function doesn't
need the number of bits because all ones in one's complement
represents 'negative zero', a value that can't be represented
in Common Lisp integers."
(if (>= n 0)
n
(1- n)))
(defun unsigned->signed/bits (n bits)
(let* ((negative-offset (expt 2 bits))
(max (- (/ negative-offset 2) 1)))
(if (> n max)
(- n negative-offset)
n)))
(defun unsigned->signed (n bytes &key (type :twos-complement))
(let ((twos-complement (unsigned->signed/bits n (* 8 bytes))))
(ecase type
(:twos-complement twos-complement)
(:ones-complement (twos-complement->ones-complement twos-complement (* 8 bytes))))))
(defgeneric write-bytes (buffer stream &optional bytes)
(:documentation "Write BYTES bytes of the BUFFER into the STREAM. If
BYTES is not provided, then the whole BUFFER is written.
For some types of stream, it is legal to use a fractional number for BYTES. In that case,
the whole bytes are written first, and then the leftover bits. The leftover bits must be given
their own byte at the end of the BUFFER. WRITE-BYTES assumes that all bytes are 8 bits long,
so to write 4 bits, you would give 1/2 as the value of BYTES.
NOTE: If you're using this with a bit-stream created with WRAP-IN-BIT-STREAM, the
:BYTE-ORDER given to that function should match the one given to this function."))
(defmethod write-bytes (buffer stream &optional bytes)
(setf bytes (or bytes (length buffer)))
(check-type bytes integer)
(write-sequence buffer stream :end bytes)
(length buffer))
(defgeneric read-bytes (n stream &key element-type)
(:documentation "Read N bytes of type ELEMENT-TYPE from STREAM and return them in a newly-allocated array.
Returns two values: The array containing the bytes, and the number of bytes read.
For some types of stream, it is legal to use a fractional number for N. In that case,
the whole bytes are read first, and then the leftover bits. The leftover bits are given
their own byte at the end of the returned array. The second return value (# of bytes read)
will also be fractional in this case. The fractional part can be used to calculate
how many bits the partial byte represents.
If you're using 8-bit bytes and want to read 11 bits (a whole byte plus three bits), give
11/8 as the value of N.
NOTE: If you're using this with a bit-stream created with WRAP-IN-BIT-STREAM, the :BYTE-ORDER given
to that function should match the one given to this function."))
(defmethod read-bytes (n stream &key (element-type '(unsigned-byte 8)))
(let* ((result (make-array n :element-type element-type))
(bytes-read (read-sequence result stream)))
(when (< bytes-read n)
(cerror "Ignore the error and proceed as if the remaining bytes were zeroes"
(make-condition 'end-of-file :stream stream)))
(values result bytes-read)))
(defun write-integer (number size stream &key (byte-order :little-endian)
(signed-representation :twos-complement)
signed)
(when signed
(setf number (signed->unsigned number size signed-representation)))
(cond ((integerp size)
(write-bytes (ecase byte-order
((:big-endian) (encode-msb number size))
((:little-endian) (encode-lsb number size))
(otherwise (error "Invalid byte order: ~a" byte-order)))
stream))
(t (let* ((whole-bytes (floor size))
TOO - BIG encodes the integer to be written with one more
;; byte for the fractional part.
(ecase byte-order
(:big-endian #'encode-msb)
(:little-endian #'encode-lsb))
number (1+ whole-bytes))))
(write-bytes too-big stream size)))))
(defmacro tlabels (labels &body body)
`(labels ,(loop for (name args . bod) in labels
for gs = (gensym)
collect `(,name ,args
(let ((,gs (progn ,@bod)))
(format t "~s returned ~s~%"
(list ',name ,@args)
,gs)
,gs)))
,@body))
(defmacro tif (expr if-t if-nil)
(let ((expr* (gensym))
(res (gensym)))
`(let ((,expr* ,expr))
(if ,expr*
(let ((,res ,if-t))
(format t "IF condition: ~s~%Test result: TRUE~%Value: ~S~%"
,expr* ,res)
,res)
(let ((,res ,if-nil))
(format t "IF condition: ~s~%Test result: FALSE~%Value: ~S~%"
,expr* ,res)
,res)))))
(defun ash* (&rest integers)
(apply #'ash integers))
(defun logior* (&rest args)
(apply #'logior args))
(defun read-integer (length stream &key (byte-order :little-endian)
signed
(signed-representation :twos-complement))
"Reads an integer of LENGTH bytes from the STREAM in the specified BYTE-ORDER.
If SIGNED is non-NIL, the number is interpreted as being in two's complement format.
If the STREAM is a BIT-STREAM, then the LENGTH doesn't have to be an integer."
(multiple-value-bind (bytes bytes-read) (read-bytes length stream)
(let ((bytes (if (integerp bytes-read)
bytes
(subseq bytes 0 (1- (length bytes)))))
(partial-byte (unless (integerp bytes-read)
(aref bytes (1- (length bytes)))))
(extra-bits (multiple-value-bind (whole frac) (floor bytes-read)
(declare (ignore whole))
(* frac 8))))
(labels ((add-extra-bits (int)
(if partial-byte
(ecase byte-order
(:big-endian
(logior
;; Note: SBCL 1.4.13.debian claims that both
calls to ASH are unreachable , and prints
;; the message "deleting unreachable code"
;; for them. Yet, I have confirmed through
;; extensive tracing that the code is
;; indeed executed, and removing it changes
;; the return value of READ-INTEGER in
;; the relevant case (where BIT-STREAMs are
;; involved)
(ash int extra-bits)
partial-byte))
(:little-endian
(logior
(ash partial-byte (* (floor length) 8))
int)))
int))
(decode-msb* (bytes)
(add-extra-bits
(decode-msb bytes)))
(decode-lsb* (bytes)
(add-extra-bits
(decode-lsb bytes))))
(declare (inline add-extra-bits decode-msb* decode-lsb*))
(values
(let ((result (case byte-order
((:big-endian) (decode-msb* bytes))
((:little-endian) (decode-lsb* bytes))
(otherwise (error "Invalid byte order: ~a" byte-order)))))
(if signed
(unsigned->signed result length :type signed-representation)
result))
bytes-read)))))
(defun split-bit-field (integer field-bits &optional field-signedness)
"Given the INTEGER, split it up as a bit field. The sizes and number of elements are given
by the FIELD-BITS parameter. If FIELD-SIGNEDNESS is specified, then it must be a list
that contains NIL for each element that will be interpreted as an unsigned integer,
and non-NIL for signed integers.
Example:
CL-USER> (split-bit-field #xffaaff '(8 8 8))
255
170
255
CL-USER>
Better performance could be acheived if INTEGER could be a FIXNUM, but it can't.
"
(declare (type integer integer)
(type list field-bits))
(setf field-signedness (reverse field-signedness))
(apply #'values
(reverse (loop for bits of-type (unsigned-byte 29) in (reverse field-bits)
for mask = (- (ash 1 bits)
1)
for signed = (pop field-signedness)
collect (let ((unsigned-result (logand mask integer)))
(if signed
(unsigned->signed/bits unsigned-result bits)
unsigned-result))
do (setf integer (ash integer (- bits)))))))
(defun join-field-bits (field-bits field-signedness field-values)
(let ((result 0))
(loop for (bits next-bits)
on field-bits
for value in field-values
for signed = (pop field-signedness)
do
(setf result
(logior result
(if signed
(signed->unsigned value (/ bits 8))
value)))
(when next-bits
(setf result (ash result next-bits))))
result))
(defmacro push-bits (n integer-size integer-place)
"Pushes N onto the front of INTEGER-PLACE,
the 'front' being defined as the MOST significant bits. The
INTEGER-SIZE specifies how many bits are already in the
INTEGER-PLACE."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion integer-place)
(let ((old-value (gensym))
(integer-size-temp (gensym)))
`(let* (,@(mapcar #'list dummies vals)
(,old-value ,getter)
(,integer-size-temp ,integer-size)
(,(car newval) (+ ,old-value (ash ,n ,integer-size-temp)))
,@(cdr newval))
,setter))))
(defmacro push-bits/le (n n-bits integer-place)
"Pushes N-BITS bits from N onto the front of INTEGER-PLACE,
the 'front' being defined as the LEAST significant bits. The
INTEGER-SIZE specifies how many bits are already in the
INTEGER-PLACE."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion integer-place)
(let ((old-value (gensym))
(n-ones (gensym))
(n-bits-temp (gensym)))
`(let* (,@(mapcar #'list dummies vals)
(,old-value ,getter)
(,n-bits-temp ,n-bits)
(,n-ones (1- (ash 1 ,n-bits-temp)))
(,(car newval) (+ (ash ,old-value ,n-bits-temp) (logand ,n ,n-ones)))
,@(cdr newval))
,setter))))
(defmacro pop-bits (n-bits integer-size integer-place)
"Pops the N most significant bits off the front of the INTEGER-PLACE and returns it.
INTEGER-SIZE is the number of unpopped bits in the integer."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion integer-place)
(let ((old-value (gensym "OLD-VALUE-"))
(n-ones (gensym "N-ONES-"))
(integer-size-temp (gensym "INTEGER-SIZE-"))
(n-bits-temp (gensym "N-BITS-"))
(selected-bits (gensym "SELECTED-BITS-")))
`(let* (,@(mapcar #'list dummies vals)
(,old-value ,getter)
(,n-bits-temp ,n-bits)
(,integer-size-temp ,integer-size)
(,n-ones (1- (ash 1 ,n-bits-temp)))
(,selected-bits (logand ,old-value (ash ,n-ones (- ,integer-size-temp ,n-bits-temp))))
(,(car newval) (- ,old-value ,selected-bits))
,@(cdr newval))
,setter
(ash ,selected-bits
(- (- ,integer-size-temp ,n-bits-temp)))))))
(defmacro pop-bits/le (n-bits integer-place)
"Pops the N LEAST significant bits off the front of the INTEGER-PLACE and returns it.
INTEGER-SIZE is the number of bits in the integer."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion integer-place)
(let ((old-value (gensym))
(n-ones (gensym))
(n-bits-temp (gensym))
(selected-bits (gensym)))
`(let* (,@(mapcar #'list dummies vals)
(,old-value ,getter)
(,n-bits-temp ,n-bits)
(,n-ones (1- (ash 1 ,n-bits-temp)))
(,selected-bits (logand ,old-value ,n-ones))
(,(car newval) (ash ,old-value (- ,n-bits-temp)))
,@(cdr newval))
,setter
,selected-bits))))
| null | https://raw.githubusercontent.com/j3pic/lisp-binary/d92325a9176bcc3f48bf60d3098336e96de9c9f9/integer.lisp | lisp | (declare (type (simple-array (unsigned-byte 8) (*)) bytes))
byte for the fractional part.
Note: SBCL 1.4.13.debian claims that both
the message "deleting unreachable code"
for them. Yet, I have confirmed through
extensive tracing that the code is
indeed executed, and removing it changes
the return value of READ-INTEGER in
the relevant case (where BIT-STREAMs are
involved) | (defpackage :lisp-binary/integer
(:use :common-lisp :lisp-binary-utils)
(:export :get-lsb-byte :encode-lsb :decode-lsb :encode-msb :decode-msb
:signed->unsigned :unsigned->signed :unsigned->signed/bits
:signed->unsigned/bits
:read-integer :write-integer :read-bytes :write-bytes :pop-bits
:split-bit-field :join-field-bits :pop-bits/le
:push-bits :push-bits/le :bit-stream))
(in-package :lisp-binary/integer)
( declaim ( optimize ( debug 0 ) ( speed 3 ) ) )
(defun get-lsb-byte (number byte)
(declare (type integer number)
(type (signed-byte 32) byte))
(logand #xff (ash number (* byte -8))))
(defun encode-lsb (number bytes)
(declare (type integer number))
(let ((result (make-array (list bytes) :element-type '(unsigned-byte 8))))
(loop for x from 0 below bytes
do (setf (aref result x) (get-lsb-byte number x)))
result))
(declaim (inline encode-lsb))
(defun decode-lsb (bytes)
(let ((result 0))
(declare (type integer result))
(loop for b across bytes
for ix from 0 do
(setf result (logior result (ash b (* ix 8)))))
result))
(declaim (inline decode-lsb))
(defun decode-msb (bytes)
(decode-lsb (reverse bytes)))
(declaim (inline decode-msb))
(defun encode-msb (number bytes)
(declare (type integer number))
(reverse (encode-lsb number bytes)))
(declaim (inline encode-msb))
(defun signed->unsigned/bits (n bits)
(let ((negative-offset (expt 2 bits)))
(if (< n 0)
(the integer (+ n negative-offset))
n)))
(defun signed->unsigned (n bytes &optional (type :twos-complement))
(let ((n (ecase type
(:twos-complement n)
(:ones-complement (ones-complement->twos-complement n)))))
(signed->unsigned/bits n (* 8 bytes))))
(defun twos-complement->ones-complement (n bits)
"Given a number that has been decoded as two's complement,
correct it to what its value should be if the original bits
were a one's complement representation."
(cond ((>= n 0)
n)
((= n (1- (expt 2 bits)))
0)
(t
(1+ n))))
(defun ones-complement->twos-complement (n)
"Given a number that has been decoded as one's complement,
correct it to what its value should be if the original bits
were a two's complement representation. This function doesn't
need the number of bits because all ones in one's complement
represents 'negative zero', a value that can't be represented
in Common Lisp integers."
(if (>= n 0)
n
(1- n)))
(defun unsigned->signed/bits (n bits)
(let* ((negative-offset (expt 2 bits))
(max (- (/ negative-offset 2) 1)))
(if (> n max)
(- n negative-offset)
n)))
(defun unsigned->signed (n bytes &key (type :twos-complement))
(let ((twos-complement (unsigned->signed/bits n (* 8 bytes))))
(ecase type
(:twos-complement twos-complement)
(:ones-complement (twos-complement->ones-complement twos-complement (* 8 bytes))))))
(defgeneric write-bytes (buffer stream &optional bytes)
(:documentation "Write BYTES bytes of the BUFFER into the STREAM. If
BYTES is not provided, then the whole BUFFER is written.
For some types of stream, it is legal to use a fractional number for BYTES. In that case,
the whole bytes are written first, and then the leftover bits. The leftover bits must be given
their own byte at the end of the BUFFER. WRITE-BYTES assumes that all bytes are 8 bits long,
so to write 4 bits, you would give 1/2 as the value of BYTES.
NOTE: If you're using this with a bit-stream created with WRAP-IN-BIT-STREAM, the
:BYTE-ORDER given to that function should match the one given to this function."))
(defmethod write-bytes (buffer stream &optional bytes)
(setf bytes (or bytes (length buffer)))
(check-type bytes integer)
(write-sequence buffer stream :end bytes)
(length buffer))
(defgeneric read-bytes (n stream &key element-type)
(:documentation "Read N bytes of type ELEMENT-TYPE from STREAM and return them in a newly-allocated array.
Returns two values: The array containing the bytes, and the number of bytes read.
For some types of stream, it is legal to use a fractional number for N. In that case,
the whole bytes are read first, and then the leftover bits. The leftover bits are given
their own byte at the end of the returned array. The second return value (# of bytes read)
will also be fractional in this case. The fractional part can be used to calculate
how many bits the partial byte represents.
If you're using 8-bit bytes and want to read 11 bits (a whole byte plus three bits), give
11/8 as the value of N.
NOTE: If you're using this with a bit-stream created with WRAP-IN-BIT-STREAM, the :BYTE-ORDER given
to that function should match the one given to this function."))
(defmethod read-bytes (n stream &key (element-type '(unsigned-byte 8)))
(let* ((result (make-array n :element-type element-type))
(bytes-read (read-sequence result stream)))
(when (< bytes-read n)
(cerror "Ignore the error and proceed as if the remaining bytes were zeroes"
(make-condition 'end-of-file :stream stream)))
(values result bytes-read)))
(defun write-integer (number size stream &key (byte-order :little-endian)
(signed-representation :twos-complement)
signed)
(when signed
(setf number (signed->unsigned number size signed-representation)))
(cond ((integerp size)
(write-bytes (ecase byte-order
((:big-endian) (encode-msb number size))
((:little-endian) (encode-lsb number size))
(otherwise (error "Invalid byte order: ~a" byte-order)))
stream))
(t (let* ((whole-bytes (floor size))
TOO - BIG encodes the integer to be written with one more
(ecase byte-order
(:big-endian #'encode-msb)
(:little-endian #'encode-lsb))
number (1+ whole-bytes))))
(write-bytes too-big stream size)))))
(defmacro tlabels (labels &body body)
`(labels ,(loop for (name args . bod) in labels
for gs = (gensym)
collect `(,name ,args
(let ((,gs (progn ,@bod)))
(format t "~s returned ~s~%"
(list ',name ,@args)
,gs)
,gs)))
,@body))
(defmacro tif (expr if-t if-nil)
(let ((expr* (gensym))
(res (gensym)))
`(let ((,expr* ,expr))
(if ,expr*
(let ((,res ,if-t))
(format t "IF condition: ~s~%Test result: TRUE~%Value: ~S~%"
,expr* ,res)
,res)
(let ((,res ,if-nil))
(format t "IF condition: ~s~%Test result: FALSE~%Value: ~S~%"
,expr* ,res)
,res)))))
(defun ash* (&rest integers)
(apply #'ash integers))
(defun logior* (&rest args)
(apply #'logior args))
(defun read-integer (length stream &key (byte-order :little-endian)
signed
(signed-representation :twos-complement))
"Reads an integer of LENGTH bytes from the STREAM in the specified BYTE-ORDER.
If SIGNED is non-NIL, the number is interpreted as being in two's complement format.
If the STREAM is a BIT-STREAM, then the LENGTH doesn't have to be an integer."
(multiple-value-bind (bytes bytes-read) (read-bytes length stream)
(let ((bytes (if (integerp bytes-read)
bytes
(subseq bytes 0 (1- (length bytes)))))
(partial-byte (unless (integerp bytes-read)
(aref bytes (1- (length bytes)))))
(extra-bits (multiple-value-bind (whole frac) (floor bytes-read)
(declare (ignore whole))
(* frac 8))))
(labels ((add-extra-bits (int)
(if partial-byte
(ecase byte-order
(:big-endian
(logior
calls to ASH are unreachable , and prints
(ash int extra-bits)
partial-byte))
(:little-endian
(logior
(ash partial-byte (* (floor length) 8))
int)))
int))
(decode-msb* (bytes)
(add-extra-bits
(decode-msb bytes)))
(decode-lsb* (bytes)
(add-extra-bits
(decode-lsb bytes))))
(declare (inline add-extra-bits decode-msb* decode-lsb*))
(values
(let ((result (case byte-order
((:big-endian) (decode-msb* bytes))
((:little-endian) (decode-lsb* bytes))
(otherwise (error "Invalid byte order: ~a" byte-order)))))
(if signed
(unsigned->signed result length :type signed-representation)
result))
bytes-read)))))
(defun split-bit-field (integer field-bits &optional field-signedness)
"Given the INTEGER, split it up as a bit field. The sizes and number of elements are given
by the FIELD-BITS parameter. If FIELD-SIGNEDNESS is specified, then it must be a list
that contains NIL for each element that will be interpreted as an unsigned integer,
and non-NIL for signed integers.
Example:
CL-USER> (split-bit-field #xffaaff '(8 8 8))
255
170
255
CL-USER>
Better performance could be acheived if INTEGER could be a FIXNUM, but it can't.
"
(declare (type integer integer)
(type list field-bits))
(setf field-signedness (reverse field-signedness))
(apply #'values
(reverse (loop for bits of-type (unsigned-byte 29) in (reverse field-bits)
for mask = (- (ash 1 bits)
1)
for signed = (pop field-signedness)
collect (let ((unsigned-result (logand mask integer)))
(if signed
(unsigned->signed/bits unsigned-result bits)
unsigned-result))
do (setf integer (ash integer (- bits)))))))
(defun join-field-bits (field-bits field-signedness field-values)
(let ((result 0))
(loop for (bits next-bits)
on field-bits
for value in field-values
for signed = (pop field-signedness)
do
(setf result
(logior result
(if signed
(signed->unsigned value (/ bits 8))
value)))
(when next-bits
(setf result (ash result next-bits))))
result))
(defmacro push-bits (n integer-size integer-place)
"Pushes N onto the front of INTEGER-PLACE,
the 'front' being defined as the MOST significant bits. The
INTEGER-SIZE specifies how many bits are already in the
INTEGER-PLACE."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion integer-place)
(let ((old-value (gensym))
(integer-size-temp (gensym)))
`(let* (,@(mapcar #'list dummies vals)
(,old-value ,getter)
(,integer-size-temp ,integer-size)
(,(car newval) (+ ,old-value (ash ,n ,integer-size-temp)))
,@(cdr newval))
,setter))))
(defmacro push-bits/le (n n-bits integer-place)
"Pushes N-BITS bits from N onto the front of INTEGER-PLACE,
the 'front' being defined as the LEAST significant bits. The
INTEGER-SIZE specifies how many bits are already in the
INTEGER-PLACE."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion integer-place)
(let ((old-value (gensym))
(n-ones (gensym))
(n-bits-temp (gensym)))
`(let* (,@(mapcar #'list dummies vals)
(,old-value ,getter)
(,n-bits-temp ,n-bits)
(,n-ones (1- (ash 1 ,n-bits-temp)))
(,(car newval) (+ (ash ,old-value ,n-bits-temp) (logand ,n ,n-ones)))
,@(cdr newval))
,setter))))
(defmacro pop-bits (n-bits integer-size integer-place)
"Pops the N most significant bits off the front of the INTEGER-PLACE and returns it.
INTEGER-SIZE is the number of unpopped bits in the integer."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion integer-place)
(let ((old-value (gensym "OLD-VALUE-"))
(n-ones (gensym "N-ONES-"))
(integer-size-temp (gensym "INTEGER-SIZE-"))
(n-bits-temp (gensym "N-BITS-"))
(selected-bits (gensym "SELECTED-BITS-")))
`(let* (,@(mapcar #'list dummies vals)
(,old-value ,getter)
(,n-bits-temp ,n-bits)
(,integer-size-temp ,integer-size)
(,n-ones (1- (ash 1 ,n-bits-temp)))
(,selected-bits (logand ,old-value (ash ,n-ones (- ,integer-size-temp ,n-bits-temp))))
(,(car newval) (- ,old-value ,selected-bits))
,@(cdr newval))
,setter
(ash ,selected-bits
(- (- ,integer-size-temp ,n-bits-temp)))))))
(defmacro pop-bits/le (n-bits integer-place)
"Pops the N LEAST significant bits off the front of the INTEGER-PLACE and returns it.
INTEGER-SIZE is the number of bits in the integer."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion integer-place)
(let ((old-value (gensym))
(n-ones (gensym))
(n-bits-temp (gensym))
(selected-bits (gensym)))
`(let* (,@(mapcar #'list dummies vals)
(,old-value ,getter)
(,n-bits-temp ,n-bits)
(,n-ones (1- (ash 1 ,n-bits-temp)))
(,selected-bits (logand ,old-value ,n-ones))
(,(car newval) (ash ,old-value (- ,n-bits-temp)))
,@(cdr newval))
,setter
,selected-bits))))
|
c726b81812d81133275ccd90bf21ab448e0fd6180660d2c6a2a66762c9a860b7 | portnov/wacom-intuos-pro-scripts | Kde.hs | # LANGUAGE TemplateHaskell , ScopedTypeVariables , DeriveDataTypeable , ExistentialQuantification #
| This module contains implementation of switching Wacom tablet settings profiles via
KDE4 or KDE5 kcm_wacomtablet systemsettings module ( via dbus ) .
module XMonad.Wacom.Kde
(
KDE (..),
getProfile,
setProfile,
withProfile
) where
import Control.Exception
import Control.Monad (when)
import Data.Generics
import Data.Monoid (mconcat)
import Data.Maybe (fromMaybe)
import DBus
import DBus.Client
import DBus.TH.EDSL
import XMonad
import qualified XMonad.StackSet as W
import qualified XMonad.Util.ExtensibleState as XS
import qualified XMonad.Wacom as API
type StringList = [String]
KDE 5 interface
interface "org.kde.Wacom" "/Tablet" "org.kde.Wacom" Nothing
[ "getTabletList" =:: Return ''StringList
, "getProfile" =:: ''String :-> Return ''String `as` "kde5getProfile"
, "setProfile" =:: ''String :-> ''String :-> Return ''Bool `as` "kde5setProfile"
]
KDE 4 interface
interface "org.kde.Wacom" "/Tablet" "org.kde.Wacom" Nothing
[ "getProfile" =:: Return ''String `as` "kde4getProfile"
, "setProfile" =:: ''String :-> Return ''Bool `as` "kde4setProfile"
]
data Wacom =
Wacom {
wClient :: Client,
wKdeVersion :: KdeVersion }
| Unknown
deriving (Typeable)
-- | Supported KDE versions
data KdeVersion = KDE4 | KDE5
deriving (Eq, Show, Typeable)
-- | Dummy type for API implementation
data KDE = KDE
instance ExtensionClass Wacom where
initialValue = Unknown
-- | Return existing dbus connection to KDE's daemon
-- or create new connection
ensureConnection :: X Wacom
ensureConnection = do
w <- XS.get
case w of
Unknown -> do
dbus <- io connectSession
v <- io $ (getTabletList dbus >> return KDE5)
`catch` \(e :: SomeException) -> return KDE4
let wacom = Wacom dbus v
XS.put wacom
return wacom
_ -> return w
-- | Return name of current profile.
-- Returns Nothing if there is no tablet attached
-- or no profile selected.
getProfile :: X (Maybe String)
getProfile = do
wacom <- ensureConnection
io $ getProfile' (wClient wacom) (wKdeVersion wacom)
where
getProfile' dbus KDE4 = do
p <- kde4getProfile dbus
case p of
Nothing -> return Nothing
Just [] -> return Nothing
profile -> return profile
getProfile' dbus KDE5 = do
tablets <- getTabletList dbus
case tablets of
Just (tablet:_) -> kde5getProfile dbus tablet
_ -> return Nothing
withProfile :: (String -> X ()) -> X ()
withProfile fn = do
mbProfile <- getProfile
whenJust mbProfile fn
-- | Set profile by name
setProfile :: String -> X ()
setProfile profile = do
wacom <- ensureConnection
io $ setProfile' (wClient wacom) (wKdeVersion wacom)
where
setProfile' dbus KDE4 = kde4setProfile dbus profile >> return ()
setProfile' dbus KDE5 = do
tablets <- getTabletList dbus
case tablets of
Just (tablet:_) -> kde5setProfile dbus tablet profile >> return ()
_ -> return ()
instance API.ProfileApi KDE where
getProfile _ = getProfile
setProfile _ name = setProfile name
| null | https://raw.githubusercontent.com/portnov/wacom-intuos-pro-scripts/78b85c09888d7031af73ede686f68cf97cea8a77/xmonad/xmonad-wacom/XMonad/Wacom/Kde.hs | haskell | | Supported KDE versions
| Dummy type for API implementation
| Return existing dbus connection to KDE's daemon
or create new connection
| Return name of current profile.
Returns Nothing if there is no tablet attached
or no profile selected.
| Set profile by name | # LANGUAGE TemplateHaskell , ScopedTypeVariables , DeriveDataTypeable , ExistentialQuantification #
| This module contains implementation of switching Wacom tablet settings profiles via
KDE4 or KDE5 kcm_wacomtablet systemsettings module ( via dbus ) .
module XMonad.Wacom.Kde
(
KDE (..),
getProfile,
setProfile,
withProfile
) where
import Control.Exception
import Control.Monad (when)
import Data.Generics
import Data.Monoid (mconcat)
import Data.Maybe (fromMaybe)
import DBus
import DBus.Client
import DBus.TH.EDSL
import XMonad
import qualified XMonad.StackSet as W
import qualified XMonad.Util.ExtensibleState as XS
import qualified XMonad.Wacom as API
type StringList = [String]
KDE 5 interface
interface "org.kde.Wacom" "/Tablet" "org.kde.Wacom" Nothing
[ "getTabletList" =:: Return ''StringList
, "getProfile" =:: ''String :-> Return ''String `as` "kde5getProfile"
, "setProfile" =:: ''String :-> ''String :-> Return ''Bool `as` "kde5setProfile"
]
KDE 4 interface
interface "org.kde.Wacom" "/Tablet" "org.kde.Wacom" Nothing
[ "getProfile" =:: Return ''String `as` "kde4getProfile"
, "setProfile" =:: ''String :-> Return ''Bool `as` "kde4setProfile"
]
data Wacom =
Wacom {
wClient :: Client,
wKdeVersion :: KdeVersion }
| Unknown
deriving (Typeable)
data KdeVersion = KDE4 | KDE5
deriving (Eq, Show, Typeable)
data KDE = KDE
instance ExtensionClass Wacom where
initialValue = Unknown
ensureConnection :: X Wacom
ensureConnection = do
w <- XS.get
case w of
Unknown -> do
dbus <- io connectSession
v <- io $ (getTabletList dbus >> return KDE5)
`catch` \(e :: SomeException) -> return KDE4
let wacom = Wacom dbus v
XS.put wacom
return wacom
_ -> return w
getProfile :: X (Maybe String)
getProfile = do
wacom <- ensureConnection
io $ getProfile' (wClient wacom) (wKdeVersion wacom)
where
getProfile' dbus KDE4 = do
p <- kde4getProfile dbus
case p of
Nothing -> return Nothing
Just [] -> return Nothing
profile -> return profile
getProfile' dbus KDE5 = do
tablets <- getTabletList dbus
case tablets of
Just (tablet:_) -> kde5getProfile dbus tablet
_ -> return Nothing
withProfile :: (String -> X ()) -> X ()
withProfile fn = do
mbProfile <- getProfile
whenJust mbProfile fn
setProfile :: String -> X ()
setProfile profile = do
wacom <- ensureConnection
io $ setProfile' (wClient wacom) (wKdeVersion wacom)
where
setProfile' dbus KDE4 = kde4setProfile dbus profile >> return ()
setProfile' dbus KDE5 = do
tablets <- getTabletList dbus
case tablets of
Just (tablet:_) -> kde5setProfile dbus tablet profile >> return ()
_ -> return ()
instance API.ProfileApi KDE where
getProfile _ = getProfile
setProfile _ name = setProfile name
|
ad695ece5a7f23e0ff8f283dd59a045af62d4d0394d4036b416fcb93e9f2a2d2 | dbushenko/sitecompiler | selmer.clj | (ns sitecompiler.renderers.selmer
(:require [selmer.parser :as selmer])
(:use sitecompiler.common))
(defrecord SelmerRenderer []
Supported
(supported? [this ext]
(= "selmer" ext))
Renderer
(render [this templ data]
(selmer/render templ data)))
(defn new-selmer-renderer []
(SelmerRenderer.))
| null | https://raw.githubusercontent.com/dbushenko/sitecompiler/ff916d4539a3c4694a1664f087a45cfdf847ecdc/src/sitecompiler/renderers/selmer.clj | clojure | (ns sitecompiler.renderers.selmer
(:require [selmer.parser :as selmer])
(:use sitecompiler.common))
(defrecord SelmerRenderer []
Supported
(supported? [this ext]
(= "selmer" ext))
Renderer
(render [this templ data]
(selmer/render templ data)))
(defn new-selmer-renderer []
(SelmerRenderer.))
|
|
d07444746b03d3e16dddd65a0e327d65feeaaec4f8957201fc669b0f58e820dc | LCBH/UKano | types.mli | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* , , and *
* *
* Copyright ( C ) INRIA , CNRS 2000 - 2020 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* Bruno Blanchet, Vincent Cheval, and Marc Sylvestre *
* *
* Copyright (C) INRIA, CNRS 2000-2020 *
* *
*************************************************************)
This program is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details ( in file LICENSE ) .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details (in file LICENSE).
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
(* Types module declares types of the abstract syntax
tree and of sets of messages.
There are recursive dependencies between these types,
that is why they are included in the same module
*)
open Stringmap
type occurrence = { occ : int; precise : bool }
(* Types *)
type typet = { tname : string }
(* Information for predicates. The integer argument corresponds
to the phase of the predicate *)
type info =
Attacker of int * typet
| Mess of int * typet
| InputP of int
| OutputP of int
| AttackerBin of int * typet
| MessBin of int * typet
| InputPBin of int
| OutputPBin of int
| AttackerGuess of typet
| Compromise of typet
| Equal of typet
| Table of int
| TableBin of int
| TestUnifP of typet
| PolymPred of string * int(*value of p_prop*) * typet list
| Combined of predicate list
| NegationPred of predicate
and predicate = { p_name: string;
p_type: typet list;
p_prop: int;
p_info: info list }
type when_include =
Always
| IfQueryNeedsIt
type eq_info =
EqNoInfo
| EqConvergent
| EqLinear
(* Identifiers that can be renamed *)
type renamable_id = {
orig_name : string; (* Original name in the input file.
Empty string if there is no original name.
When not empty, [orig_name] is used for display
if it is not already used for another identifier in
the same scope. *)
name : string; (* Prefix of the name, to be kept during renaming.
Often the [orig_name] after removing an _nnn suffix if any *)
Index to be modified when renaming .
[ name]_[idx ] provides a unique name for that identifier .
[ name ] and [ idx ] are not used much now :
They provide a unique identifier for debugging purposes ,
but they are not used for normal display .
[name]_[idx] provides a unique name for that identifier.
[name] and [idx] are not used much now:
They provide a unique identifier for debugging purposes,
but they are not used for normal display. *)
mutable display : string option (* The identifier as it is displayed.
Several identifiers may be displayed with the same
string in different scopes *)
}
Some function symbols have a fixed name ( constructors , destructors ,
free names in the typed front - end , ... )
and some can be renamed ( bound names , general variables , the symbol " any_val " , ... ) .
The type [ fixed_or_renamable ] allows to handle these two cases .
free names in the typed front-end, ...)
and some can be renamed (bound names, general variables, the symbol "any_val", ...).
The type [fixed_or_renamable] allows to handle these two cases. *)
type fixed_or_renamable =
Fixed of string
| Renamable of renamable_id
(* Variables *)
type binder = { vname : renamable_id;
unfailing : bool;
btype : typet;
mutable link : linktype }
(* Processes: patterns *)
and pattern =
PatVar of binder
| PatTuple of funsymb * pattern list
| PatEqual of term
(* What can be linked from variables *)
and linktype =
NoLink
| VLink of binder
| TLink of term
| TLink2 of term (* used only in reduction.ml *)
| FLink of format (* used only in syntax.ml *)
| PGLink of (unit -> term) (* used only in pisyntax.ml and pitsyntax.ml *)
(* Meaning of arguments of names *)
and arg_meaning =
MUnknown
| MSid of int (* The argument represents a session identifier *)
| MCompSid
| MAttSid
| MVar of binder * string option
(* The argument represents a variable.
The string option is [Some x] when the argument can be
designated by the string [x] in "new a[x = ....]" *)
and name_info = { mutable prev_inputs : term option;
mutable prev_inputs_meaning : arg_meaning list }
and funcats =
Red of rewrite_rules
| Eq of (term list * term) list
| Tuple
| Name of name_info
| SpecVar of binder
| Syntactic of funsymb
| General_var
| General_mayfail_var
| Choice
| BiProj of side
| Failure
and side = Left | Right
(* The following constraints represents the constraints that can occur in a clause,
namely disequalties between terms, inequalities between natural numbers and
predicates testing wheter a term is a natural number or not. *)
and constraints =
{
neq : (term * term) list list; (* A list of pair of term represents a disjunction of disequalities.
[neq l] represents a conjunction of disjunctions of disequalities.
TRUE can be represented by the list [].
FALSE can be represented by any list that contains [].*)
is_nat : term list; (* A list of terms that should be natural number. *)
is_not_nat : term list; (* A list of terms that should not be natural number. *)
geq : (term * int * term) list (* [geq l] represents a conjunction of inequalities where each triple
[(t,n,t')] in [l] means t + n >= t' *)
}
and rewrite_rule = term list * term * constraints
and rewrite_rules = rewrite_rule list
(* Function symbols *)
and funsymb = { f_name : fixed_or_renamable;
mutable f_type : typet list * typet; (* type of the arguments, type of the result *)
mutable f_cat : funcats;
f_initial_cat : funcats; (* Used to memorize f_cat before closing using the
equational theory. The initial f_cat is used in reduction.ml,
and also in check_several_types *)
f_private : bool; (* true when the function cannot be applied by the adversary *)
f_options : int
}
(* Terms *)
and term =
Var of binder
| FunApp of funsymb * term list
(* Format, to represent facts with jokers *)
and format =
FVar of binder
| FFunApp of funsymb * format list
| FAny of binder
type fact_format = predicate * format list
type fact =
Pred of predicate * term list
(* Type of a nounif declaration option *)
type nounif_single_op =
| Hypothesis
| Conclusion
| InductionVerif
| InductionSat of binder list
type nounif_op = nounif_single_op list
(* Environment elements; environments are needed for terms in queries
that cannot be expanded before process translation, see link PGTLink
below *)
type envElement =
EFun of funsymb
| EVar of binder
| EName of funsymb
| EPred of predicate
| EEvent of funsymb
| EType of typet
| ETable of funsymb
| ELetFun of (term list -> (term -> process) -> process) * (typet list) * typet
| EProcess of binder list * process
(* Each restriction "new" is annotated with
- optionally, the identifiers given between brackets after the "new",
which serve to determine the arguments in the internal representation
of the name
- the current environment at the restriction, which serves to determine
which variables to use in queries of the form "new a[x = ...]"
Events may also be annotated with identifiers between brackets.
They serve to determine the variables to include in the environment
used for proving injective correspondences.
*)
and new_args = binder list option * envElement StringMap.t
(* Processes *)
and process =
Nil
| Par of process * process
| Repl of process * occurrence
| Restr of funsymb * new_args * process * occurrence
| Test of term * process * process * occurrence
| Input of term * pattern * process * occurrence
| Output of term * term * process * occurrence
| Let of pattern * term * process * process * occurrence
| LetFilter of binder list * fact * process * process * occurrence
| Event of term * new_args * process * occurrence
| Insert of term * process * occurrence
| Get of pattern * term * process * process * occurrence
| Phase of int * process * occurrence
| Barrier of int * string option * process * occurrence
| AnnBarrier of int * string * funsymb * funsymb * (binder * term) list * process * occurrence
| NamedProcess of string * term list * process
(* Rule descriptions for History.get_rule_hist *)
type rulespec =
| RElem of predicate list * predicate
| RApplyFunc of funsymb * predicate
| RApplyProj of funsymb * int * predicate (* For projections corresponding to data constructors *)
(* History of construction of rules *)
type onestatus =
No | NonInj | Inj
type hypspec =
ReplTag of occurrence * int(*Number of elements of name_params after it*)
| InputTag of occurrence
| PreciseTag of occurrence
| BeginEvent of occurrence
| BeginFact
| LetFilterTag of occurrence (* Destructors succeed *)
| LetFilterFact
| OutputTag of occurrence
| TestTag of occurrence
| LetTag of occurrence
| TestUnifTag of occurrence
| TestUnifTag2 of occurrence
| InputPTag of occurrence
| OutputPTag of occurrence
| InsertTag of occurrence
| GetTag of occurrence
| GetTagElse of occurrence
type label =
ProcessRule of hypspec list * term list
| Apply of funsymb * predicate
| TestApply of funsymb * predicate
| TestEq of predicate
| LblEquiv
| LblClause
| LblEq
| Rl of predicate * predicate
| Rs of predicate * predicate
| Ri of predicate * predicate
| Ro of predicate * predicate
| Rfail of predicate
| TestComm of predicate * predicate
| WeakSecr
| Rn of predicate
| Init
| PhaseChange
| TblPhaseChange
| LblComp
| LblNone
| Elem of predicate list * predicate
| TestUnif
| TestDeterministic of funsymb
| TestTotal of funsymb
| Goal
| GoalCombined
| GoalInjective
| GenerationNested
(* Rules *)
type injectivity =
| DoubleIndex of int * int
| SingleIndex of fact (* Conclusion fact*) * fact (* Fact to match *) * int
| NoIndex of fact (* Conclusion facts*)
type history =
Rule of int * label * fact list * fact * constraints
| Removed of int (* Position of the fact removed *) * int (* Position of the duplicated fact *) * history
| Any of int (* Position of the fact removed in elim_any_x *) * history
| Empty of fact (* The history for the intial query goal *)
| HMaxHyp of int * history
| HEquation of int * fact * fact * history
| Resolution of history * int * history
| TestUnifTrue of int * history
| HLemma of
int (* Lemma number *) *
match of lemme 's premises with hypothesis of the clause
(fact list * constraints * (term * term) list) (* Conclusion of lemma *) *
history (* History of the rule on which the lemma is applied *)
| HCaseDistinction of
fact (* The conclusion of the clause *) *
fact list (* The hypotheses *) *
(term * term) list (* Substitution to apply *) *
constraints (* Added constraints *) *
history (* History of the rule on which the verification is applied *)
| HInjectivity of injectivity * history
| HNested of
int list (* Index matching the premise of the nested query *) *
int (* Nb of fact in the original clause's conclusion *) *
history
type reduction = fact list * fact * history * constraints
type order =
| Less
| Leq
type ordering_function = (int * order) list (* Always sorted on the integer *)
type ordered_reduction =
{
rule : reduction;
order_data : (ordering_function * bool) list option;
(* The boolean indicates whether an hypothesis can be
selected if they matched a nounif declaration with option [ignoreOnce] *)
}
Equational theory
type equation = term * term
(* Proof history *)
type fact_tree_desc =
FHAny
| FEmpty
| FRemovedWithMaxHyp
| FRemovedWithProof of fact_tree
| FRule of int * label * constraints * fact_tree list * constraints * fact_tree list
| FEquation of fact_tree
and fact_tree =
{ mutable desc: fact_tree_desc;
mutable thefact: fact
}
(* type of input to the Horn clause resolution solver *)
type t_solver_kind =
Solve_Standard
| Solve_Equivalence
| Solve_WeakSecret of (typet * history) list * int
Weaksecr.attrulenum , max_used_phase
| Solve_Noninterf of (funsymb * term list option) list
type t_lemma_application =
| LANone (* Does not apply the lemma *)
| LAOnlyWhenRemove (* Apply the lemma only when its application remove the clause afterwards *)
Apply the lemma when it does not create more than one clause and when it instantiate at least one variable
| LAFull (* Fully apply the lemma *)
type lemma =
{
l_index : int;
l_premise : fact list;
l_conclusion : (fact list * constraints * (term * term) list) list;
l_verif_app : t_lemma_application;
l_sat_app : t_lemma_application;
l_induction : int option
}
type t_horn_state =
{ h_clauses : reduction list;
h_equations : ((term * term) list * eq_info) list;
h_close_with_equations : bool;
h_not : fact list;
h_elimtrue : (int * fact) list;
h_equiv : (fact list * fact * int) list;
h_nounif : (fact_format * int * nounif_op) list;
h_clauses_to_initialize_selfun : reduction list;
h_solver_kind : t_solver_kind;
h_lemmas : lemma list;
h_pred_prove : predicate list; (* Predicates that we are trying to prove,
which must therefore not be removed by eliminating redundant clauses *)
h_event_in_queries : funsymb list (*
Events that occurs in the conclusion of the queries.
Thus they cannot be removed even when they cannot be used for applying
a lemma. *)
}
(* For precise options *)
type precise_info =
| Action of typet
| null | https://raw.githubusercontent.com/LCBH/UKano/13c046ddaca48b45d3652c3ea08e21599e051527/proverif2.01/src/types.mli | ocaml | Types module declares types of the abstract syntax
tree and of sets of messages.
There are recursive dependencies between these types,
that is why they are included in the same module
Types
Information for predicates. The integer argument corresponds
to the phase of the predicate
value of p_prop
Identifiers that can be renamed
Original name in the input file.
Empty string if there is no original name.
When not empty, [orig_name] is used for display
if it is not already used for another identifier in
the same scope.
Prefix of the name, to be kept during renaming.
Often the [orig_name] after removing an _nnn suffix if any
The identifier as it is displayed.
Several identifiers may be displayed with the same
string in different scopes
Variables
Processes: patterns
What can be linked from variables
used only in reduction.ml
used only in syntax.ml
used only in pisyntax.ml and pitsyntax.ml
Meaning of arguments of names
The argument represents a session identifier
The argument represents a variable.
The string option is [Some x] when the argument can be
designated by the string [x] in "new a[x = ....]"
The following constraints represents the constraints that can occur in a clause,
namely disequalties between terms, inequalities between natural numbers and
predicates testing wheter a term is a natural number or not.
A list of pair of term represents a disjunction of disequalities.
[neq l] represents a conjunction of disjunctions of disequalities.
TRUE can be represented by the list [].
FALSE can be represented by any list that contains [].
A list of terms that should be natural number.
A list of terms that should not be natural number.
[geq l] represents a conjunction of inequalities where each triple
[(t,n,t')] in [l] means t + n >= t'
Function symbols
type of the arguments, type of the result
Used to memorize f_cat before closing using the
equational theory. The initial f_cat is used in reduction.ml,
and also in check_several_types
true when the function cannot be applied by the adversary
Terms
Format, to represent facts with jokers
Type of a nounif declaration option
Environment elements; environments are needed for terms in queries
that cannot be expanded before process translation, see link PGTLink
below
Each restriction "new" is annotated with
- optionally, the identifiers given between brackets after the "new",
which serve to determine the arguments in the internal representation
of the name
- the current environment at the restriction, which serves to determine
which variables to use in queries of the form "new a[x = ...]"
Events may also be annotated with identifiers between brackets.
They serve to determine the variables to include in the environment
used for proving injective correspondences.
Processes
Rule descriptions for History.get_rule_hist
For projections corresponding to data constructors
History of construction of rules
Number of elements of name_params after it
Destructors succeed
Rules
Conclusion fact
Fact to match
Conclusion facts
Position of the fact removed
Position of the duplicated fact
Position of the fact removed in elim_any_x
The history for the intial query goal
Lemma number
Conclusion of lemma
History of the rule on which the lemma is applied
The conclusion of the clause
The hypotheses
Substitution to apply
Added constraints
History of the rule on which the verification is applied
Index matching the premise of the nested query
Nb of fact in the original clause's conclusion
Always sorted on the integer
The boolean indicates whether an hypothesis can be
selected if they matched a nounif declaration with option [ignoreOnce]
Proof history
type of input to the Horn clause resolution solver
Does not apply the lemma
Apply the lemma only when its application remove the clause afterwards
Fully apply the lemma
Predicates that we are trying to prove,
which must therefore not be removed by eliminating redundant clauses
Events that occurs in the conclusion of the queries.
Thus they cannot be removed even when they cannot be used for applying
a lemma.
For precise options | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* , , and *
* *
* Copyright ( C ) INRIA , CNRS 2000 - 2020 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* Bruno Blanchet, Vincent Cheval, and Marc Sylvestre *
* *
* Copyright (C) INRIA, CNRS 2000-2020 *
* *
*************************************************************)
This program is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details ( in file LICENSE ) .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details (in file LICENSE).
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Stringmap
type occurrence = { occ : int; precise : bool }
type typet = { tname : string }
type info =
Attacker of int * typet
| Mess of int * typet
| InputP of int
| OutputP of int
| AttackerBin of int * typet
| MessBin of int * typet
| InputPBin of int
| OutputPBin of int
| AttackerGuess of typet
| Compromise of typet
| Equal of typet
| Table of int
| TableBin of int
| TestUnifP of typet
| Combined of predicate list
| NegationPred of predicate
and predicate = { p_name: string;
p_type: typet list;
p_prop: int;
p_info: info list }
type when_include =
Always
| IfQueryNeedsIt
type eq_info =
EqNoInfo
| EqConvergent
| EqLinear
type renamable_id = {
Index to be modified when renaming .
[ name]_[idx ] provides a unique name for that identifier .
[ name ] and [ idx ] are not used much now :
They provide a unique identifier for debugging purposes ,
but they are not used for normal display .
[name]_[idx] provides a unique name for that identifier.
[name] and [idx] are not used much now:
They provide a unique identifier for debugging purposes,
but they are not used for normal display. *)
}
Some function symbols have a fixed name ( constructors , destructors ,
free names in the typed front - end , ... )
and some can be renamed ( bound names , general variables , the symbol " any_val " , ... ) .
The type [ fixed_or_renamable ] allows to handle these two cases .
free names in the typed front-end, ...)
and some can be renamed (bound names, general variables, the symbol "any_val", ...).
The type [fixed_or_renamable] allows to handle these two cases. *)
type fixed_or_renamable =
Fixed of string
| Renamable of renamable_id
type binder = { vname : renamable_id;
unfailing : bool;
btype : typet;
mutable link : linktype }
and pattern =
PatVar of binder
| PatTuple of funsymb * pattern list
| PatEqual of term
and linktype =
NoLink
| VLink of binder
| TLink of term
and arg_meaning =
MUnknown
| MCompSid
| MAttSid
| MVar of binder * string option
and name_info = { mutable prev_inputs : term option;
mutable prev_inputs_meaning : arg_meaning list }
and funcats =
Red of rewrite_rules
| Eq of (term list * term) list
| Tuple
| Name of name_info
| SpecVar of binder
| Syntactic of funsymb
| General_var
| General_mayfail_var
| Choice
| BiProj of side
| Failure
and side = Left | Right
and constraints =
{
}
and rewrite_rule = term list * term * constraints
and rewrite_rules = rewrite_rule list
and funsymb = { f_name : fixed_or_renamable;
mutable f_cat : funcats;
f_options : int
}
and term =
Var of binder
| FunApp of funsymb * term list
and format =
FVar of binder
| FFunApp of funsymb * format list
| FAny of binder
type fact_format = predicate * format list
type fact =
Pred of predicate * term list
type nounif_single_op =
| Hypothesis
| Conclusion
| InductionVerif
| InductionSat of binder list
type nounif_op = nounif_single_op list
type envElement =
EFun of funsymb
| EVar of binder
| EName of funsymb
| EPred of predicate
| EEvent of funsymb
| EType of typet
| ETable of funsymb
| ELetFun of (term list -> (term -> process) -> process) * (typet list) * typet
| EProcess of binder list * process
and new_args = binder list option * envElement StringMap.t
and process =
Nil
| Par of process * process
| Repl of process * occurrence
| Restr of funsymb * new_args * process * occurrence
| Test of term * process * process * occurrence
| Input of term * pattern * process * occurrence
| Output of term * term * process * occurrence
| Let of pattern * term * process * process * occurrence
| LetFilter of binder list * fact * process * process * occurrence
| Event of term * new_args * process * occurrence
| Insert of term * process * occurrence
| Get of pattern * term * process * process * occurrence
| Phase of int * process * occurrence
| Barrier of int * string option * process * occurrence
| AnnBarrier of int * string * funsymb * funsymb * (binder * term) list * process * occurrence
| NamedProcess of string * term list * process
type rulespec =
| RElem of predicate list * predicate
| RApplyFunc of funsymb * predicate
type onestatus =
No | NonInj | Inj
type hypspec =
| InputTag of occurrence
| PreciseTag of occurrence
| BeginEvent of occurrence
| BeginFact
| LetFilterFact
| OutputTag of occurrence
| TestTag of occurrence
| LetTag of occurrence
| TestUnifTag of occurrence
| TestUnifTag2 of occurrence
| InputPTag of occurrence
| OutputPTag of occurrence
| InsertTag of occurrence
| GetTag of occurrence
| GetTagElse of occurrence
type label =
ProcessRule of hypspec list * term list
| Apply of funsymb * predicate
| TestApply of funsymb * predicate
| TestEq of predicate
| LblEquiv
| LblClause
| LblEq
| Rl of predicate * predicate
| Rs of predicate * predicate
| Ri of predicate * predicate
| Ro of predicate * predicate
| Rfail of predicate
| TestComm of predicate * predicate
| WeakSecr
| Rn of predicate
| Init
| PhaseChange
| TblPhaseChange
| LblComp
| LblNone
| Elem of predicate list * predicate
| TestUnif
| TestDeterministic of funsymb
| TestTotal of funsymb
| Goal
| GoalCombined
| GoalInjective
| GenerationNested
type injectivity =
| DoubleIndex of int * int
type history =
Rule of int * label * fact list * fact * constraints
| HMaxHyp of int * history
| HEquation of int * fact * fact * history
| Resolution of history * int * history
| TestUnifTrue of int * history
| HLemma of
match of lemme 's premises with hypothesis of the clause
| HCaseDistinction of
| HInjectivity of injectivity * history
| HNested of
history
type reduction = fact list * fact * history * constraints
type order =
| Less
| Leq
type ordered_reduction =
{
rule : reduction;
order_data : (ordering_function * bool) list option;
}
Equational theory
type equation = term * term
type fact_tree_desc =
FHAny
| FEmpty
| FRemovedWithMaxHyp
| FRemovedWithProof of fact_tree
| FRule of int * label * constraints * fact_tree list * constraints * fact_tree list
| FEquation of fact_tree
and fact_tree =
{ mutable desc: fact_tree_desc;
mutable thefact: fact
}
type t_solver_kind =
Solve_Standard
| Solve_Equivalence
| Solve_WeakSecret of (typet * history) list * int
Weaksecr.attrulenum , max_used_phase
| Solve_Noninterf of (funsymb * term list option) list
type t_lemma_application =
Apply the lemma when it does not create more than one clause and when it instantiate at least one variable
type lemma =
{
l_index : int;
l_premise : fact list;
l_conclusion : (fact list * constraints * (term * term) list) list;
l_verif_app : t_lemma_application;
l_sat_app : t_lemma_application;
l_induction : int option
}
type t_horn_state =
{ h_clauses : reduction list;
h_equations : ((term * term) list * eq_info) list;
h_close_with_equations : bool;
h_not : fact list;
h_elimtrue : (int * fact) list;
h_equiv : (fact list * fact * int) list;
h_nounif : (fact_format * int * nounif_op) list;
h_clauses_to_initialize_selfun : reduction list;
h_solver_kind : t_solver_kind;
h_lemmas : lemma list;
}
type precise_info =
| Action of typet
|
2e2cefe77639ca70203d9e2f238324f4b1bdea476223a2db294de3a985a31f7a | monadbobo/ocaml-core | stringable.ml | module type S = sig
type t
val of_string : string -> t
val to_string : t -> string
end
| null | https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/lib/stringable.ml | ocaml | module type S = sig
type t
val of_string : string -> t
val to_string : t -> string
end
|
|
af944cceeea0b9d82ceda0a9518b873c630cf8a011896ce2fe936edcab5af1e2 | rd--/hsc3 | abs.help.hs | -- abs
abs (syncSaw ar 100 440 * 0.1)
| null | https://raw.githubusercontent.com/rd--/hsc3/60cb422f0e2049f00b7e15076b2667b85ad8f638/Help/Ugen/abs.help.hs | haskell | abs | abs (syncSaw ar 100 440 * 0.1)
|
c7b19296f16c93d929774624c149a8b5434a46519f34a315ab921e010e396b2c | jvf/scalaris | db_mnesia.erl | 2013 - 2015 Zuse Institute Berlin ,
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.
@author
@doc DB back - end using .
Two keys K and L are considered equal if K = = L yields true .
%% @end
-module(db_mnesia).
-author('').
-vsn('$Id: db_ets.erl 6270 2014-03-28 14:25:52Z $').
-include("scalaris.hrl").
-behaviour(db_backend_beh).
-define(TRACE(_X, _Y), ok).
%% -define(TRACE(X, Y), io:format(X, Y)).
%% -define(TRACE(X, Y), ct:pal(X, Y)).
%% primitives
-export([start/0, new/1, new/2, open/1, close/1, put/2, get/2, delete/2]).
%% db info
-export([get_persisted_tables/0, get_name/1, get_load/1,
is_available/0, supports_feature/1]).
%% cleanup functions
-export([mnesia_tables_of/1, delete_mnesia_tables/1, close_and_delete/1]).
%% iteration
-export([foldl/3, foldl/4, foldl/5]).
-export([foldr/3, foldr/4, foldr/5]).
-export([foldl_unordered/3]).
-export([tab2list/1]).
-type db() :: atom().
-type key() :: db_backend_beh:key(). %% '$end_of_table' is not allowed as key() or else iterations won't work!
-type entry() :: db_backend_beh:entry().
-export_type([db/0]).
-export([traverse_table_and_show/1]).
-spec start() -> ok.
start() ->
FullDataDir = config:read(db_directory) ++ "/" ++ atom_to_list(node()),
application:set_env(mnesia, dir, FullDataDir),
% case config:read(_type) of
case config:read(start_type) of
recover ->
case mnesia:create_schema([node()]) of
ok ->
io:format("starting mnesia: no previous Schema to recover from.~n"),
ok = mnesia:delete_schema([node()]),
erlang:halt();
{error, {_, {already_exists, _}}} ->
io:format("starting mnesia: recovering.~n");
Msg ->
case util:is_unittest() of
true -> ct:pal("starting mnesia recover : ~w~n", [Msg]);
false -> io:format("starting mnesia recover : ~w~n", [Msg])
end,
erlang:halt()
end;
_ ->
case mnesia:create_schema([node()]) of
ok -> ok;
Msg ->
case util:is_unittest() of
true ->
ct:pal("starting mnesia: ~w~n", [Msg]),
ct:pal("starting mnesia: maybe you tried to start a new node "
"while we still found persisted data of a node with the "
"same name. If you want to get rid of the old persisted "
"data, delete them using ~p.~n",
["rm -rf data/" ++ atom_to_list(node())]);
false ->
io:format("starting mnesia: ~w~n", [Msg]),
io:format("starting mnesia: maybe you tried to start a new node "
"while we still found persisted data of a node with the "
"same name. If you want to get rid of the old persisted "
"data, delete them using ~p.~n",
["rm -rf data/" ++ atom_to_list(node())])
end,
erlang:halt()
end
end,
_ = application:start(mnesia),
ok.
%% @doc traverse table and print content
-spec traverse_table_and_show(Table_name::nonempty_string()) -> ok.
traverse_table_and_show(Table_name)->
Iterator = fun(Rec,_)->
log:log(warn, "~p~n",[Rec]),
[]
end,
case mnesia:is_transaction() of
true -> mnesia:foldl(Iterator,[],Table_name);
false ->
Exec = fun({Fun,Tab}) -> mnesia:foldl(Fun, [],Tab) end,
mnesia:activity(transaction,Exec,[{Iterator,Table_name}],mnesia_frag)
end.
@doc Return all the tables owned by PidGroup
%% NOTE: only returns tables with names according to this regular expression:
%% <tt>^[^:]+:PidGroup(:.*)?$</tt>
-spec mnesia_tables_of(PidGroup::pid_groups:groupname()) -> [atom()].
mnesia_tables_of(PidGroup) ->
Tabs = mnesia:system_info(tables),
[ Tab || Tab <- Tabs,
element(2, db_util:parse_table_name(
erlang:atom_to_list(Tab))) =:= PidGroup ].
%% @doc Gets a list of persisted tables.
-spec get_persisted_tables() -> [nonempty_string()].
get_persisted_tables() ->
[atom_to_list(Table) || Table <- mnesia:system_info(tables), Table =/= schema].
%% @doc Close recursivly all mnesia tables in List
-spec delete_mnesia_tables(list()) -> ok.
delete_mnesia_tables(Tabs) ->
_ = [close(Tab) || Tab <- Tabs],
ok.
%% @doc Creates new DB handle named DBName.
-spec new(DBName::nonempty_string()) -> db().
new(DBName) ->
?TRACE("new:~nDB_name:~p~n",[DBName]),
DbAtom = list_to_atom(DBName),
mnesia:create_table(DbAtom, [{disc_copies, [node()]}, {type, ordered_set}]),
DbAtom.
%% @doc Creates new DB handle named DBName with possibility to pass Options.
-spec new(DBName::nonempty_string(), Options::[term()] ) -> db().
new(DBName, Options) ->
?TRACE("new:~nDB_name:~p~nOption~p~n",[DBName, Options]),
DbAtom = list_to_atom(DBName),
mnesia:create_table(DbAtom, [{disc_copies, [node()]}, {type, ordered_set} | Options]),
DbAtom.
%% @doc Open a previously existing database assuming the database has been
restored by the start of the application .
-spec open(DBName::nonempty_string()) -> db().
open(DBName) ->
erlang:list_to_atom(DBName).
%% @doc Closes the DB named DBName
-spec close(DB::db()) -> true.
close(DB) ->
?TRACE("close:~nDB_name:~p~n",[DB]),
{atomic, ok} = mnesia:delete_table(DB),
true.
%% @doc Closes and deletes the DB named DBName
-spec close_and_delete(DBName::db()) -> true.
close_and_delete(DBName) ->
close(DBName).
%% @doc Saves arbitrary tuple Entry or list of tuples Entries
%% in DB DBName and returns the new DB.
The key is expected to be the first element of Entry .
-spec put(DBName::db(), Entry::entry() | [Entries::entry()]) -> db().
put(DBName, []) ->
DBName;
put(DBName, Entry) ->
?DBG_ASSERT(case is_list(Entry) of
true ->
lists:all(
fun(E) ->
element(1, E) =/= '$end_of_table'
end,
Entry);
false ->
element(1, Entry) =/= '$end_of_table'
end),
{atomic, _} = mnesia:transaction(fun() -> mnesia:write({DBName, element(1, Entry), Entry}) end),
DBName.
%% @doc Returns the entry that corresponds to Key or {} if no such tuple exists.
-spec get(DBName::db(), Key::key()) -> entry() | {}.
get(DBName, Key) ->
case mnesia:transaction(fun() -> mnesia:read(DBName, Key) end) of
{atomic, [Entry]} ->
element(3, Entry);
{atomic, []} ->
{}
end.
%% @doc Deletes the tuple saved under Key and returns the new DB.
%% If such a tuple does not exists nothing is changed.
-spec delete(DBName::db(), Key::key()) -> db().
delete(DBName, Key) ->
{atomic, _} = mnesia:transaction(fun()-> mnesia:delete({DBName, Key}) end),
DBName.
%% @doc Returns the name of the DB specified in new/1.
-spec get_name(DB::db()) -> nonempty_string().
get_name(DB) ->
erlang:atom_to_list(mnesia:table_info(DB, name)).
%% @doc Checks for modules required for this DB backend. Returns true if no
%% modules are missing, or else a list of missing modules
-spec is_available() -> boolean() | [atom()].
is_available() ->
case code:which(mnesia) of
non_existing -> [mnesia];
_ -> true
end.
%% @doc Returns true if the DB support a specific feature (e.g. recovery), false otherwise.
-spec supports_feature(Feature::atom()) -> boolean().
supports_feature(recover) -> true;
supports_feature(_) -> false.
%% @doc Returns the current load (i.e. number of stored tuples) of the DB.
-spec get_load(DB::db()) -> non_neg_integer().
get_load(DB) ->
mnesia:table_info(DB, size).
%% @doc Is equivalent to ets:foldl(Fun, Acc0, DB).
-spec foldl(DB::db(), Fun::fun((Key::key(), AccIn::A) -> AccOut::A), Acc0::A) -> Acc1::A.
foldl(DB, Fun, Acc) ->
?TRACE("foldl/3:~n",[]),
{atomic, First} = mnesia:transaction(fun()-> mnesia:first(DB) end),
{atomic, Last} = mnesia:transaction(fun()-> mnesia:last(DB) end),
foldl(DB, Fun, Acc, {'[', First, Last, ']'}, mnesia:table_info(DB, size)).
@doc foldl/4 iterates over DB and applies Fun(Entry , AccIn ) to every element
encountered in Interval . On the first call AccIn = = Acc0 . The iteration
%% only apply Fun to the elements inside the Interval.
-spec foldl(DB::db(), Fun::fun((Key::key(), AccIn::A) -> AccOut::A), Acc0::A,
Interval::db_backend_beh:interval()) -> Acc1::A.
foldl(DB, Fun, Acc, Interval) ->
?TRACE("foldl/4:~nstart:~n",[]),
foldl(DB, Fun, Acc, Interval, mnesia:table_info(DB, size)).
@doc foldl/5 iterates over DB and applies Fun(Entry , AccIn ) to every element
encountered in Interval . On the first call AccIn = = Acc0 . The iteration
stops as soon as MaxNum elements have been encountered .
-spec foldl(db(), fun((Key::key(), A) -> A), A,
db_backend_beh:interval(), non_neg_integer()) -> Acc1::A.
foldl(_DB, _Fun, Acc, _Interval, 0) -> Acc;
foldl(_DB, _Fun, Acc, {_, '$end_of_table', _End, _}, _MaxNum) -> Acc;
foldl(_DB, _Fun, Acc, {_, _Start, '$end_of_table', _}, _MaxNum) -> Acc;
foldl(_DB, _Fun, Acc, {_, Start, End, _}, _MaxNum) when Start > End -> Acc;
foldl(DB, Fun, Acc, {El}, _MaxNum) ->
case mnesia:transaction(fun() -> mnesia:read(DB, El) end) of
{atomic, []} ->
Acc;
{atomic, [_Entry]} ->
Fun(El, Acc)
end;
foldl(DB, Fun, Acc, all, MaxNum) ->
{atomic, First} = mnesia:transaction(fun()-> mnesia:first(DB) end),
{atomic, Last} = mnesia:transaction(fun()-> mnesia:last(DB) end),
foldl(DB, Fun, Acc, {'[', First, Last, ']'}, MaxNum);
foldl(DB, Fun, Acc, {'(', Start, End, RBr}, MaxNum) ->
{atomic, Next} = mnesia:transaction(fun()-> mnesia:next(DB, Start) end),
foldl(DB, Fun, Acc, {'[', Next, End, RBr}, MaxNum);
foldl(DB, Fun, Acc, {LBr, Start, End, ')'}, MaxNum) ->
{atomic, Previous} = mnesia:transaction(fun()-> mnesia:prev(DB, End) end),
foldl(DB, Fun, Acc, {LBr, Start, Previous, ']'}, MaxNum);
foldl(DB, Fun, Acc, {'[', Start, End, ']'}, MaxNum) ->
?TRACE("foldl:~nstart: ~p~nend: ~p~nmaxnum: ~p~ninterval: ~p~n",
[Start, End, MaxNum, {'[', Start, End, ']'}]),
case mnesia:transaction(fun()-> mnesia:read(DB, Start) end) of
{atomic, []} ->
{atomic, Next} = mnesia:transaction(fun()-> mnesia:next(DB, Start) end),
foldl(DB, Fun, Acc, {'[', Next, End, ']'},
MaxNum);
{atomic, [_Entry]} ->
foldl_iter(DB, Fun, Acc, {'[', Start, End, ']'},
MaxNum)
end.
%% @doc foldl_iter(/5) is a recursive function applying Fun only on elements
%% inside the Interval. It is called by every foldl operation.
-spec foldl_iter(DB::db(), Fun::fun((Key::key(), AccIn::A) -> AccOut::A), Acc0::A,
Intervall::db_backend_beh:interval(), MaxNum::non_neg_integer()) -> Acc1::A.
foldl_iter(_DB, _Fun, Acc, _Interval, 0) -> Acc;
foldl_iter(_DB, _Fun, Acc, {_, '$end_of_table', _End, _}, _MaxNum) -> Acc;
foldl_iter(_DB, _Fun, Acc, {_, _Start, '$end_of_table', _}, _MaxNum) -> Acc;
foldl_iter(_DB, _Fun, Acc, {_, Start, End, _}, _MaxNum) when Start > End -> Acc;
foldl_iter(DB, Fun, Acc, {'[', Start, End, ']'}, MaxNum) ->
?TRACE("foldl_iter:~nstart: ~p~nend: ~p~nmaxnum: ~p~ninterval: ~p~n",
[Start, End, MaxNum, {'[', Start, End, ']'}]),
{atomic, Next} = mnesia:transaction(fun()-> mnesia:next(DB, Start) end),
foldl_iter(DB, Fun, Fun(Start, Acc), {'[', Next, End, ']'}, MaxNum - 1).
%% @doc Is equivalent to foldr(Fun, Acc0, DB).
-spec foldr(db(), fun((Key::key(), AccIn::A) -> AccOut::A), Acc0::A) -> Acc1::A.
foldr(DB, Fun, Acc) ->
{atomic, First} = mnesia:transaction(fun()-> mnesia:first(DB) end),
{atomic, Last} = mnesia:transaction(fun()-> mnesia:last(DB) end),
foldr(DB, Fun, Acc, {'[', First, Last, ']'}, mnesia:table_info(DB, size)).
@doc Is equivalent to foldr(DB , Fun , Acc0 , Interval , ) ) .
-spec foldr(db(), fun((Key::key(), AccIn::A) -> AccOut::A), Acc0::A, db_backend_beh:interval()) -> Acc1::A.
foldr(DB, Fun, Acc, Interval) ->
foldr(DB, Fun, Acc, Interval, mnesia:table_info(DB, size)).
@doc Behaves like foldl/5 with the difference that it starts at the end of
Interval and iterates towards the start of Interval .
-spec foldr(db(), fun((Key::key(), AccIn::A) -> AccOut::A), Acc0::A, db_backend_beh:interval(), non_neg_integer()) -> Acc1::A.
foldr(_DB, _Fun, Acc, _Interval, 0) -> Acc;
foldr(_DB, _Fun, Acc, {_, _End, '$end_of_table', _}, _MaxNum) -> Acc;
foldr(_DB, _Fun, Acc, {_, '$end_of_table', _Start, _}, _MaxNum) -> Acc;
foldr(_DB, _Fun, Acc, {_, End, Start, _}, _MaxNum) when Start < End -> Acc;
foldr(DB, Fun, Acc, {El}, _MaxNum) ->
case mnesia:transaction(fun()-> mnesia:read(DB, El) end) of
{atomic, []} ->
Acc;
{atomic, [_Entry]} ->
Fun(El, Acc)
end;
foldr(DB, Fun, Acc, all, MaxNum) ->
{atomic, First} = mnesia:transaction(fun()-> mnesia:first(DB) end),
{atomic, Last} = mnesia:transaction(fun()-> mnesia:last(DB) end),
foldr(DB, Fun, Acc, {'[', First, Last, ']'}, MaxNum);
foldr(DB, Fun, Acc, {'(', End, Start, RBr}, MaxNum) ->
{atomic, Next} = mnesia:transaction(fun()-> mnesia:next(DB, End) end),
foldr(DB, Fun, Acc, {'[', Next, Start, RBr}, MaxNum);
foldr(DB, Fun, Acc, {LBr, End, Start, ')'}, MaxNum) ->
{atomic, Previous} = mnesia:transaction(fun()-> mnesia:prev(DB, Start) end),
foldr(DB, Fun, Acc, {LBr, End, Previous, ']'}, MaxNum);
foldr(DB, Fun, Acc, {'[', End, Start, ']'}, MaxNum) ->
case mnesia:transaction(fun()-> mnesia:read(DB, Start) end) of
{atomic, []} ->
{atomic, Previous} = mnesia:transaction(fun()-> mnesia:prev(DB, Start) end),
foldr(DB, Fun, Acc, {'[', End, Previous, ']'}, MaxNum);
{atomic, [_Entry]} ->
foldr_iter(DB, Fun, Acc, {'[', End, Start, ']'}, MaxNum)
end.
-spec foldr_iter(db(), fun((Key::key(), AccIn::A) -> AccOut::A), Acc0::A, db_backend_beh:interval(), non_neg_integer()) -> Acc1::A.
foldr_iter(_DB, _Fun, Acc, _Interval, 0) -> Acc;
foldr_iter(_DB, _Fun, Acc, {_, _End, '$end_of_table', _}, _MaxNum) -> Acc;
foldr_iter(_DB, _Fun, Acc, {_, '$end_of_table', _Start, _}, _MaxNum) -> Acc;
foldr_iter(_DB, _Fun, Acc, {_, End, Start, _}, _MaxNum) when Start < End -> Acc;
foldr_iter(DB, Fun, Acc, {'[', End, Start, ']'}, MaxNum) ->
?TRACE("foldr:~nstart: ~p~nend ~p~nmaxnum: ~p~nfound",
[Start, End, MaxNum]),
{atomic, Previous} = mnesia:transaction(fun()-> mnesia:prev(DB, Start) end),
foldr_iter(DB, Fun, Fun(Start, Acc), {'[', End, Previous, ']'}, MaxNum - 1).
@doc Works similar to foldl/3 but uses : foldl instead of our own implementation .
%% The order in which will be iterated over is unspecified, but using this fuction
%% might be faster than foldl/3 if it does not matter.
-spec foldl_unordered(DB::db(), Fun::fun((Entry::entry(), AccIn::A) -> AccOut::A), Acc0::A) -> Acc1::A.
foldl_unordered(DB, Fun, Acc) ->
% Entry = {db, key, value}
FoldlFun = fun(Entry, AccIn) -> Fun(element(3, Entry), AccIn) end,
{atomic, Result} = mnesia:transaction(fun() ->
mnesia:foldl(FoldlFun, Acc, DB)
end),
Result.
-spec tab2list(Table_name::db()) -> [Entries::entry()].
tab2list(Table_name) ->
Iterator = fun({_DBName, _Key, Entry}, Acc)->
[Entry | Acc]
end,
case mnesia:is_transaction() of
true -> mnesia:foldl(Iterator,[],Table_name);
false ->
Exec = fun({Fun,Tab}) -> mnesia:foldl(Fun, [],Tab) end,
mnesia:activity(transaction,Exec,[{Iterator,Table_name}],mnesia_frag)
end.
| null | https://raw.githubusercontent.com/jvf/scalaris/c069f44cf149ea6c69e24bdb08714bda242e7ee0/src/db_mnesia.erl | erlang | 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.
@end
-define(TRACE(X, Y), io:format(X, Y)).
-define(TRACE(X, Y), ct:pal(X, Y)).
primitives
db info
cleanup functions
iteration
'$end_of_table' is not allowed as key() or else iterations won't work!
case config:read(_type) of
@doc traverse table and print content
NOTE: only returns tables with names according to this regular expression:
<tt>^[^:]+:PidGroup(:.*)?$</tt>
@doc Gets a list of persisted tables.
@doc Close recursivly all mnesia tables in List
@doc Creates new DB handle named DBName.
@doc Creates new DB handle named DBName with possibility to pass Options.
@doc Open a previously existing database assuming the database has been
@doc Closes the DB named DBName
@doc Closes and deletes the DB named DBName
@doc Saves arbitrary tuple Entry or list of tuples Entries
in DB DBName and returns the new DB.
@doc Returns the entry that corresponds to Key or {} if no such tuple exists.
@doc Deletes the tuple saved under Key and returns the new DB.
If such a tuple does not exists nothing is changed.
@doc Returns the name of the DB specified in new/1.
@doc Checks for modules required for this DB backend. Returns true if no
modules are missing, or else a list of missing modules
@doc Returns true if the DB support a specific feature (e.g. recovery), false otherwise.
@doc Returns the current load (i.e. number of stored tuples) of the DB.
@doc Is equivalent to ets:foldl(Fun, Acc0, DB).
only apply Fun to the elements inside the Interval.
@doc foldl_iter(/5) is a recursive function applying Fun only on elements
inside the Interval. It is called by every foldl operation.
@doc Is equivalent to foldr(Fun, Acc0, DB).
The order in which will be iterated over is unspecified, but using this fuction
might be faster than foldl/3 if it does not matter.
Entry = {db, key, value} | 2013 - 2015 Zuse Institute Berlin ,
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@author
@doc DB back - end using .
Two keys K and L are considered equal if K = = L yields true .
-module(db_mnesia).
-author('').
-vsn('$Id: db_ets.erl 6270 2014-03-28 14:25:52Z $').
-include("scalaris.hrl").
-behaviour(db_backend_beh).
-define(TRACE(_X, _Y), ok).
-export([start/0, new/1, new/2, open/1, close/1, put/2, get/2, delete/2]).
-export([get_persisted_tables/0, get_name/1, get_load/1,
is_available/0, supports_feature/1]).
-export([mnesia_tables_of/1, delete_mnesia_tables/1, close_and_delete/1]).
-export([foldl/3, foldl/4, foldl/5]).
-export([foldr/3, foldr/4, foldr/5]).
-export([foldl_unordered/3]).
-export([tab2list/1]).
-type db() :: atom().
-type entry() :: db_backend_beh:entry().
-export_type([db/0]).
-export([traverse_table_and_show/1]).
-spec start() -> ok.
start() ->
FullDataDir = config:read(db_directory) ++ "/" ++ atom_to_list(node()),
application:set_env(mnesia, dir, FullDataDir),
case config:read(start_type) of
recover ->
case mnesia:create_schema([node()]) of
ok ->
io:format("starting mnesia: no previous Schema to recover from.~n"),
ok = mnesia:delete_schema([node()]),
erlang:halt();
{error, {_, {already_exists, _}}} ->
io:format("starting mnesia: recovering.~n");
Msg ->
case util:is_unittest() of
true -> ct:pal("starting mnesia recover : ~w~n", [Msg]);
false -> io:format("starting mnesia recover : ~w~n", [Msg])
end,
erlang:halt()
end;
_ ->
case mnesia:create_schema([node()]) of
ok -> ok;
Msg ->
case util:is_unittest() of
true ->
ct:pal("starting mnesia: ~w~n", [Msg]),
ct:pal("starting mnesia: maybe you tried to start a new node "
"while we still found persisted data of a node with the "
"same name. If you want to get rid of the old persisted "
"data, delete them using ~p.~n",
["rm -rf data/" ++ atom_to_list(node())]);
false ->
io:format("starting mnesia: ~w~n", [Msg]),
io:format("starting mnesia: maybe you tried to start a new node "
"while we still found persisted data of a node with the "
"same name. If you want to get rid of the old persisted "
"data, delete them using ~p.~n",
["rm -rf data/" ++ atom_to_list(node())])
end,
erlang:halt()
end
end,
_ = application:start(mnesia),
ok.
-spec traverse_table_and_show(Table_name::nonempty_string()) -> ok.
traverse_table_and_show(Table_name)->
Iterator = fun(Rec,_)->
log:log(warn, "~p~n",[Rec]),
[]
end,
case mnesia:is_transaction() of
true -> mnesia:foldl(Iterator,[],Table_name);
false ->
Exec = fun({Fun,Tab}) -> mnesia:foldl(Fun, [],Tab) end,
mnesia:activity(transaction,Exec,[{Iterator,Table_name}],mnesia_frag)
end.
@doc Return all the tables owned by PidGroup
-spec mnesia_tables_of(PidGroup::pid_groups:groupname()) -> [atom()].
mnesia_tables_of(PidGroup) ->
Tabs = mnesia:system_info(tables),
[ Tab || Tab <- Tabs,
element(2, db_util:parse_table_name(
erlang:atom_to_list(Tab))) =:= PidGroup ].
-spec get_persisted_tables() -> [nonempty_string()].
get_persisted_tables() ->
[atom_to_list(Table) || Table <- mnesia:system_info(tables), Table =/= schema].
-spec delete_mnesia_tables(list()) -> ok.
delete_mnesia_tables(Tabs) ->
_ = [close(Tab) || Tab <- Tabs],
ok.
-spec new(DBName::nonempty_string()) -> db().
new(DBName) ->
?TRACE("new:~nDB_name:~p~n",[DBName]),
DbAtom = list_to_atom(DBName),
mnesia:create_table(DbAtom, [{disc_copies, [node()]}, {type, ordered_set}]),
DbAtom.
-spec new(DBName::nonempty_string(), Options::[term()] ) -> db().
new(DBName, Options) ->
?TRACE("new:~nDB_name:~p~nOption~p~n",[DBName, Options]),
DbAtom = list_to_atom(DBName),
mnesia:create_table(DbAtom, [{disc_copies, [node()]}, {type, ordered_set} | Options]),
DbAtom.
restored by the start of the application .
-spec open(DBName::nonempty_string()) -> db().
open(DBName) ->
erlang:list_to_atom(DBName).
-spec close(DB::db()) -> true.
close(DB) ->
?TRACE("close:~nDB_name:~p~n",[DB]),
{atomic, ok} = mnesia:delete_table(DB),
true.
-spec close_and_delete(DBName::db()) -> true.
close_and_delete(DBName) ->
close(DBName).
The key is expected to be the first element of Entry .
-spec put(DBName::db(), Entry::entry() | [Entries::entry()]) -> db().
put(DBName, []) ->
DBName;
put(DBName, Entry) ->
?DBG_ASSERT(case is_list(Entry) of
true ->
lists:all(
fun(E) ->
element(1, E) =/= '$end_of_table'
end,
Entry);
false ->
element(1, Entry) =/= '$end_of_table'
end),
{atomic, _} = mnesia:transaction(fun() -> mnesia:write({DBName, element(1, Entry), Entry}) end),
DBName.
-spec get(DBName::db(), Key::key()) -> entry() | {}.
get(DBName, Key) ->
case mnesia:transaction(fun() -> mnesia:read(DBName, Key) end) of
{atomic, [Entry]} ->
element(3, Entry);
{atomic, []} ->
{}
end.
-spec delete(DBName::db(), Key::key()) -> db().
delete(DBName, Key) ->
{atomic, _} = mnesia:transaction(fun()-> mnesia:delete({DBName, Key}) end),
DBName.
-spec get_name(DB::db()) -> nonempty_string().
get_name(DB) ->
erlang:atom_to_list(mnesia:table_info(DB, name)).
-spec is_available() -> boolean() | [atom()].
is_available() ->
case code:which(mnesia) of
non_existing -> [mnesia];
_ -> true
end.
-spec supports_feature(Feature::atom()) -> boolean().
supports_feature(recover) -> true;
supports_feature(_) -> false.
-spec get_load(DB::db()) -> non_neg_integer().
get_load(DB) ->
mnesia:table_info(DB, size).
-spec foldl(DB::db(), Fun::fun((Key::key(), AccIn::A) -> AccOut::A), Acc0::A) -> Acc1::A.
foldl(DB, Fun, Acc) ->
?TRACE("foldl/3:~n",[]),
{atomic, First} = mnesia:transaction(fun()-> mnesia:first(DB) end),
{atomic, Last} = mnesia:transaction(fun()-> mnesia:last(DB) end),
foldl(DB, Fun, Acc, {'[', First, Last, ']'}, mnesia:table_info(DB, size)).
@doc foldl/4 iterates over DB and applies Fun(Entry , AccIn ) to every element
encountered in Interval . On the first call AccIn = = Acc0 . The iteration
-spec foldl(DB::db(), Fun::fun((Key::key(), AccIn::A) -> AccOut::A), Acc0::A,
Interval::db_backend_beh:interval()) -> Acc1::A.
foldl(DB, Fun, Acc, Interval) ->
?TRACE("foldl/4:~nstart:~n",[]),
foldl(DB, Fun, Acc, Interval, mnesia:table_info(DB, size)).
@doc foldl/5 iterates over DB and applies Fun(Entry , AccIn ) to every element
encountered in Interval . On the first call AccIn = = Acc0 . The iteration
stops as soon as MaxNum elements have been encountered .
-spec foldl(db(), fun((Key::key(), A) -> A), A,
db_backend_beh:interval(), non_neg_integer()) -> Acc1::A.
foldl(_DB, _Fun, Acc, _Interval, 0) -> Acc;
foldl(_DB, _Fun, Acc, {_, '$end_of_table', _End, _}, _MaxNum) -> Acc;
foldl(_DB, _Fun, Acc, {_, _Start, '$end_of_table', _}, _MaxNum) -> Acc;
foldl(_DB, _Fun, Acc, {_, Start, End, _}, _MaxNum) when Start > End -> Acc;
foldl(DB, Fun, Acc, {El}, _MaxNum) ->
case mnesia:transaction(fun() -> mnesia:read(DB, El) end) of
{atomic, []} ->
Acc;
{atomic, [_Entry]} ->
Fun(El, Acc)
end;
foldl(DB, Fun, Acc, all, MaxNum) ->
{atomic, First} = mnesia:transaction(fun()-> mnesia:first(DB) end),
{atomic, Last} = mnesia:transaction(fun()-> mnesia:last(DB) end),
foldl(DB, Fun, Acc, {'[', First, Last, ']'}, MaxNum);
foldl(DB, Fun, Acc, {'(', Start, End, RBr}, MaxNum) ->
{atomic, Next} = mnesia:transaction(fun()-> mnesia:next(DB, Start) end),
foldl(DB, Fun, Acc, {'[', Next, End, RBr}, MaxNum);
foldl(DB, Fun, Acc, {LBr, Start, End, ')'}, MaxNum) ->
{atomic, Previous} = mnesia:transaction(fun()-> mnesia:prev(DB, End) end),
foldl(DB, Fun, Acc, {LBr, Start, Previous, ']'}, MaxNum);
foldl(DB, Fun, Acc, {'[', Start, End, ']'}, MaxNum) ->
?TRACE("foldl:~nstart: ~p~nend: ~p~nmaxnum: ~p~ninterval: ~p~n",
[Start, End, MaxNum, {'[', Start, End, ']'}]),
case mnesia:transaction(fun()-> mnesia:read(DB, Start) end) of
{atomic, []} ->
{atomic, Next} = mnesia:transaction(fun()-> mnesia:next(DB, Start) end),
foldl(DB, Fun, Acc, {'[', Next, End, ']'},
MaxNum);
{atomic, [_Entry]} ->
foldl_iter(DB, Fun, Acc, {'[', Start, End, ']'},
MaxNum)
end.
-spec foldl_iter(DB::db(), Fun::fun((Key::key(), AccIn::A) -> AccOut::A), Acc0::A,
Intervall::db_backend_beh:interval(), MaxNum::non_neg_integer()) -> Acc1::A.
foldl_iter(_DB, _Fun, Acc, _Interval, 0) -> Acc;
foldl_iter(_DB, _Fun, Acc, {_, '$end_of_table', _End, _}, _MaxNum) -> Acc;
foldl_iter(_DB, _Fun, Acc, {_, _Start, '$end_of_table', _}, _MaxNum) -> Acc;
foldl_iter(_DB, _Fun, Acc, {_, Start, End, _}, _MaxNum) when Start > End -> Acc;
foldl_iter(DB, Fun, Acc, {'[', Start, End, ']'}, MaxNum) ->
?TRACE("foldl_iter:~nstart: ~p~nend: ~p~nmaxnum: ~p~ninterval: ~p~n",
[Start, End, MaxNum, {'[', Start, End, ']'}]),
{atomic, Next} = mnesia:transaction(fun()-> mnesia:next(DB, Start) end),
foldl_iter(DB, Fun, Fun(Start, Acc), {'[', Next, End, ']'}, MaxNum - 1).
-spec foldr(db(), fun((Key::key(), AccIn::A) -> AccOut::A), Acc0::A) -> Acc1::A.
foldr(DB, Fun, Acc) ->
{atomic, First} = mnesia:transaction(fun()-> mnesia:first(DB) end),
{atomic, Last} = mnesia:transaction(fun()-> mnesia:last(DB) end),
foldr(DB, Fun, Acc, {'[', First, Last, ']'}, mnesia:table_info(DB, size)).
@doc Is equivalent to foldr(DB , Fun , Acc0 , Interval , ) ) .
-spec foldr(db(), fun((Key::key(), AccIn::A) -> AccOut::A), Acc0::A, db_backend_beh:interval()) -> Acc1::A.
foldr(DB, Fun, Acc, Interval) ->
foldr(DB, Fun, Acc, Interval, mnesia:table_info(DB, size)).
@doc Behaves like foldl/5 with the difference that it starts at the end of
Interval and iterates towards the start of Interval .
-spec foldr(db(), fun((Key::key(), AccIn::A) -> AccOut::A), Acc0::A, db_backend_beh:interval(), non_neg_integer()) -> Acc1::A.
foldr(_DB, _Fun, Acc, _Interval, 0) -> Acc;
foldr(_DB, _Fun, Acc, {_, _End, '$end_of_table', _}, _MaxNum) -> Acc;
foldr(_DB, _Fun, Acc, {_, '$end_of_table', _Start, _}, _MaxNum) -> Acc;
foldr(_DB, _Fun, Acc, {_, End, Start, _}, _MaxNum) when Start < End -> Acc;
foldr(DB, Fun, Acc, {El}, _MaxNum) ->
case mnesia:transaction(fun()-> mnesia:read(DB, El) end) of
{atomic, []} ->
Acc;
{atomic, [_Entry]} ->
Fun(El, Acc)
end;
foldr(DB, Fun, Acc, all, MaxNum) ->
{atomic, First} = mnesia:transaction(fun()-> mnesia:first(DB) end),
{atomic, Last} = mnesia:transaction(fun()-> mnesia:last(DB) end),
foldr(DB, Fun, Acc, {'[', First, Last, ']'}, MaxNum);
foldr(DB, Fun, Acc, {'(', End, Start, RBr}, MaxNum) ->
{atomic, Next} = mnesia:transaction(fun()-> mnesia:next(DB, End) end),
foldr(DB, Fun, Acc, {'[', Next, Start, RBr}, MaxNum);
foldr(DB, Fun, Acc, {LBr, End, Start, ')'}, MaxNum) ->
{atomic, Previous} = mnesia:transaction(fun()-> mnesia:prev(DB, Start) end),
foldr(DB, Fun, Acc, {LBr, End, Previous, ']'}, MaxNum);
foldr(DB, Fun, Acc, {'[', End, Start, ']'}, MaxNum) ->
case mnesia:transaction(fun()-> mnesia:read(DB, Start) end) of
{atomic, []} ->
{atomic, Previous} = mnesia:transaction(fun()-> mnesia:prev(DB, Start) end),
foldr(DB, Fun, Acc, {'[', End, Previous, ']'}, MaxNum);
{atomic, [_Entry]} ->
foldr_iter(DB, Fun, Acc, {'[', End, Start, ']'}, MaxNum)
end.
-spec foldr_iter(db(), fun((Key::key(), AccIn::A) -> AccOut::A), Acc0::A, db_backend_beh:interval(), non_neg_integer()) -> Acc1::A.
foldr_iter(_DB, _Fun, Acc, _Interval, 0) -> Acc;
foldr_iter(_DB, _Fun, Acc, {_, _End, '$end_of_table', _}, _MaxNum) -> Acc;
foldr_iter(_DB, _Fun, Acc, {_, '$end_of_table', _Start, _}, _MaxNum) -> Acc;
foldr_iter(_DB, _Fun, Acc, {_, End, Start, _}, _MaxNum) when Start < End -> Acc;
foldr_iter(DB, Fun, Acc, {'[', End, Start, ']'}, MaxNum) ->
?TRACE("foldr:~nstart: ~p~nend ~p~nmaxnum: ~p~nfound",
[Start, End, MaxNum]),
{atomic, Previous} = mnesia:transaction(fun()-> mnesia:prev(DB, Start) end),
foldr_iter(DB, Fun, Fun(Start, Acc), {'[', End, Previous, ']'}, MaxNum - 1).
@doc Works similar to foldl/3 but uses : foldl instead of our own implementation .
-spec foldl_unordered(DB::db(), Fun::fun((Entry::entry(), AccIn::A) -> AccOut::A), Acc0::A) -> Acc1::A.
foldl_unordered(DB, Fun, Acc) ->
FoldlFun = fun(Entry, AccIn) -> Fun(element(3, Entry), AccIn) end,
{atomic, Result} = mnesia:transaction(fun() ->
mnesia:foldl(FoldlFun, Acc, DB)
end),
Result.
-spec tab2list(Table_name::db()) -> [Entries::entry()].
tab2list(Table_name) ->
Iterator = fun({_DBName, _Key, Entry}, Acc)->
[Entry | Acc]
end,
case mnesia:is_transaction() of
true -> mnesia:foldl(Iterator,[],Table_name);
false ->
Exec = fun({Fun,Tab}) -> mnesia:foldl(Fun, [],Tab) end,
mnesia:activity(transaction,Exec,[{Iterator,Table_name}],mnesia_frag)
end.
|
ec7f22c86f3dcfc6aa34b6a9fb1f38daf87dd6688758c01192f29716feb466e7 | making/clj-gae-ds | core.clj | (ns am.ik.clj-gae-ds.core
(:use [clojure.test]
[clojure.contrib.singleton])
(:import [com.google.appengine.api.datastore
DatastoreServiceFactory DatastoreService
Entity Key KeyFactory KeyRange Text
Query Query$FilterOperator Query$SortDirection
PreparedQuery FetchOptions FetchOptions$Builder
Cursor QueryResultList
Transaction]))
(def
^DatastoreService
^{:arglists '([])
:doc "get DatastoreService. This method returns singleton instance of the service."}
get-ds-service (global-singleton #(DatastoreServiceFactory/getDatastoreService)))
;; Key
(defn ^Key create-key
"create key."
([parent kind id-or-name]
(KeyFactory/createKey parent kind (if (integer? id-or-name) (long id-or-name) (str id-or-name))))
([kind id-or-name]
(KeyFactory/createKey kind (if (integer? id-or-name) (long id-or-name) (str id-or-name)))))
;; Entity
(defn ^Entity create-entity
"create entity."
([kind] (Entity. kind))
([kind keyname-or-parent] (Entity. kind keyname-or-parent))
([kind ^String keyname ^Key parent] (Entity. kind (str keyname) parent)))
(defn ^Key get-key
"returns the key of an Entity."
[^Entity entity]
(.getKey entity))
(defn ^Key get-parent
"returns the parent key of an Entity."
[^Entity entity]
(.getParent entity))
(defn ^Long get-id
"retuns the numeric identifier of a Key."
[^Key key]
(.getId key))
(defn ^String get-name
"retuns the name of a Key."
[^Key key]
(.getName key))
(defn ^String get-kind
"returns the kind of the Entity by a Key."
[^Key key]
(.getKind key))
(defn- encode-prop
"encodes a property if it is a String longer than 500 chars"
[obj]
(if (and (instance? String obj) (> (count obj) 500))
(Text. obj)
obj))
(defn- decode-prop
"decodes a property to a String if it is a Text"
[prop]
(if (instance? Text prop)
(.getValue prop)
prop))
(defn ^Entity map-entity
"create Entity from map.
(map-entity \"person\" :name \"Bob\" :age 25)
-> #<Entity <Entity [person(no-id-yet)]:
name = Bob
age = 25>>
To set key, use keyword, :keyname <java.lang.String>
, and to set parent, :parent <com.google.appengine.api.datastore.Key>.
(map-entity \"person\" :name \"John\" :age 30 :parent (create-key \"parent\" \"xxx\"))
#<Entity <Entity [parent(\"xxx\")/person(no-id-yet)]:
name = John
age = 30>>
So cannot include :keyname and :parent in key of the map.
"
[ename & inits]
(let [init-map (apply hash-map inits)
keyname (:keyname init-map)
parent (:parent init-map)
entity-arity (filter #(not (nil? %)) [keyname parent])
m (apply array-map (mapcat identity (dissoc init-map :keyname :parent)))
^Entity entity (apply create-entity ename entity-arity)]
(doseq [e m]
(.setProperty entity (name (first e)) (encode-prop (last e))))
entity))
(defn entity-map
"convert entity to map"
[^Entity entity]
(into {:keyname (.getName (.getKey entity)) :parent (.getParent entity)}
(reduce (fn [props [k v]] (assoc props k (decode-prop v)))
{} (.getProperties entity))))
(defn- ^String key->str
"convert keyword to string. if key-or-str is not clojure.lang.Keyword,
then use key-or-str directory."
[key-or-str]
(if (keyword? key-or-str) (name key-or-str) key-or-str))
(defn get-prop
"get property"
[^Entity entity ^String key]
(decode-prop (.getProperty entity (key->str key))))
(defn set-prop
"set property"
[^Entity entity key value]
(.setProperty entity (key->str key) (encode-prop value)))
;; Query
(defn ^Query query
"create query."
([kind-or-ancestor] (Query. kind-or-ancestor))
([kind ancestor] (Query. kind ancestor)))
(def ^Query
^{:arglists '([kind-or-ancestor] [kind ancestor])
:doc "aliase of (query)"}
q
query)
(defn ^Query add-sort
"add sort option to query.
ex. (add-sort (query \"Entity\") \"property\" :desc)
-> #<Query SELECT * FROM Entity ORDER BY property DESC>
(add-sort (query \"Entity\") \"property\" :asc)
-> #<Query SELECT * FROM Entity ORDER BY property>"
[q prop-name asc-or-desc]
(.addSort q (key->str prop-name) (cond (= asc-or-desc :desc) Query$SortDirection/DESCENDING
(= asc-or-desc :asc) Query$SortDirection/ASCENDING
:else asc-or-desc)))
(def ^Query
^{:arglists '([q prop-name asc-or-desc])
:doc "aliase of (add-sort)"}
srt
add-sort)
(defn ^Query add-filter
"add filter option to query.
operator can be Keyword (:eq, :neq, :lt, :gt, :lte, :gte, :in)
or function (= not= > >= < <=)
ex. (add-filter (query \"Entity\") \"property\" :gt 100)
-> #<Query SELECT * FROM Entity WHERE property > 100>
(add-filter (query \"Entity\") \"property\" not= 100)
-> #<Query SELECT * FROM Entity WHERE property != 100>"
[q prop-name operator value]
(.addFilter q (key->str prop-name) (condp = operator
= Query$FilterOperator/EQUAL
not= Query$FilterOperator/NOT_EQUAL
> Query$FilterOperator/GREATER_THAN
>= Query$FilterOperator/GREATER_THAN_OR_EQUAL
< Query$FilterOperator/LESS_THAN
<= Query$FilterOperator/LESS_THAN_OR_EQUAL
:eq Query$FilterOperator/EQUAL
:neq Query$FilterOperator/NOT_EQUAL
:gt Query$FilterOperator/GREATER_THAN
:gte Query$FilterOperator/GREATER_THAN_OR_EQUAL
:lt Query$FilterOperator/LESS_THAN
:lte Query$FilterOperator/LESS_THAN_OR_EQUAL
:in Query$FilterOperator/IN) value))
(def ^Query
^{:arglists '([q prop-name operator value])
:doc "aliase of (add-filter)"}
flt add-filter)
(defn ^PreparedQuery prepare
"parepare query."
[^Query q]
(.prepare (get-ds-service) q))
(defprotocol Queries
(query-seq [q] [q fetch-options] "return sequence made from the result of query.")
(query-seq-with-cursor [q] [q fetch-options] "return map which contains sequence made from the result of query by :result key and
the cursor of current point by :cursor.
ex. (query-seq-with-cursor (query \"entity\")) -> {:result (...), :cursor ..}
")
(count-entities [q] "return count of entities."))
(extend Query Queries
{:query-seq (fn ([q] (query-seq (prepare q)))
([q fetch-options] (query-seq (prepare q) fetch-options))),
:query-seq-with-cursor (fn [q fetch-options] (query-seq-with-cursor (prepare q) fetch-options)),
:count-entities (fn [q] (count-entities (prepare q)))})
(extend PreparedQuery Queries
{:query-seq (fn ([pq] (lazy-seq (.asIterable pq)))
([pq fetch-options] (lazy-seq (.asIterable pq fetch-options)))),
:query-seq-with-cursor (fn [pq fetch-options]
(let [^QueryResultList result-list (.asQueryResultList pq fetch-options)]
{:result (lazy-seq result-list) :cursor ^Cursor (.getCursor result-list)})),
:count-entities (fn [pq] (.countEntities pq (FetchOptions$Builder/withDefaults)))})
(defn ^FetchOptions fetch-options
"return FetchOption which describe the limit, offset,
and chunk size to be applied when executing a PreparedQuery.
use these key to set limit, offset, chunk size,
:limit -> the maximum number of results the query will return.
:offset -> the number of result to skip before returning any results. default offset value is 0.
:chunk-size -> the chunk size which determines the internal chunking strategy of the Iterator.
:prefetch-size -> the number of entities to prefetch.
:cursor -> the cursor to start the query from.
ex.
(fetch-options :limit 20 :offset 10 :chunk-size 10)
(fetch-options :limit 100 :offset 20)
(fetch-options :limit 100)
"
[& options]
(let [option-map (apply array-map options)
offset (Math/max 0 (or (:offset option-map) 0))
limit (:limit option-map)
chunk-size (:chunk-size option-map)
prefetch-size (:prefetch-size option-map)
cursor (:cursor option-map)
^FetchOptions fetch (FetchOptions$Builder/withOffset offset)
^FetchOptions limitted (if limit (.limit fetch limit) fetch)
^FetchOptions chunk-sized (if chunk-size (.chunkSize limitted chunk-size) limitted)
^FetchOptions prefetch-sized (if prefetch-size (.prefetchSize chunk-sized prefetch-size) chunk-sized)
^FetchOptions cursored (if cursor (.cursor prefetch-sized cursor) prefetch-sized)]
cursored))
Cursor
(defn ^String cursor-encode [^Cursor cursor]
(.toWebSafeString cursor))
(defn ^Cursor cursor-decode [str]
(Cursor/fromWebSafeString str))
;; Datestore
(def ^{:doc "The current datastore transaction."} ^:dynamic *transaction* nil)
(defn ds-put
"put entity to datastore"
([entity-or-entities]
(.put (get-ds-service) *transaction* entity-or-entities))
([^Transaction txn entity-or-entities]
(binding [*transaction* txn]
(ds-put entity-or-entities))))
(defn ds-get
"get entity from datastore.
If entity is not found, return nil."
([key-or-keys]
(try
(.get (get-ds-service) *transaction* key-or-keys)
(catch Throwable e nil)))
([^Transaction txn key-or-keys]
(binding [*transaction* txn]
(ds-get key-or-keys))))
(defn ds-delete
"delete entity from datastore"
([key-or-keys]
(.delete (get-ds-service) *transaction* (if (instance? Iterable key-or-keys) key-or-keys [key-or-keys])))
([^Transaction txn key-or-keys]
(binding [*transaction* txn]
(ds-delete key-or-keys))))
(defn ^KeyRange allocate-ids
([kind num] (.allocateIds (get-ds-service) kind num))
([parent-key kind num] (.allocateIds (get-ds-service) parent-key kind num)))
(defn allocate-id-seq
([kind num] (lazy-seq (allocate-ids kind num)))
([parent-key kind num] (lazy-seq (allocate-ids parent-key kind num))))
(defmacro with-transaction
"create transaction block. when use \"ds-put\", \"ds-get\", \"ds-delete\" in this block,
automatically transaction begins and is committed after all processes normally finished or is rollbacked if failed."
[& body]
(let [txn (gensym "txn")]
`(let [service# (get-ds-service)
~txn (.beginTransaction service#)]
(try
(let [ret# (binding [*transaction* ~txn] ~@body)]
(.commit ~txn)
ret#)
(finally
(if (.isActive ~txn)
(.rollback ~txn)))))))
| null | https://raw.githubusercontent.com/making/clj-gae-ds/4f50697d750118a00abce37ed9f0d246664e3e85/src/am/ik/clj_gae_ds/core.clj | clojure | Key
Entity
Query
Datestore | (ns am.ik.clj-gae-ds.core
(:use [clojure.test]
[clojure.contrib.singleton])
(:import [com.google.appengine.api.datastore
DatastoreServiceFactory DatastoreService
Entity Key KeyFactory KeyRange Text
Query Query$FilterOperator Query$SortDirection
PreparedQuery FetchOptions FetchOptions$Builder
Cursor QueryResultList
Transaction]))
(def
^DatastoreService
^{:arglists '([])
:doc "get DatastoreService. This method returns singleton instance of the service."}
get-ds-service (global-singleton #(DatastoreServiceFactory/getDatastoreService)))
(defn ^Key create-key
"create key."
([parent kind id-or-name]
(KeyFactory/createKey parent kind (if (integer? id-or-name) (long id-or-name) (str id-or-name))))
([kind id-or-name]
(KeyFactory/createKey kind (if (integer? id-or-name) (long id-or-name) (str id-or-name)))))
(defn ^Entity create-entity
"create entity."
([kind] (Entity. kind))
([kind keyname-or-parent] (Entity. kind keyname-or-parent))
([kind ^String keyname ^Key parent] (Entity. kind (str keyname) parent)))
(defn ^Key get-key
"returns the key of an Entity."
[^Entity entity]
(.getKey entity))
(defn ^Key get-parent
"returns the parent key of an Entity."
[^Entity entity]
(.getParent entity))
(defn ^Long get-id
"retuns the numeric identifier of a Key."
[^Key key]
(.getId key))
(defn ^String get-name
"retuns the name of a Key."
[^Key key]
(.getName key))
(defn ^String get-kind
"returns the kind of the Entity by a Key."
[^Key key]
(.getKind key))
(defn- encode-prop
"encodes a property if it is a String longer than 500 chars"
[obj]
(if (and (instance? String obj) (> (count obj) 500))
(Text. obj)
obj))
(defn- decode-prop
"decodes a property to a String if it is a Text"
[prop]
(if (instance? Text prop)
(.getValue prop)
prop))
(defn ^Entity map-entity
"create Entity from map.
(map-entity \"person\" :name \"Bob\" :age 25)
-> #<Entity <Entity [person(no-id-yet)]:
name = Bob
age = 25>>
To set key, use keyword, :keyname <java.lang.String>
, and to set parent, :parent <com.google.appengine.api.datastore.Key>.
(map-entity \"person\" :name \"John\" :age 30 :parent (create-key \"parent\" \"xxx\"))
#<Entity <Entity [parent(\"xxx\")/person(no-id-yet)]:
name = John
age = 30>>
So cannot include :keyname and :parent in key of the map.
"
[ename & inits]
(let [init-map (apply hash-map inits)
keyname (:keyname init-map)
parent (:parent init-map)
entity-arity (filter #(not (nil? %)) [keyname parent])
m (apply array-map (mapcat identity (dissoc init-map :keyname :parent)))
^Entity entity (apply create-entity ename entity-arity)]
(doseq [e m]
(.setProperty entity (name (first e)) (encode-prop (last e))))
entity))
(defn entity-map
"convert entity to map"
[^Entity entity]
(into {:keyname (.getName (.getKey entity)) :parent (.getParent entity)}
(reduce (fn [props [k v]] (assoc props k (decode-prop v)))
{} (.getProperties entity))))
(defn- ^String key->str
"convert keyword to string. if key-or-str is not clojure.lang.Keyword,
then use key-or-str directory."
[key-or-str]
(if (keyword? key-or-str) (name key-or-str) key-or-str))
(defn get-prop
"get property"
[^Entity entity ^String key]
(decode-prop (.getProperty entity (key->str key))))
(defn set-prop
"set property"
[^Entity entity key value]
(.setProperty entity (key->str key) (encode-prop value)))
(defn ^Query query
"create query."
([kind-or-ancestor] (Query. kind-or-ancestor))
([kind ancestor] (Query. kind ancestor)))
(def ^Query
^{:arglists '([kind-or-ancestor] [kind ancestor])
:doc "aliase of (query)"}
q
query)
(defn ^Query add-sort
"add sort option to query.
ex. (add-sort (query \"Entity\") \"property\" :desc)
-> #<Query SELECT * FROM Entity ORDER BY property DESC>
(add-sort (query \"Entity\") \"property\" :asc)
-> #<Query SELECT * FROM Entity ORDER BY property>"
[q prop-name asc-or-desc]
(.addSort q (key->str prop-name) (cond (= asc-or-desc :desc) Query$SortDirection/DESCENDING
(= asc-or-desc :asc) Query$SortDirection/ASCENDING
:else asc-or-desc)))
(def ^Query
^{:arglists '([q prop-name asc-or-desc])
:doc "aliase of (add-sort)"}
srt
add-sort)
(defn ^Query add-filter
"add filter option to query.
operator can be Keyword (:eq, :neq, :lt, :gt, :lte, :gte, :in)
or function (= not= > >= < <=)
ex. (add-filter (query \"Entity\") \"property\" :gt 100)
-> #<Query SELECT * FROM Entity WHERE property > 100>
(add-filter (query \"Entity\") \"property\" not= 100)
-> #<Query SELECT * FROM Entity WHERE property != 100>"
[q prop-name operator value]
(.addFilter q (key->str prop-name) (condp = operator
= Query$FilterOperator/EQUAL
not= Query$FilterOperator/NOT_EQUAL
> Query$FilterOperator/GREATER_THAN
>= Query$FilterOperator/GREATER_THAN_OR_EQUAL
< Query$FilterOperator/LESS_THAN
<= Query$FilterOperator/LESS_THAN_OR_EQUAL
:eq Query$FilterOperator/EQUAL
:neq Query$FilterOperator/NOT_EQUAL
:gt Query$FilterOperator/GREATER_THAN
:gte Query$FilterOperator/GREATER_THAN_OR_EQUAL
:lt Query$FilterOperator/LESS_THAN
:lte Query$FilterOperator/LESS_THAN_OR_EQUAL
:in Query$FilterOperator/IN) value))
(def ^Query
^{:arglists '([q prop-name operator value])
:doc "aliase of (add-filter)"}
flt add-filter)
(defn ^PreparedQuery prepare
"parepare query."
[^Query q]
(.prepare (get-ds-service) q))
(defprotocol Queries
(query-seq [q] [q fetch-options] "return sequence made from the result of query.")
(query-seq-with-cursor [q] [q fetch-options] "return map which contains sequence made from the result of query by :result key and
the cursor of current point by :cursor.
ex. (query-seq-with-cursor (query \"entity\")) -> {:result (...), :cursor ..}
")
(count-entities [q] "return count of entities."))
(extend Query Queries
{:query-seq (fn ([q] (query-seq (prepare q)))
([q fetch-options] (query-seq (prepare q) fetch-options))),
:query-seq-with-cursor (fn [q fetch-options] (query-seq-with-cursor (prepare q) fetch-options)),
:count-entities (fn [q] (count-entities (prepare q)))})
(extend PreparedQuery Queries
{:query-seq (fn ([pq] (lazy-seq (.asIterable pq)))
([pq fetch-options] (lazy-seq (.asIterable pq fetch-options)))),
:query-seq-with-cursor (fn [pq fetch-options]
(let [^QueryResultList result-list (.asQueryResultList pq fetch-options)]
{:result (lazy-seq result-list) :cursor ^Cursor (.getCursor result-list)})),
:count-entities (fn [pq] (.countEntities pq (FetchOptions$Builder/withDefaults)))})
(defn ^FetchOptions fetch-options
"return FetchOption which describe the limit, offset,
and chunk size to be applied when executing a PreparedQuery.
use these key to set limit, offset, chunk size,
:limit -> the maximum number of results the query will return.
:offset -> the number of result to skip before returning any results. default offset value is 0.
:chunk-size -> the chunk size which determines the internal chunking strategy of the Iterator.
:prefetch-size -> the number of entities to prefetch.
:cursor -> the cursor to start the query from.
ex.
(fetch-options :limit 20 :offset 10 :chunk-size 10)
(fetch-options :limit 100 :offset 20)
(fetch-options :limit 100)
"
[& options]
(let [option-map (apply array-map options)
offset (Math/max 0 (or (:offset option-map) 0))
limit (:limit option-map)
chunk-size (:chunk-size option-map)
prefetch-size (:prefetch-size option-map)
cursor (:cursor option-map)
^FetchOptions fetch (FetchOptions$Builder/withOffset offset)
^FetchOptions limitted (if limit (.limit fetch limit) fetch)
^FetchOptions chunk-sized (if chunk-size (.chunkSize limitted chunk-size) limitted)
^FetchOptions prefetch-sized (if prefetch-size (.prefetchSize chunk-sized prefetch-size) chunk-sized)
^FetchOptions cursored (if cursor (.cursor prefetch-sized cursor) prefetch-sized)]
cursored))
Cursor
(defn ^String cursor-encode [^Cursor cursor]
(.toWebSafeString cursor))
(defn ^Cursor cursor-decode [str]
(Cursor/fromWebSafeString str))
(def ^{:doc "The current datastore transaction."} ^:dynamic *transaction* nil)
(defn ds-put
"put entity to datastore"
([entity-or-entities]
(.put (get-ds-service) *transaction* entity-or-entities))
([^Transaction txn entity-or-entities]
(binding [*transaction* txn]
(ds-put entity-or-entities))))
(defn ds-get
"get entity from datastore.
If entity is not found, return nil."
([key-or-keys]
(try
(.get (get-ds-service) *transaction* key-or-keys)
(catch Throwable e nil)))
([^Transaction txn key-or-keys]
(binding [*transaction* txn]
(ds-get key-or-keys))))
(defn ds-delete
"delete entity from datastore"
([key-or-keys]
(.delete (get-ds-service) *transaction* (if (instance? Iterable key-or-keys) key-or-keys [key-or-keys])))
([^Transaction txn key-or-keys]
(binding [*transaction* txn]
(ds-delete key-or-keys))))
(defn ^KeyRange allocate-ids
([kind num] (.allocateIds (get-ds-service) kind num))
([parent-key kind num] (.allocateIds (get-ds-service) parent-key kind num)))
(defn allocate-id-seq
([kind num] (lazy-seq (allocate-ids kind num)))
([parent-key kind num] (lazy-seq (allocate-ids parent-key kind num))))
(defmacro with-transaction
"create transaction block. when use \"ds-put\", \"ds-get\", \"ds-delete\" in this block,
automatically transaction begins and is committed after all processes normally finished or is rollbacked if failed."
[& body]
(let [txn (gensym "txn")]
`(let [service# (get-ds-service)
~txn (.beginTransaction service#)]
(try
(let [ret# (binding [*transaction* ~txn] ~@body)]
(.commit ~txn)
ret#)
(finally
(if (.isActive ~txn)
(.rollback ~txn)))))))
|
75a00fc3d3ef931be6f1530ff933af769d7bc9ec2a29cb4bf6a07a26e6280a98 | obsidiansystems/beam-automigrate | Main.hs | {-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Exception (bracket)
import Control.Monad.IO.Class (liftIO)
import Criterion.Main
import qualified Data.Map.Strict as M
import Database.Beam.AutoMigrate
import Database.Beam.AutoMigrate.BenchUtil
import Database.Beam.AutoMigrate.Postgres (getSchema)
import Database.Beam.Postgres (runBeamPostgres)
import qualified Database.PostgreSQL.Simple as Pg
pgMigrate :: Pg.Connection -> (Schema -> Schema -> Diff) -> Schema -> IO SpineStrict
pgMigrate conn diffFun hsSchema =
Pg.withTransaction conn $
runBeamPostgres conn $ do
dbSchema <- liftIO (getSchema conn)
pure . SS $ diffFun hsSchema dbSchema
main :: IO ()
main = do
putStrLn "Generating schema with 10_000 tables ..."
(hsSchema, dbSchema) <- predictableSchemas 10000
putStrLn $ "Generated schema with " ++ show (M.size . schemaTables $ hsSchema) ++ " tables."
bracket (setupDatabase dbSchema) tearDownDatabase $ \pgConn ->
defaultMain
[ bgroup
"diff"
[ bench "reference/10_000 tables avg. case (similar schema)" $ nf (SS . diffReferenceImplementation hsSchema) dbSchema,
bench "efficient/10_000 tables avg. case (similar schema)" $ nf (SS . diff hsSchema) dbSchema,
bench "reference/10_000 tables worst case (no schema)" $ nf (SS . diffReferenceImplementation hsSchema) noSchema,
bench "efficient/10_000 tables worst case (no schema)" $ nf (SS . diff hsSchema) noSchema
],
bgroup
"getSchema"
[ bench "10_000 tables" $ nfIO (getSchema pgConn)
],
bgroup
"full_migration"
[ bench "reference/10_000 tables avg. case (similar schema)" $ nfIO (pgMigrate pgConn diffReferenceImplementation hsSchema),
bench "efficient/10_000 tables avg. case (similar schema)" $ nfIO (pgMigrate pgConn diff hsSchema),
bench "reference/10_000 tables worst case (no previous schema)" $ nfIO (pgMigrate pgConn diffReferenceImplementation hsSchema),
bench "efficient/10_000 tables worst case (no previous schema)" $ nfIO (pgMigrate pgConn diff hsSchema)
]
]
| null | https://raw.githubusercontent.com/obsidiansystems/beam-automigrate/93f86a29b81150ac356107b82225ac7f151d6e51/bench/Main.hs | haskell | # LANGUAGE OverloadedStrings # |
module Main where
import Control.Exception (bracket)
import Control.Monad.IO.Class (liftIO)
import Criterion.Main
import qualified Data.Map.Strict as M
import Database.Beam.AutoMigrate
import Database.Beam.AutoMigrate.BenchUtil
import Database.Beam.AutoMigrate.Postgres (getSchema)
import Database.Beam.Postgres (runBeamPostgres)
import qualified Database.PostgreSQL.Simple as Pg
pgMigrate :: Pg.Connection -> (Schema -> Schema -> Diff) -> Schema -> IO SpineStrict
pgMigrate conn diffFun hsSchema =
Pg.withTransaction conn $
runBeamPostgres conn $ do
dbSchema <- liftIO (getSchema conn)
pure . SS $ diffFun hsSchema dbSchema
main :: IO ()
main = do
putStrLn "Generating schema with 10_000 tables ..."
(hsSchema, dbSchema) <- predictableSchemas 10000
putStrLn $ "Generated schema with " ++ show (M.size . schemaTables $ hsSchema) ++ " tables."
bracket (setupDatabase dbSchema) tearDownDatabase $ \pgConn ->
defaultMain
[ bgroup
"diff"
[ bench "reference/10_000 tables avg. case (similar schema)" $ nf (SS . diffReferenceImplementation hsSchema) dbSchema,
bench "efficient/10_000 tables avg. case (similar schema)" $ nf (SS . diff hsSchema) dbSchema,
bench "reference/10_000 tables worst case (no schema)" $ nf (SS . diffReferenceImplementation hsSchema) noSchema,
bench "efficient/10_000 tables worst case (no schema)" $ nf (SS . diff hsSchema) noSchema
],
bgroup
"getSchema"
[ bench "10_000 tables" $ nfIO (getSchema pgConn)
],
bgroup
"full_migration"
[ bench "reference/10_000 tables avg. case (similar schema)" $ nfIO (pgMigrate pgConn diffReferenceImplementation hsSchema),
bench "efficient/10_000 tables avg. case (similar schema)" $ nfIO (pgMigrate pgConn diff hsSchema),
bench "reference/10_000 tables worst case (no previous schema)" $ nfIO (pgMigrate pgConn diffReferenceImplementation hsSchema),
bench "efficient/10_000 tables worst case (no previous schema)" $ nfIO (pgMigrate pgConn diff hsSchema)
]
]
|
0b7a3f9abc079d22938ed07966ffac11ce717ccd61bf32512cb07478a28c8111 | ghcjs/jsaddle-dom | TextEncoder.hs | # LANGUAGE PatternSynonyms #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.TextEncoder
(newTextEncoder, encode, encode_, getEncoding, TextEncoder(..),
gTypeTextEncoder)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/TextEncoder Mozilla TextEncoder documentation >
newTextEncoder :: (MonadDOM m) => m TextEncoder
newTextEncoder
= liftDOM (TextEncoder <$> new (jsg "TextEncoder") ())
| < -US/docs/Web/API/TextEncoder.encode Mozilla TextEncoder.encode documentation >
encode ::
(MonadDOM m, ToJSString input) =>
TextEncoder -> Maybe input -> m Uint8Array
encode self input
= liftDOM
((self ^. jsf "encode" [toJSVal input]) >>= fromJSValUnchecked)
| < -US/docs/Web/API/TextEncoder.encode Mozilla TextEncoder.encode documentation >
encode_ ::
(MonadDOM m, ToJSString input) =>
TextEncoder -> Maybe input -> m ()
encode_ self input
= liftDOM (void (self ^. jsf "encode" [toJSVal input]))
| < -US/docs/Web/API/TextEncoder.encoding Mozilla TextEncoder.encoding documentation >
getEncoding ::
(MonadDOM m, FromJSString result) => TextEncoder -> m result
getEncoding self
= liftDOM ((self ^. js "encoding") >>= fromJSValUnchecked)
| null | https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/TextEncoder.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | # LANGUAGE PatternSynonyms #
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.TextEncoder
(newTextEncoder, encode, encode_, getEncoding, TextEncoder(..),
gTypeTextEncoder)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/TextEncoder Mozilla TextEncoder documentation >
newTextEncoder :: (MonadDOM m) => m TextEncoder
newTextEncoder
= liftDOM (TextEncoder <$> new (jsg "TextEncoder") ())
| < -US/docs/Web/API/TextEncoder.encode Mozilla TextEncoder.encode documentation >
encode ::
(MonadDOM m, ToJSString input) =>
TextEncoder -> Maybe input -> m Uint8Array
encode self input
= liftDOM
((self ^. jsf "encode" [toJSVal input]) >>= fromJSValUnchecked)
| < -US/docs/Web/API/TextEncoder.encode Mozilla TextEncoder.encode documentation >
encode_ ::
(MonadDOM m, ToJSString input) =>
TextEncoder -> Maybe input -> m ()
encode_ self input
= liftDOM (void (self ^. jsf "encode" [toJSVal input]))
| < -US/docs/Web/API/TextEncoder.encoding Mozilla TextEncoder.encoding documentation >
getEncoding ::
(MonadDOM m, FromJSString result) => TextEncoder -> m result
getEncoding self
= liftDOM ((self ^. js "encoding") >>= fromJSValUnchecked)
|
18b780721b7ea9c3781bbb60063b8b40671814f18dd63c20193c1d7c25ac6b44 | input-output-hk/project-icarus-importer | Property.hs | {-# LANGUAGE RankNTypes #-}
-- | Helpers for 'BlockProperty'.
module Test.Pos.Block.Property
( blockPropertySpec
) where
import Universum
import Test.Hspec (Spec)
import Test.Hspec.QuickCheck (prop)
import Pos.Configuration (HasNodeConfiguration)
import Pos.Core (HasConfiguration)
import Pos.Delegation (HasDlgConfiguration)
import Pos.Ssc.Configuration (HasSscConfiguration)
import Test.Pos.Block.Logic.Mode (BlockProperty, blockPropertyTestable)
| Specialized version of ' prop ' function from ' hspec ' .
blockPropertySpec ::
(HasNodeConfiguration, HasDlgConfiguration, HasSscConfiguration)
=> String
-> (HasConfiguration => BlockProperty a)
-> Spec
blockPropertySpec description bp = prop description (blockPropertyTestable bp)
| null | https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/generator/test/Test/Pos/Block/Property.hs | haskell | # LANGUAGE RankNTypes #
| Helpers for 'BlockProperty'. |
module Test.Pos.Block.Property
( blockPropertySpec
) where
import Universum
import Test.Hspec (Spec)
import Test.Hspec.QuickCheck (prop)
import Pos.Configuration (HasNodeConfiguration)
import Pos.Core (HasConfiguration)
import Pos.Delegation (HasDlgConfiguration)
import Pos.Ssc.Configuration (HasSscConfiguration)
import Test.Pos.Block.Logic.Mode (BlockProperty, blockPropertyTestable)
| Specialized version of ' prop ' function from ' hspec ' .
blockPropertySpec ::
(HasNodeConfiguration, HasDlgConfiguration, HasSscConfiguration)
=> String
-> (HasConfiguration => BlockProperty a)
-> Spec
blockPropertySpec description bp = prop description (blockPropertyTestable bp)
|
63014e7aadbd71d9ae27f3cf5dfd221ff6e01455b2e9c874850d55c722be4970 | LexiFi/csml | tast.ml | This file is released under the terms of an MIT - like license .
(* See the attached LICENSE file. *)
Copyright 2016 by LexiFi .
type cs_bind = Ast.cs_bind
type flags = Ast.flags
type typ =
| Int
| Int64
| Double
| Single
| Date
| String
| Bool
| ML2CS_T of string * string * pmanifest
| CS2ML_T of string * string * string * pcs_manifest * string
| List of typ
| Array of typ
| Tuple of typ list
| Option of typ
| Nullable of typ
| Arrow of typ list * typ option
| Exn
| Blob
| IntPtr
| Variant
| Variantized of string * string * string * string * string
| Weak of Lexer.loc Misc.physical_ref * typ
and pmanifest =
| PSumType of bool * (string * string * precord) list
| PRecordType of bool * precord
| PAbstract
and precord = (bool * string * string * typ Lazy.t Misc.physical_ref) list
and parrow = typ list * typ option
and pclass_component =
| PMLClass_method of string * string * parrow * cs_bind
| PMLClass_inline of string * string * string
and pcs_manifest =
| PCs_enum of string list * bool
| PCs_abstract
| PCs_mlclass of (typ option * pclass_component list) option Misc.physical_ref
| PCs_as_int
type mldecl =
| PModule of string * mldecl list
| PType of string * string * pcs_manifest * string * string
| PValue of (string * string * parrow * cs_bind)
| PMLInline of string
type csdecl =
| PNamespace of string * csdecl list
| PClass of csclass
| PCSInline of string
| PCSScope of Ast.cs_scope * csdecl list
and csclass = flags * string * (string * pmanifest) option * csfield list
and csfield =
| PNestedClass of csclass
| PMethod of string * flags * string * parrow * Ast.ml_kind
| PConstructor of string * flags * string * parrow * Ast.ml_kind
| PProperty of flags * string * typ option * typ *
(string * Ast.ml_kind) option * (string * Ast.ml_kind) option
| PCSInlineClass of string
| PCSScopeClass of Ast.cs_scope * csfield list
type tidl = {
tml: (string * string * mldecl list) list;
tcs: (string * csdecl list) list;
cs2ml_arrows: (typ list * typ option * string) list;
ml2cs_arrows: (typ list * typ option * string) list;
idl: Ast.idl;
}
open Pp.Operators
let comma = Pp.list ~sep:~~","
let rec dump_type = function
| Int -> ~~"Int"
| Int64 -> ~~"Int64"
| Double -> ~~"Double"
| Single -> ~~"Single"
| String -> ~~"String"
| Bool -> ~~"Bool"
| Date -> ~~"Date"
| ML2CS_T (cs,ml,_) -> ~~"(cs:%s <- ml:%s)" cs ml
| CS2ML_T (cs,ml,_,_,_) -> ~~"(cs:%s -> ml:%s)" cs ml
| IntPtr -> ~~"IntPtr"
| List t -> ~~"List(%t)" (dump_type t)
| Array t -> ~~"Array(%t)" (dump_type t)
| Tuple tl -> ~~"Tuple(%t)" (comma dump_type tl)
| Option t -> ~~"Option(%t)" (dump_type t)
| Nullable t -> ~~"Nullable(%t)" (dump_type t)
| Arrow (tl,None) -> ~~"Arrow(%t -> unit)" (comma dump_type tl)
| Arrow (tl,Some t) -> ~~"Arrow(%t -> %t)" (comma dump_type tl) (dump_type t)
| Exn -> ~~"Exn"
| Blob -> ~~"Blob"
| Variant -> ~~"Variant"
| Variantized (cs,ml,_,_,_) -> ~~"Variantized(cs:%s <-> ml:%s)" cs ml
| Weak (_, t) -> ~~"Weak(%t)" (dump_type t)
let string_of_type t =
let open Pp in
to_string ({width=1000; indent=0}, dump_type t)
| null | https://raw.githubusercontent.com/LexiFi/csml/1bdffc60b937b0cd23730589b191940cd1861640/src/tast.ml | ocaml | See the attached LICENSE file. | This file is released under the terms of an MIT - like license .
Copyright 2016 by LexiFi .
type cs_bind = Ast.cs_bind
type flags = Ast.flags
type typ =
| Int
| Int64
| Double
| Single
| Date
| String
| Bool
| ML2CS_T of string * string * pmanifest
| CS2ML_T of string * string * string * pcs_manifest * string
| List of typ
| Array of typ
| Tuple of typ list
| Option of typ
| Nullable of typ
| Arrow of typ list * typ option
| Exn
| Blob
| IntPtr
| Variant
| Variantized of string * string * string * string * string
| Weak of Lexer.loc Misc.physical_ref * typ
and pmanifest =
| PSumType of bool * (string * string * precord) list
| PRecordType of bool * precord
| PAbstract
and precord = (bool * string * string * typ Lazy.t Misc.physical_ref) list
and parrow = typ list * typ option
and pclass_component =
| PMLClass_method of string * string * parrow * cs_bind
| PMLClass_inline of string * string * string
and pcs_manifest =
| PCs_enum of string list * bool
| PCs_abstract
| PCs_mlclass of (typ option * pclass_component list) option Misc.physical_ref
| PCs_as_int
type mldecl =
| PModule of string * mldecl list
| PType of string * string * pcs_manifest * string * string
| PValue of (string * string * parrow * cs_bind)
| PMLInline of string
type csdecl =
| PNamespace of string * csdecl list
| PClass of csclass
| PCSInline of string
| PCSScope of Ast.cs_scope * csdecl list
and csclass = flags * string * (string * pmanifest) option * csfield list
and csfield =
| PNestedClass of csclass
| PMethod of string * flags * string * parrow * Ast.ml_kind
| PConstructor of string * flags * string * parrow * Ast.ml_kind
| PProperty of flags * string * typ option * typ *
(string * Ast.ml_kind) option * (string * Ast.ml_kind) option
| PCSInlineClass of string
| PCSScopeClass of Ast.cs_scope * csfield list
type tidl = {
tml: (string * string * mldecl list) list;
tcs: (string * csdecl list) list;
cs2ml_arrows: (typ list * typ option * string) list;
ml2cs_arrows: (typ list * typ option * string) list;
idl: Ast.idl;
}
open Pp.Operators
let comma = Pp.list ~sep:~~","
let rec dump_type = function
| Int -> ~~"Int"
| Int64 -> ~~"Int64"
| Double -> ~~"Double"
| Single -> ~~"Single"
| String -> ~~"String"
| Bool -> ~~"Bool"
| Date -> ~~"Date"
| ML2CS_T (cs,ml,_) -> ~~"(cs:%s <- ml:%s)" cs ml
| CS2ML_T (cs,ml,_,_,_) -> ~~"(cs:%s -> ml:%s)" cs ml
| IntPtr -> ~~"IntPtr"
| List t -> ~~"List(%t)" (dump_type t)
| Array t -> ~~"Array(%t)" (dump_type t)
| Tuple tl -> ~~"Tuple(%t)" (comma dump_type tl)
| Option t -> ~~"Option(%t)" (dump_type t)
| Nullable t -> ~~"Nullable(%t)" (dump_type t)
| Arrow (tl,None) -> ~~"Arrow(%t -> unit)" (comma dump_type tl)
| Arrow (tl,Some t) -> ~~"Arrow(%t -> %t)" (comma dump_type tl) (dump_type t)
| Exn -> ~~"Exn"
| Blob -> ~~"Blob"
| Variant -> ~~"Variant"
| Variantized (cs,ml,_,_,_) -> ~~"Variantized(cs:%s <-> ml:%s)" cs ml
| Weak (_, t) -> ~~"Weak(%t)" (dump_type t)
let string_of_type t =
let open Pp in
to_string ({width=1000; indent=0}, dump_type t)
|
148a54ffd5b1f3509364740de56b8c4331cd0ccefdb3f6d537e567c7757a338b | polytypic/rea-ml | Signatures.ml | type 'a ok = [`Ok of 'a]
type 'e error = [`Error of 'e]
type ('l, 'r) branch = [`Fst of 'l | `Snd of 'r]
type ('e, 'a) res = ['a ok | 'e error]
type ('d, 'c) cps = ('d -> 'c) -> 'c
type 'a op'1 = 'a -> 'a
type 'a op'2 = 'a -> 'a -> 'a
type 'a lazy_op'2 = (unit -> 'a) -> (unit -> 'a) -> 'a
(* *)
type nothing = |
(* *)
type ('R, +'e, +'a) s
type ('R, 'e, 'a, 'D) er = 'D -> ('R, 'e, 'a) s
(* *)
type ('R, 'e, 'a, 'b, 'D) map'm =
('b -> 'a) -> ('R, 'e, 'b, 'D) er -> ('R, 'e, 'a) s
class virtual ['R, 'D] map' =
object
method virtual map' : 'e 'a 'b. ('R, 'e, 'a, 'b, 'D) map'm
end
type ('R, 'e, 'a, 'D) pure'm = 'a -> ('R, 'e, 'a) s
class virtual ['R, 'D] pure' =
object
method virtual pure' : 'e 'a. ('R, 'e, 'a, 'D) pure'm
end
type ('R, 'e, 'a, 'b, 'D) pair'm =
('R, 'e, 'a, 'D) er -> ('R, 'e, 'b, 'D) er -> ('R, 'e, 'a * 'b) s
class virtual ['R, 'D] pair' =
object
method virtual pair' : 'e 'a 'b. ('R, 'e, 'a, 'b, 'D) pair'm
end
type ('R, 'e, 'a, 'b, 'c, 'D) branch'm =
('R, 'e, 'b -> 'a, 'D) er ->
('R, 'e, 'c -> 'a, 'D) er ->
('R, 'e, ('b, 'c) branch, 'D) er ->
('R, 'e, 'a) s
class virtual ['R, 'D] branch' =
object
method virtual branch' : 'e 'a 'b 'c. ('R, 'e, 'a, 'b, 'c, 'D) branch'm
end
type ('R, 'e, 'a, 'b, 'D) bind'm =
('R, 'e, 'b, 'D) er -> ('b -> ('R, 'e, 'a, 'D) er) -> ('R, 'e, 'a) s
class virtual ['R, 'D] bind' =
object
method virtual bind' : 'e 'a 'b. ('R, 'e, 'a, 'b, 'D) bind'm
end
type ('R, 'e, 'a, 'D) zero'm = ('R, 'e, 'a) s
class virtual ['R, 'D] zero' =
object
method virtual zero' : 'e 'a. ('R, 'e, 'a, 'D) zero'm
end
type ('R, 'e, 'a, 'D) alt'm =
('R, 'e, 'a, 'D) er -> ('R, 'e, 'a, 'D) er -> ('R, 'e, 'a) s
class virtual ['R, 'D] alt' =
object
method virtual alt' : 'e 'a. ('R, 'e, 'a, 'D) alt'm
end
type ('R, 'e, 'a, 'D) fail'm = 'e -> ('R, 'e, 'a) s
class virtual ['R, 'D] fail' =
object
method virtual fail' : 'e 'a. ('R, 'e, 'a, 'D) fail'm
end
type ('R, 'e, 'f, 'a, 'b, 'D) tryin'm =
('f -> ('R, 'e, 'a, 'D) er) ->
('b -> ('R, 'e, 'a, 'D) er) ->
('R, 'f, 'b, 'D) er ->
('R, 'e, 'a) s
class virtual ['R, 'D] tryin' =
object
method virtual tryin' : 'e 'f 'a 'b. ('R, 'e, 'f, 'a, 'b, 'D) tryin'm
end
type ('R, 'e, 'a, 'b, 'D) par'm = ('R, 'e, 'a, 'b, 'D) pair'm
class virtual ['R, 'D] par' =
object
method virtual par' : 'e 'a 'b. ('R, 'e, 'a, 'b, 'D) par'm
end
type ('R, 'e, 'a, 'D) suspend'm = (('e, 'a) res, unit) cps -> ('R, 'e, 'a) s
class virtual ['R, 'D] suspend' =
object
method virtual suspend' : 'e 'a. ('R, 'e, 'a, 'D) suspend'm
end
type ('R, 'e, 'D) spawn'm = ('R, nothing, unit, 'D) er -> ('R, 'e, unit) s
class virtual ['R, 'D] spawn' =
object
method virtual spawn' : 'e. ('R, 'e, 'D) spawn'm
end
class virtual ['R, 'D] functr' =
object
inherit ['R, 'D] map'
end
class virtual ['R, 'D] pointed' =
object
inherit ['R, 'D] map'
inherit ['R, 'D] pure'
end
class virtual ['R, 'D] product' =
object
inherit ['R, 'D] map'
inherit ['R, 'D] pair'
end
class virtual ['R, 'D] applicative' =
object
inherit ['R, 'D] pointed'
inherit ['R, 'D] pair'
end
class virtual ['R, 'D] selective' =
object
inherit ['R, 'D] applicative'
inherit ['R, 'D] branch'
end
class virtual ['R, 'D] monad' =
object
inherit ['R, 'D] selective'
inherit ['R, 'D] bind'
end
class virtual ['R, 'D] plus' =
object
inherit ['R, 'D] zero'
inherit ['R, 'D] alt'
end
class virtual ['R, 'D] errors' =
object
inherit ['R, 'D] fail'
inherit ['R, 'D] tryin'
end
class virtual ['R, 'D] sync' =
object
inherit ['R, 'D] monad'
inherit ['R, 'D] errors'
end
class virtual ['R, 'D] async' =
object
inherit ['R, 'D] sync'
inherit ['R, 'D] suspend'
inherit ['R, 'D] par'
inherit ['R, 'D] spawn'
end
| null | https://raw.githubusercontent.com/polytypic/rea-ml/56235733ada478f266f666db229bb6b0ae2ff80b/src/main/Rea/Signatures.ml | ocaml | type 'a ok = [`Ok of 'a]
type 'e error = [`Error of 'e]
type ('l, 'r) branch = [`Fst of 'l | `Snd of 'r]
type ('e, 'a) res = ['a ok | 'e error]
type ('d, 'c) cps = ('d -> 'c) -> 'c
type 'a op'1 = 'a -> 'a
type 'a op'2 = 'a -> 'a -> 'a
type 'a lazy_op'2 = (unit -> 'a) -> (unit -> 'a) -> 'a
type nothing = |
type ('R, +'e, +'a) s
type ('R, 'e, 'a, 'D) er = 'D -> ('R, 'e, 'a) s
type ('R, 'e, 'a, 'b, 'D) map'm =
('b -> 'a) -> ('R, 'e, 'b, 'D) er -> ('R, 'e, 'a) s
class virtual ['R, 'D] map' =
object
method virtual map' : 'e 'a 'b. ('R, 'e, 'a, 'b, 'D) map'm
end
type ('R, 'e, 'a, 'D) pure'm = 'a -> ('R, 'e, 'a) s
class virtual ['R, 'D] pure' =
object
method virtual pure' : 'e 'a. ('R, 'e, 'a, 'D) pure'm
end
type ('R, 'e, 'a, 'b, 'D) pair'm =
('R, 'e, 'a, 'D) er -> ('R, 'e, 'b, 'D) er -> ('R, 'e, 'a * 'b) s
class virtual ['R, 'D] pair' =
object
method virtual pair' : 'e 'a 'b. ('R, 'e, 'a, 'b, 'D) pair'm
end
type ('R, 'e, 'a, 'b, 'c, 'D) branch'm =
('R, 'e, 'b -> 'a, 'D) er ->
('R, 'e, 'c -> 'a, 'D) er ->
('R, 'e, ('b, 'c) branch, 'D) er ->
('R, 'e, 'a) s
class virtual ['R, 'D] branch' =
object
method virtual branch' : 'e 'a 'b 'c. ('R, 'e, 'a, 'b, 'c, 'D) branch'm
end
type ('R, 'e, 'a, 'b, 'D) bind'm =
('R, 'e, 'b, 'D) er -> ('b -> ('R, 'e, 'a, 'D) er) -> ('R, 'e, 'a) s
class virtual ['R, 'D] bind' =
object
method virtual bind' : 'e 'a 'b. ('R, 'e, 'a, 'b, 'D) bind'm
end
type ('R, 'e, 'a, 'D) zero'm = ('R, 'e, 'a) s
class virtual ['R, 'D] zero' =
object
method virtual zero' : 'e 'a. ('R, 'e, 'a, 'D) zero'm
end
type ('R, 'e, 'a, 'D) alt'm =
('R, 'e, 'a, 'D) er -> ('R, 'e, 'a, 'D) er -> ('R, 'e, 'a) s
class virtual ['R, 'D] alt' =
object
method virtual alt' : 'e 'a. ('R, 'e, 'a, 'D) alt'm
end
type ('R, 'e, 'a, 'D) fail'm = 'e -> ('R, 'e, 'a) s
class virtual ['R, 'D] fail' =
object
method virtual fail' : 'e 'a. ('R, 'e, 'a, 'D) fail'm
end
type ('R, 'e, 'f, 'a, 'b, 'D) tryin'm =
('f -> ('R, 'e, 'a, 'D) er) ->
('b -> ('R, 'e, 'a, 'D) er) ->
('R, 'f, 'b, 'D) er ->
('R, 'e, 'a) s
class virtual ['R, 'D] tryin' =
object
method virtual tryin' : 'e 'f 'a 'b. ('R, 'e, 'f, 'a, 'b, 'D) tryin'm
end
type ('R, 'e, 'a, 'b, 'D) par'm = ('R, 'e, 'a, 'b, 'D) pair'm
class virtual ['R, 'D] par' =
object
method virtual par' : 'e 'a 'b. ('R, 'e, 'a, 'b, 'D) par'm
end
type ('R, 'e, 'a, 'D) suspend'm = (('e, 'a) res, unit) cps -> ('R, 'e, 'a) s
class virtual ['R, 'D] suspend' =
object
method virtual suspend' : 'e 'a. ('R, 'e, 'a, 'D) suspend'm
end
type ('R, 'e, 'D) spawn'm = ('R, nothing, unit, 'D) er -> ('R, 'e, unit) s
class virtual ['R, 'D] spawn' =
object
method virtual spawn' : 'e. ('R, 'e, 'D) spawn'm
end
class virtual ['R, 'D] functr' =
object
inherit ['R, 'D] map'
end
class virtual ['R, 'D] pointed' =
object
inherit ['R, 'D] map'
inherit ['R, 'D] pure'
end
class virtual ['R, 'D] product' =
object
inherit ['R, 'D] map'
inherit ['R, 'D] pair'
end
class virtual ['R, 'D] applicative' =
object
inherit ['R, 'D] pointed'
inherit ['R, 'D] pair'
end
class virtual ['R, 'D] selective' =
object
inherit ['R, 'D] applicative'
inherit ['R, 'D] branch'
end
class virtual ['R, 'D] monad' =
object
inherit ['R, 'D] selective'
inherit ['R, 'D] bind'
end
class virtual ['R, 'D] plus' =
object
inherit ['R, 'D] zero'
inherit ['R, 'D] alt'
end
class virtual ['R, 'D] errors' =
object
inherit ['R, 'D] fail'
inherit ['R, 'D] tryin'
end
class virtual ['R, 'D] sync' =
object
inherit ['R, 'D] monad'
inherit ['R, 'D] errors'
end
class virtual ['R, 'D] async' =
object
inherit ['R, 'D] sync'
inherit ['R, 'D] suspend'
inherit ['R, 'D] par'
inherit ['R, 'D] spawn'
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.